Resumos Python
Resumos Python
Converting into strings: Converting into ints: Converting floats into ints:
str(1+2) 100 + int('33') int(2.78)
='3'
=133 =2
• Variable names may include both letters and digits, but they must
begin with a letter.
Input functions:
• name = input("What's your name? ")
• age = int(input(‘Enter your age: ‘)) #if it´s not a string you must
convert
Presenting outputs:
• To write multiple lines, add the ‘\n’ character:
print("Hello World\nThis is a message")
• Use sep= and end= to change how arguments are separated and
terminated in the output.
print(..., sep=' ',end='\n')
Traversing strings:
index = 0
fruit = 'banana' #b
while index < len(fruit):
for char in fruit: #a
letter = fruit[index]
print(char) #n
print(letter)
#a
index = index + 1
#n
#a
Formating:
• '{:*>10}'.format('test') #-> '******test'
• '{:04d}'.format(42) #-> '0042'
• '{:5.2f}'.format(3.2451) #-> ' 3.25'
• print('{:4d}{:4d}{:4d}'.format(10,20,30)) #-> 10 20 30
• print(f'{10:4d}{20:4d}{30:4d}') #-> 10 20 30
Import math:
Boolean expression:
• A boolean expression is an expression that is either true or false.
>>> n = 5 # this IS NOT a boolean expression!
>>> n == 5 # this IS a boolean expression! True
>>> 6 == n # this is another boolean expression. False
Lists:
numbers = [10, 20, 30, 40]
Exemplos
fruits = ['banana', 'pear', 'orange']
de listas
empty = [] # an empty list
things = ['spam', 2.0, [1, 2]] # a list inside a list!
• len(numbers) #-> 4
• numbers[0] #-> 10
• numbers[-1] #-> 40
• numbers[1:3] #-> [20, 30]
• numbers[0:4:2] #-> [10, 30] (step = 2)
• s = [1, 2, 3] + [7, 7] #-> [1, 2, 3, 7, 7]
• s2 = [1, 2, 3]*2 #-> [1, 2, 3, 1, 2, 3]
• s3 = 3*[0] #-> [0, 0, 0]
• 7 in s #-> True
• 4 not in s #-> True
• sum(s) #-> 20
• min(s) #-> 1
• max(s) #-> 7
• numbers[1] = 99 #->[10,99,30,40]
#banana
#pear
#orange
Traversing lists:
for f in fruits:
print(f)
-------------------------------------------------------------------------------
for i in range(len(fruits)):
print(i, fruits[i])
-------------------------------------
#0 banana
i=0
while i < len(numbers): #1 pear
print(i, fruits[i])
#2 orange
i += 1
------------------------------------
for i, f in enumerate(fruits):
print(i, f)
Tuples: (tuples are immutable)
t = ('a', 'b', 'c', 'd', 'e') #exemplo de um tuple
• t = tuple('ape') # t → ('a', 'p', 'e')
• t = tuple([1, 2]) # t → (1, 2)
Tuples and lists:
s = 'abc'
t = [4, 3, 2]
list(zip(s, t)) # → [('a', 4), ('b', 3), ('c', 2)]
-------------------------------------------------------------------------
enumerate('abc') # → (0, 'a'), (1, 'b'), (2, 'c')
------------------------------------------------------------------------
s = 'somestuff'
for i, c in enumerate(s):
print(i, c) #(0,s),(1,o),(2,m),etc.
Sets (not sliceable)
fruits = {'pear', 'apple', 'banana', 'orange'}
S = { x for x in fruits if x<'c' }
• numbers = set([3, 1, 3]) #-> {1, 3}
• empty = set()
• {1, 2, 1} == {1, 2} #-> True
• len({4, 5, 4, 5, 5}) #-> 2
• S = {23, 5, 12}
• 5 in S # True
• {3,4,5} & {1,2,3} #-> {3}
• {3,4,5} | {1,2,3} #-> {1,2,3,4,5}
• {3,4,5} - {1,2,3} #-> {4,5}
• {3,4,5} ^ {1,2,3} #-> {1,2,4,5}
• S = {1,2,3}
• S.add(4) # S -> {1,2,3,4}
• S.remove(2) # S -> {1,3,4}
• S.discard(7) # No error!
Dictionaries (not sliceable)
• eng2sp={'one': 'uno', 'two': 'dos', 'three': 'tres'}
• shop = {'eggs': 12, 'sugar': 1.0, 'coffee': 3}
• shop['sugar'] #-> 1.0
• eng2sp['two'] #-> 'dos'
• shop['bread'] = 6 # Add a new key-value association
• shop['eggs'] = 24 # Change the value for an existing key
• The len function returns the number of key-value pairs.
• 'two' in eng2sp #-> True ('two' is a key)
• 'uno' in eng2sp #-> False ('uno' is not a key)
• 'uno' in eng2sp.values() #-> True
• d.keys() #-> [10, 20, 1000]
• d.values() #-> ['dez', 'vinte', 'mil']
• d.items() #-> [(10, 'dez'), (20, 'vinte'), (1000, 'mil')]
• d[10] #-> 'dez'
• d[0] #-> KeyError
• d.get(10) #-> 'dez' (same as d[10])
• d.get(0) #-> None (no error!)
• d.get(0, 'nada') #-> 'nada' (no error)
• 0 in d #-> False (.get did not change d)
• d.setdefault(0, 'nada') #-> 'nada'
• 0 in d #-> True(set changes d)
• x = d.pop(10) #-> x == 'dez’ # {20:'vinte', 1000: 'mil'}
• del d[20] # {1000:'mil'}
• t = d.popitem() #-> (1000,'mil') #removes the last item inserted
Transversing dictionary:
shop = {'eggs':24, 'bread':6,'coffee':3, 'sugar':1.0}
for k in shop:
print(k, shop[k])
-------------------------------
for k in shop.keys():
print(k, shop[k])
-----------------------------
for k, v in shop.items():
print(k, v)
----------------------
message = 'parrot'
d = dict()
for c in message:
if c not in d:
d[c] = 1
else:
d[c] += 1
List comprehensions:
nums= [4, -5, 3, 7, 2, 3, 1]
nums2 = [ v**2 for v in nums ]
args = ['apple', 'dell', 'ibm', 'hp', 'sun']
d = { a: len(a) for a in args } #-> {'apple': 5, 'ibm': 3, 'hp': 2, ...}
sum( x/2 for x in nums if x%2==0 ) #-> 3.0
all( x>0 for x in nums ) #-> False
tuple( v for v in nums if v<3 ) #-> (-5, 2, 1)
Sorting:
• L.sort() # Modifies list L in-place
• L2 = sorted(L) # Creates L2. L is not modified!
• sorted('banana') #-> ['a', 'a', 'a', 'b', 'n', 'n']
• print(sorted(L, key=len)) # sort by length #-> ['nuno', 'Mario',
'Carla', 'Maria', 'anabela']
• To reverse the order, use the reverse=True argument.
• dates = [(1910, 10, 5, 'Republic'),
(1974, 4, 25, 'Liberty'),
(1640, 12, 1, 'Independence')]
• print(sorted(dates)) # "lexicographic" order
• sorted(dates, key=lambda t: t[3]) # by name
• sorted(dates, key=lambda t:(t[1],t[2])) # by month,day
Other functions:
• max(x1,x2) #gives you the biggest number
• Assert len(m)>8 #In Python, the assert statement is used to
continue the execute if the given condition evaluates to True. If
the assert condition evaluates to False, then it raises the
AssertionError exception with the specified error message.
• random.randrange(0,101) #Pick a random number between 1 and
100, inclusive
• b = a.copy() # clone a
Classes:
• class Myclass1: #to create/define a class
•