You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
print("073", "928", "375", sep=".", end="-")
print(18)
print('This is a \'string\' (str)') # We can use double quotesprint("This is a 'string' (str)")
# Ignoring escape characters with 'r' in front of the stringprint(r"This is also \n a string")
name="Joaquim"age=18print(f'This is my name: {name}'f', and this is my age: {age}')
Data Types
str - string -> texts
int - integer -> integer numbers
float - floating point -> real numbers
bool - boolean - logic values
# We can see the type of some value using the 'type' functionprint('Joaquim', type('Joaquim'))
print(13, type(13))
print(13.0, type(13.0))
print(13==13, type(13==13))
print("\n")
# Type casting# There's truthy and falsy valuesprint('joaquim', type('joaquim'), bool('joaquim'))
print(type(int('10')))
Arithmetic Operators
+ -> Plus
- -> Minus
* -> Times
/ -> Quotient
// -> Integer quotient
** -> Power
% -> Modulus
()
print('Times (*), 10 * 10 =', 10*10)
print('Plus (+), 10 + 10 =', 10+10)
print('Minus (-), 10 - 5 =', 10-5)
print('Division (/), 10 / 2 =', 10/2)
# * can be used as a repeat operator to repeat stringsprint('Joaquim'*3)
# We can use type casting to concatenate different data typesprint('Joaquim is '+str(18) +' years old.')
# Division without restprint(10.7//5)
print(2**10)
print(10%3)
Variables:
Start with letter, can contain numbers, separate with _, lowercase letters
name='Joaquim'age=18height=1.76is_of_age=age>=18# boolweight=100imc=weight/ (height**2)
print(name, 'is', age, 'years old and his imc is', imc)
Print Variables
name='Joaquim'age=18height=1.76is_of_age=age>=18weight=100imc=weight/ (height**2)
## 'format' functionprint(name, 'is', age, 'years old and his imc is', imc)
print(f'{name} is {age} years old and his imc is {imc:.2f}')
# We can use variables anywhere using its indexprint('IMC = {2:.0f}. {0} is {1} years old and his imc is {2:.2f}'.format(
name, age, imc))
# We can give aliases to the variablesprint('IMC = {im:.0f}. {n} is {a} years old and his imc is {im:.2f}'.format(
n=name, a=age, im=imc))
Data Input
input function
name=input("What is your name? ")
age=input("What is your age? (years) ")
year_of_birth=2021-int(age)
# Notice that we can ommit the comma in the print functionprint(f"{name} is {age} years old. "f"{name} was born in {year_of_birth}")
Conditions
if, elif e else
You can use relational operators:
’==’, ‘>’, ‘>=’, ‘<’, ‘<=’, ‘!=’
You can use relational keywords:
‘and’, ‘or’, ‘not’, ‘in’, ‘not in’
You can use the ‘pass’ keyword as a placeholder
if2>=3and1==1:
print("True.")
elifnotFalse:
print("Now it's true.")
elif1>2or3<4:
passelse:
print("It's not true.")
# Short hand if .. elsea=2b=330print("A") ifa>belseprint("=") ifa==belseprint("B")
name="Joaquim Gregório"if"uim"inname:
print("There's 'uim' in your name.")
if"w"notinname:
print("There's no 'w' character in your name.")
:(character)(> or < or ^)(quantity)(type - s, d or f)
> -> Left
< -> Right
^ -> Center
num_1=10num_2=3quotient=num_1/num_2print('{:.2f}'.format(quotient)) # 2 decimal placesprint(f'{quotient:.2f}') # 2 decimal placesnum_1=1print(f'{num_1:0>10}') # on the leftnum_2=1150print(f'{num_2:0<10}') # on the rightnum_3=1233print(f'{num_3:0^10}') # on the centernum_4=3455print(f'{num_4:0>10.2f}')
name='Joaquim Gregório'print(len(name))
print(f'{name:#^50}')
formated_name='{:@>50}'.format(name)
print(formated_name)
name='Joaquim Gregório'# name = name.ljust(30, '#')print(name.lower())
print(name.upper())
print(name.title())
String Manipulation
String indexes (supports either positive and negative indexes)
String slicing [beginning:end:pass]
Built-in functions len, abs, type, print, etc…
These functions can be used directly in each type
text="Python_s2"# [012345678] and -[987654321] as indexes# print(text[-2])url="www.gentoo.org/"print(url[4:-1]) # slicingnew_text=text[:6]
new_text_2=text[7:]
print(new_text, new_text_2)
print(text[:-2])
# [beginning:end:pass]print(text[::2]) # jumping 2 characters in all the stringprint(text[0:6:2]) # from 0 till 6 jumping 2 characters (ignoring one character)forcharintext:
print(char)
While
Keywords
Functionality
continue
jumps one loop cycle
break
ends the loop
Syntax
x=0whilex<5:
ifx%2==0:
x+=1continueprint(x)
x+=1
While Else
Else code block is executed if when condition is false
x=1y=1whilex<=100:
ifx==7:
break# since here the while condition is already trueprint(x, y)
x+=yy+=1else: # is execute if the while condition is falseprint("Else after while")
Iterating Over Strings
sentence="o rato roeu a roupa do rei de roma"sentence_size=len(sentence)
counting=0new_sentence=""whilecounting<sentence_size:
# print(sentence[counting], counting)character=sentence[counting]
ifcharacter=="r":
new_sentence+="R"else:
new_sentence+=charactercounting+=1print("new sentence:", new_sentence)
Else is called when the loop ends without breaking (break)
list1= ["sJoaquim", "André", "Carlos"]
forelinlist1:
print(el)
ifel.lower().startswith("j"):
breakelse:
print("There's no word which starts with J.")
Lists
Some functions:
Syntax
Functionality
append(el)
Adds an element at the end of the list
clear()
Removes all the elements from the list
copy()
Returns a copy of the list
count()
Returns the number of elements with the specified value
extend()
Add any iterable to the end of the current list
index()
Returns the index of the first element with the specified value
insert(i, el)
Adds an element at the specified position
pop(i?)
Removes the element at the specified position
remove()
Removes the item with the specified value
reverse()
Reverses the order of the list
sort()
Sorts the list
min()
Returns the smallest element in the list
max()
Returns the biggest element
del
Keyword. Used to delete an element, range or the entire list
list
Class that converts any iterable to a list
List Slicing
list1=list(("a", "b", "c", "d", "e", "f", 1, 2, False))
forelinlist1:
print(el)
l1=list(range(1, 7))
l1.append(7)
l1.insert(0, 8)
dell1[1]
dell1[3:5]
print(l1)
print(max(l1))
print(min(l1))
l2= ["a", "ab", "abc", "abcd", "abcde"]
print(max(l2))
print(min(l2))
l3= ["String", True, 10, -20.5]
foreleminl3:
print(f"The type of elem is {type(elem)} and its value is {elem}")
List Comprehension
[print(el) forelinl3]
fruits= ["apple", "banana", "cherry", "kiwi", "mango"]
newlist= [xforxinfruitsif"a"inx]
# General syntax: newlist = [expression for item in iterable if condition == True]# expression can be whatever you want
Hangman Game
secret="hello"typed= []
chances=3whileTrue:
ifchances==0:
print("You lose!")
breakletter=input("Type a letter: ")
iflen(letter) >1:
print("Type only one letter!")
chances-=1continuetyped.append(letter)
ifletterinsecret:
print(f'Nice, the letter "{letter}" is in the secret word.')
else:
print(f'Hurr, the letter "{letter}" isn\'t in the secret word.')
typed.pop()
chances-=1secret_buffer=""forsecret_letterinsecret:
ifsecret_letterintyped:
secret_buffer+=secret_letterelse:
secret_buffer+="*"ifsecret_buffer==secret:
print(f'\nNice, you won!!!\nThe secret word is "{secret_buffer}"')
breakelse:
print(secret_buffer)
print(f"You still have {chances} chances.")
Split, Join and Enumerate
Function
Functionality
split()
split a string
join()
join a list
enumerate()
enumerate elements of a list (iterables)
Split
string="O Brasil é o país do futebol, o Brasil é penta."list1=string.split(" ")
list2=string.split(",")
word=""counter=0forvalueinlist1:
occurrences=list1.count(value)
ifoccurrences>counter:
counter=occurrencesword=valueprint(f"The word that appeared most times is {word} ({counter}x)")
forvalueinlist2:
print(value.strip().capitalize())
Join
string2="O Brasil é penta."list3=string2.split(" ")
string3=",".join(list3)
print(string3)
Enumerate
string2="O Brasil é penta."list3=string2.split(" ")
fori, valueinenumerate(list3, 10):
print(i, value)
# This is exactly what enumerate() does, but it does it in a tuplelist4= [[0, "Joaquim"], [1, "Marcos"], [2, "Carlos"]]
fori, valueinlist4:
print(i, value)
list1= ["João", "Luis", "Maria", 1, 2, 3, 4, 5]
n1, n2, *other_list, last_value=list1# you can use *_ to ignore the restprint(n1, n2)
print(other_list)
print(last_value)
## Inverting variable valuesx=1y="a"print(f"x: {x}, y: {y}")
[x, y] = [y, x]
print(f"x: {x}, y: {y}")
x, y=y, xprint(f"x: {x}, y: {y}")
Ternary Operator
Syntax
logged_user=Falsemsg="User is logged in."iflogged_userelse"User needs to login."print(msg)
age=input("Type your age: ")
ifnotage.isnumeric():
print("Type only numbers.")
else:
age=int(age)
is_of_legal_age=age>=18msg2="Can access."ifis_of_legal_ageelse"Cannot access."print(msg2)
Expressions with OR operator
name=input("Type your name: ")
# "Old" way:# if name:# print(name)# else:# print("You didn't type anything.")# Ternary operator way:# msg = name or "You didn't type anything."# print(msg)# Short and "unreadable" wayprint(nameor"You didn't type anything.")
# 'msg' and 'name' have default valuesdefgreeting(msg: str="Hello", name: str="user") ->str:
"""Prints and returns some greeting."""print(msg, name)
returnf"{msg}{name}"greeting()
greeting("Hi", "Joaquim")
greeting(name="Marcos", msg="Nice to meet you")
Since we set a default value for an parameter, after that, the following parameters must have a default value too. The same pattern is valid for the arguments when calling a function.
deffunc(a, b, c="c", d=None):
# d must have a default valueprint(f"{a}, {b}, {c}, {d}")
# here we get an error:func(1, b=2, c="c", 3)
# the right way:func(1, b=2, d=3, c="c") # any order (b, d and c)
Args and Kwargs
deffunc(a, b, *args, **kwargs):
# arguments (args) and keyword arguments (kwargs)print(a, b)
print(args)
print(kwargs)
print(kwargs.get("age"))
# different from kwargs['age'], kwargs.get('age')# returns a value or None if key does not exist.func(1, 2, 3, 4, 5, name="Joaquim", lastname="Gregório")
# Unpacking when passing the arguments (valid for any iterable):list1= [1, 2, 3, 4, 5]
print(*list1, sep="-") # the same as: print(1, 2, 3, 4, 5)
Global Variables
Variables has a scope.
We can use a global variable, but to change its value we must call that global variable, otherwise, we will create another variable in the current scope with the same name of the global variable we refer to.
some_var="value"print(some_var)
deffunc():
globalsome_varsome_var="other value"# modifying global variable# now we have access to some_var which is a global variablefunc()
print(some_var) # has 'other value' as valuedeffunc1():
# here we get another error:print(some_var) # we must call global variable before use itglobalsome_varprint(some_var)
# error: some_var2 is used prior to global declaration
In tuples we cannot insert or remove elements and we cannot change their values. That’s why tuples are different from lists.
Tuple Methods
Method
Description
count(val)
Returns the number of times a specified value occurs in a tuple
index(val)
Returns the position of where the passed value was found
t1= (1,) # or just 't1 = 1,'t2= () # void tuplet3= (1, 2, 3, "a", "b", "c")
t4=6, 7, 8, "d", "e", "f"t5=t3+t4t6= ("a", 1) *4# repeat '"a", 1' four timesprint(t6)
# Modifying a tuplet7= ("a", "b", "c")
t7=list(t7)
t7.append("d")
t7=tuple(t7)
print(t7)
t8= (1, 2, 3)
item= (4,) # could be multiple itemst8+=itemprint(t8)
Dictionaries
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
Methods:
Method
Description
clear()
Removes all the elements from the dictionary
copy()
Returns a copy of the dictionary
fromkeys(keys, val?)
Returns a dictionary with the specified keys and value
get(key)
Returns the value of the specified key
items()
Returns a list containing a tuple for each key value pair
keys()
Returns a list containing the dictionary’s keys
pop(k, defaulvalue?)
Removes the element with the specified key
popitem()
Removes the last inserted key-value pair
setdefault(k, val?)
Returns the value of the specified key. If the key does
not exist: insert the key, with the specified value
update(iterable)
Updates the dictionary with the specified key-value pairs
values()
Returns a list of all the values in the dictionary
Syntax
d1= {"key": "key value", "key": "key value 2", "key": "key real value"}
d1["new_key"] ="new_key value"print(d1)
d2=dict(
key1="key1 value",
key2="key2 value",
)
# Accept immutable types as keys:d3= {"str": "value", 123: "other value", (1, 2, 3): "tuple as key"}
# Deleting a key:deld3["str"] # we can delete the hole dictprint(d3)
# Verify if a KEY exists:print("str"ind3) # or '"str" in d3.keys()'# Verify if a VALUE exists:print("other value"ind3.values())
# Verify number of paris (key:value)print(len(d3))
# Looping:d4= {
"key1": "key1 value",
"key2": "key2 value",
"key3": "key3 value",
"key4": "key4 value",
}
forkeyind4:
print(key, d4[key])
forvalueind4.values():
print(value)
forkey_valueind4.items():
print(key_value) # tuplesforkey, valueind4.items():
print(key, value)
More on Syntax and Dict Copy
importcopycustomers= {
"customer1": {"name": "Joaquim", "lastname": "Gregório"},
"customer2": {"name": "Marcos", "lastname": "Silva"},
}
forcustomer_k, customer_vincustomers.items():
print(f"Showing {customer_k}")
fordata_k, data_vincustomer_v.items():
print(f"\t{data_k}: {data_v}")
d1= {1: "a", 2: "b", 3: "c"}
v=d1# it's not a copyv[1] ="othe value"# it will change in both, v and d1print(d1)
print(v)
d2= {1: "a", 2: "b", 3: "c", 4: ["d", "e", "f"]}
v2=d2.copy() # now it's a shallow copy# Only tuples will not change# Check why it's a shallow copy:v2[4][0] ="D"# notice that it will change in d2 tooprint(d2[4], id(d2))
print(v2[4], id(v2))
# How to make a real copy:d3= {1: "a", 2: "b", 3: "c", 4: ["d", "e", "f"]}
v3=copy.deepcopy(d3) # independent copy# Check why it's a shallow copy:v3[4][0] ="D"# notice that it will not change in d3print(d3[4])
print(v3[4])
Generators and Iterators: you can get their values only once, using for..in loops or the next() function. When you access all their values, you cannot access it again.
Iterable
importsysimporttimelist1= [1, 2, 3, 4, 5]
# Doint the same thing that for..in does:list1=iter(list1) # Iteratorprint(next(list1))
print(next(list1))
print(next(list1))
print(next(list1))
print(hasattr(list1, "__iter__")) # verify iterableprint(hasattr(list1, "__next__")) # verify iteratorprint(sys.getsizeof(list1)) # size is a problem in big size variables
Generator
# Lazy evaluation:defgen(ran: int):
"""Generate values"""forvinrange(1, ran+1):
yieldf"Value {v}"time.sleep(0.1)
g=gen(10) # it's an iterator and an interableforving:
print(v)
Creating a Generator
l1= [xforxinrange(10000)] # listprint(type(l1))
l2= (xforxinrange(10000)) # 'best' way to create a generatorprint(type(l2))
# Now we have a big difference:print(sys.getsizeof(l1))
print(sys.getsizeof(l2))
forvinl2:
print(v, end="\r")
Zip and Zip Longest
Function
Description
zip
Join iterables. The size depends on the smaller iterable
zip_longest
Join iterables. The size depends on the larger iterable.
Has the fillvalue attribute which the default value is none.
Import from itertools module.
fromitertoolsimportzip_longest, countcities= ["São Paulo", "Belo Horizonte", "Salvador", "Monte Belo"]
states= ["SP", "MG", "BA"]
index=count()
states_and_cities=zip(index, states, cities)
forvalueinstates_and_cities:
print(value)
# print(dict(states_and_cities))# print(list(states_and_cities))index=count()
## We can ommit fillvaluestates_and_cities_long=zip_longest(index, states, cities, fillvalue="None value")
print(list(states_and_cities_long))
forvalueinstates_and_cities_long:
print(value) # infinity loop because of the `index` variable.
fromitertoolsimportgroupby, teestudents= [
{"name": "Joaquim", "grade": "A"},
{"name": "João", "grade": "B"},
{"name": "Maria", "grade": "B"},
{"name": "Márcia", "grade": "F"},
{"name": "Luiz", "grade": "D"},
{"name": "Mario", "grade": "A"},
{"name": "Carlos", "grade": "A"},
{"name": "Geraldo", "grade": "A"},
{"name": "Ronaldo", "grade": "B"},
{"name": "Cristina", "grade": "C"},
]
order=lambdaitem: item["grade"]
students.sort(key=order)
# you need to order the valures before use groupbyordered_students=groupby(students, order)
forgroup, students_groupinordered_students:
print(f"Group: {group}")
new_group, new_group2=tee(students_group) # make a copy because it is an iteratorlength=len(list(new_group))
print(f"\tThere is {length} students in this group.")
forstudentinnew_group2:
print(f"\t{student}")
fromdataimportproducts, people, list_1fromfunctoolsimportreduce# Sum a list of numbers:list_sum=reduce(lambdaac, i: i+ac, list_1, 0)
print(list_sum)
# Prices sum:prices_sum=reduce(lambdaac, p: p["price"] +ac, products, 0)
print(prices_sum)
Exceptions, Modules and Functions
Try, Except
try:
# a = []a= {}
print(a[1])
exceptNameErroraserr:
# this will take the specified errorprint("Some error occurred.")
except (IndexError, KeyError) aserr:
# this will take the specified errorprint("Some index or key error.")
exceptExceptionaserr:
# this will take any errorprint("Unexpected error.")
else:
# Executed when there's no errorprint("The code has no error.")
finally:
# Since this code block will always be executed,# you can handle the possible errors here.print("Finally is always executed.")
# You can use `raise` alone to raise the same error# or with an error classdefquotient(n1: int|float, n2: int|float):
ifint(n2) ==0:
raiseValueError("You cannot divide by zero.")
returnn1/n2try:
print(quotient(12.1, 0))
exceptValueErroraserr:
print(err)
defconvert_to_num(value):
try:
value=int(value)
returnvalueexceptValueError:
try:
value=float(value)
returnvalueexceptValueError:
passwhileTrue:
number=convert_to_num(input("Type some number: "))
ifnumber==None: # functions return None by defaultprint("Error: it's not a number.")
else:
print(number*2)
importsys# from sys import platform# Give the module some alias:fromsysimportplatformassoprint(so)
# NOTE: the following way can be confused:fromrandomimport*importrandomasrandforiinrange(10):
print(rand.randint(-1, 10), rand.random())
Creating Modules
Create calc.py in the same folder as main.py
calc.py
importmathPI=math.pidefduplicate_list(listx: list) ->list:
return [x*2forxinlistx]
defmultiply_list(listx: list[int] |list[float]):
r=1foriinlistx:
r*=ireturnr# The following code avoid the code inside the if confition being# executed by other file that is importing the current module, since# the variable __name__ is "__main__" only when we execute the file# directly, otherwise, the __name__ variable will be the module name# that is the file name. So, we can avoid the code inside if confition# being executed when we import this module in other file.if__name__=="__main__":
list1= [1, 2, 3, 4, 5]
print(duplicate_list(list1))
print(multiply_list(list1))
print(PI)
# __name__ only returns the module's name if that# module is being imported in other fileprint(__name__)
main.py
importcalc# it will execute all the code inside the module# if we don't use the if condition (if __name__ == "__main__") ...# the __name__ of the first file that is being executed will# always be "__main__"# print(__name__)print(calc.PI)
list1= [2, 4]
print(calc.multiply_list(list1))
Packages and Modules
Every folder which mean to be a module must have a file called __init__.py even it being a empty file.
Open for exclusive creation, failing if the file already exists
‘a’
Open for writing, appending to the end of the file if it exists
‘b’
Binary mode
‘t’
Text mode (default)
’+’
Open for updating (reading and writing)
Syntax and Open Function
file=open("demofile.txt", "w+")
file.write("Line 1\n")
file.write("Line 2\n")
file.write("Line 3\n")
# Since we are in the end of the file, we must seek for a relative position,# then we can read the file.file.seek(0, 0)
print("Reading lines...")
print(file.read())
print("###################")
file.seek(0, 0)
print(file.readline(), end="") # now the cursor is at the end of the line that was readprint(file.readline(), end="")
print(file.readline(), end="")
print("###################")
file.seek(0, 0)
print(file.readlines()) # list with the linesforlineinfile.readlines():
print(line, end="")
# Also works:forlineinfile:
print(line, end="")
file.close() # it`s mandatory to prevent problems
Using Context Managers
Better than using try...except...finally to handle files.
# This closes the file automaticallywithopen("demofile1.txt", "w+") asfile:
file.write("Line 1\n")
file.write("Line 2\n")
file.write("Line 3\n")
file.seek(0, 0)
print(file.read())
# Read mode:withopen("demofile.txt", "r") asfile:
print(file.read())
# Append mode:# 'a+' mode will append whatever you write without clear the file content
Deleting Files
importos# First, let's create some file:withopen("demofile2.txt", "w+") asfile:
file.write("Some line 1\n")
file.write("Some line 2\n")
file.write("Some line 3\n")
# Now we can delete the file:os.remove("demofile2.txt")
The problem is that mutable default values as parameters can point to the same place in the memory and then we can work with the same object without knowing it.
fromtypingimportIterable# def clients_list(clients_iterable: Iterable[str], listx: list = []):defclients_list(clients_iterable: Iterable[str], listx: list=None):
iflistxisNone:
listx= []
listx.extend(clients_iterable)
returnlistx# Or we can just pass the second argument as an empty listclients1=clients_list(["John", "Mary", "Stewart"], [])
clients2=clients_list(["Marcos", "Steve", "Bob"])
clients3=clients_list(["Joseph"])
print(clients1)
print(clients2)
Todo List
Add, List, Undo, Redo
defadd_task(task: str, todo_list: list):
todo_list.append(task)
print("Task added successfully!")
defshow_todo_list(todo_list: list):
print(f"There are {len(todo_list)} tasks:")
fori, taskinenumerate(todo_list, start=1):
i=f"{i}"iflen(str(i)) >1elsef"0{i}"print(f"\t{i} - {task}")
defundo_task_list(task_list: list, redo_list: list):
iflen(todo_list) ==0:
print("There's nothing to undo!")
returnredo_list.append(task_list.pop())
print("Undone!")
defredo_task_list(redo_list: list, task_list: list):
iflen(redo_list) ==0:
print("There's nothing to redo!")
returntask_list.append(redo_list.pop())
print("Redone!")
todo_list= []
redo_list= []
whileTrue:
print("What do you wanna do?")
action=input("(A)dd, L(ist), (U)ndo or (R)edo? ").upper()
iflen(action) >1:
print("Please type only one letter!")
continueelifaction=="A":
task=input("Type your task: ")
add_task(task, todo_list)
continueelifaction=="L":
show_todo_list(todo_list)
continueelifaction=="U":
undo_task_list(todo_list, redo_list)
continueelifaction=="R":
redo_task_list(redo_list, todo_list)
continueelse:
print("Type a valid letter!")