Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
20 views

Resumos Python

This document summarizes key Python concepts including: 1. Converting between data types like strings, integers and floats. 2. Taking user input and presenting outputs. 3. Common string methods and traversing strings. 4. Formatting strings and importing modules. 5. Boolean expressions, comparison operators, if/else statements and functions. 6. Common data structures like lists, tuples, sets and dictionaries. 7. Traversing and modifying these structures. 8. List and dictionary comprehensions. 9. Sorting data.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Resumos Python

This document summarizes key Python concepts including: 1. Converting between data types like strings, integers and floats. 2. Taking user input and presenting outputs. 3. Common string methods and traversing strings. 4. Formatting strings and importing modules. 5. Boolean expressions, comparison operators, if/else statements and functions. 6. Common data structures like lists, tuples, sets and dictionaries. 7. Traversing and modifying these structures. 8. List and dictionary comprehensions. 9. Sorting data.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

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')

Strings: (strings are immutable)


• len(fruit) #-> 6
• fruit[1] #-> 'r'
• fruit[3:5] #-> 'ng'
• name = 'tom' + 'cat' #-> 'tomcat'
• gps = 2 * 'tom' #-> 'tomtom'
• fruit.upper() #-> 'ORANGE'
• fruit.replace('a', 'A') #-> 'orAnge'
• fruit.capitalize() #->”Orange”

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

• Boolean values may be stored in variables.


>>> isEven = n%2==0
• Null and empty values convert to False: (non empty convert to true)
>>> bool(0) # False
>>> bool(1) # True
>>> bool('') # False
>>> bool([False]) #True
Relation and logical operators:
• x == y # x is equal to y
• x != y # x is not equal to y
• x > y # x is greater than y
• x < y # x is less than y
• x >= y # x is greater than or equal to y
• x <= y # x is less than or equal to y
• x < y < z # x is less than y and y is less than z (cool!)
• There are three logical operators: and, or, not.
If function:
• if x < 10: mark = 'Poor'
elif x < 13: mark = 'Reasonable'
elif x < 17: mark = 'Good'
else: mark = 'Excelent'
• n = int(input("number? "))
msg = "odd" if n%2!=0 else "even"
print(n, "is", msg)
• The exit() function can be used to exit the if function
Functions:
• def square(x):
y = x**2
return y
print( square(2) + square(3) )

• You may need to process a function for more arguments


than you specified while defining the function:
def printinfo( arg1, *vartuple ):
print(arg1)
for var in vartuple:
print(var)
printinfo( 10 )
printinfo( 70, 60, 50 ) #the last two are passed as a tuple
Lambda expressions:
add = lambda a, b: a + b ← #lambda expression
# Now you can call add as a function
print("Total: ", add(10, 20)) #Total: 30
The while statement:
n=3
while n > 0:
print(n)
n = n-1
print("Go!") #3 2 1 Go!
• We can use the else clause in the while
statement but it should be avoided
The for statement:
for n in [3, 1, 9]:
print(n)
print("End") #3 1 9
---------------------------
for n in range (0,4):
print (n) #0 1 2 3
The continue and break statment: (can be used for the while and for
statements)
• The break statement in Python terminates the current loop and
resumes execution at the next statemen
• The continue statement rejects all the remaining statements in the
current iteration of the loop and moves the control back to the top
of the loop.

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

You might also like