Python Flashcards
Define:
1) Integers
2) Float numbers
3) //
4) %
1) Números inteiros
2) Números decimais
3) Quociente da divisão, ex: 14 dividido por 3 é 4 (quociente) e sobra 2 (resto)
4) Resto da divisão
Dê os símbolos das operações:
1) Adição +, Subtração -, Multiplicação *, Divisão /
2) Quociente da divisão
3) Resto da divisão
4) Potência
5) Raiz
6) Qual a ordem das operações
1)
2) //
3) % (module)
4) **
5) ** 1/(raiz desejada)
6) **, * e /, + e -
Assignment: dar nome a algo
a = 10
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
a = a + a
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
a = 3 * a
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
print(a)
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
X
X = 60
O próprio objeto pode mudar sua definição
1) Os nomes podem começar com número? Podem conter números a partir do segundo caracter?
2) O que substitui espaços no Python? (‘ ‘)
3) Podemos usar qualquer símbolo ao nomear objetos no Python?
4) É melhor usar lowercase ou UPPERCASE?
1) Não. Sim.
2) __ (underline)
3) Não. Exemplo: :’””,<>/?|!@#%^&*~-+
4) lower case. Elegante
Defina:
1) +=
2) -=
3) *=
4) /=
5) **=
6) %=
mais igual, menos igual, vezes igual, dividido igual, módulo igual
x = 3
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
x += 2
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
print x
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
5
Como verificar qual o tipo de determinado objeto?
int (integers), float, str (string), list, tuple, dict (dictionary), set. bool (boolean True or False)
”
comando type( ) -> type(objectname)
(entre parênteses coloca o nome do objeto sem aspas etc)
int (integers), float, str (string), list, tuple, dict (dictionary), set, bool (boolean True or False)
1) Defina Strings
2) Por que é melhor usar “ “ do que ‘ ‘ ao definir string?
3) Qual o comando para contar caracteres de uma string (x)?
(espaços contam como caracteres aqui)
1) Strings are used in Python to record text information, such as names. Strings in Python are actually a sequence, which basically means Python keeps track of every element in the string as a sequence. For example, Python understands the string “hello’ to be a sequence of letters in a specific order. This means we will be able to use indexing to grab particular letters (like the first letter, or the last letter).
This idea of a sequence is an important one in Python and we will touch upon it later on in the future.
2) Não confundir com I`m por exemplo
3) len(x)
“String Indexing
a = Artur Faria
a[0] >>> ?1
a[-1] >>> ?2
a[1] >>> ?3
a[7:] >>> ?4
a[:5] >>> ?5
a[::-1]>>> ?6
a[3::2]>>> ?7
a*2 >>>> ?8
a + ‘concatenate’ >>>> ?9
a + ‘ ok’ >>>>>> ?10
“A, a, r, Faria, Artur, airaF rutrA, u ai,
?8 Artur FariaArtur Faria,
?9 Artur Fariaconcatenate
?10 Artur Faria ok
A primeira posição da esquerda pra direita é 0 e a primeira posição da direita pra esquerda é -1
x: significa daquele x em diante incluindo x
:y significa tudo até aquele y excluindo y
z: :k significa a partir de z até o fim de k em k posição
b: c:d significa de b até c de d em d
::-1 (voltar a partir do último item)
Lembrar de dar espaço na hora de acrescentar itens (concatenate)
Pode-se fazer operações de + e * com Strings
“Formatting with the .format() method
print(‘The {} {} {}’.format(‘fox’, ‘brown’, ‘quick’)) >>>> ?1
print(‘The {2} {1} {0}’.format(‘fox’, ‘brown’, ‘quick’)) >>>> ?2
print(‘The {q} {b} {f}’.format(b=’brown’, q=’quick’, f=’fox’)) >>>>?3
result = 100/7
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
print(““The results was {r:1.3f}”“.format(r=result))
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ?4
“?1: The fox brown quick - se não especificar o {} vai na ordem inicial
?2 = ?3: The quick brown fox - pode colocar por ordem ou dar nome
?4: 14.286 (x.yf) - f é o que define decimais, x é pra manter 1 (se aumentar aumenta só o espaço, mas o número inteiro sempre vai aparecer), y = número de casas decimais que queremos arredondar
”
f’ method
name = Artur
age = 33
print(f’{name} is {age} years old.’)
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
“Artur is 33 years old.”
Define List
Lists
Earlier when discussing strings we introduced the concept of a sequence in Python. Lists can be thought of the most general version of a sequence in Python. Unlike strings, they are mutable, meaning the elements inside a list can be changed!
Sequence, Mutable
1) Lista usa parênteses, colchetes ou chaves?
2) O que faz listx.append(‘apend me!’)
3) O que faz o comando listx.pop(‘‘append me!’’) após executar item 2?
4) O que faz listx.pop(-1) após executar item 2 e 3?
5) popped_item faz o que?
6) O que faz listx.sort?
popped_item = mostra o item ““alterado””
1) colchetes []
2) adiciona novo item ao final da lista ‘listx’
3) Nada. Mensagem de erro pois .pop() é por posição
4) Retira o último item da lista, no caso a string ‘append me!’.
5) Mostra último item retirado
6) Organiza a lista em ordem alfabética ou números ascendentes, da erro se tiver letra e número
Define Dictionary
We’ve been learning about sequences in Python but now we’re going to switch gears and learn about mappings in Python. If you’re familiar with other languages you can think of these Dictionaries as hash tables.
So what are mappings? Mappings are a collection of objects that are stored by a key, unlike a sequence that stored objects by their relative position. This is an important distinction, since mappings won’t retain order since they have objects defined by a key.
A Python dictionary consists of a key and then an associated value. That value can be almost any Python object.
Not sequence, Mutable
mydict = {‘pai’:’Artur’, ‘mae’:’Marcele’, ‘filha’:’Elisa’}
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
mydict[filha] >>> 1?
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
mydict[‘filha’] >>> 2?
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
mydict[‘pai’, ‘mae’] >>> ?3
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
mydict[‘pai][‘mae’] >>> ?4
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
mydict2 = { } >>>> mydict2[‘filha’] = ‘Elisa’ >>>> mydict2[‘pai’] = ‘Artur’
>>>> mydict2 >>>> ?5
2? Elisa
1? 3? 4? = Error
Não vi como pegar 2 itens simultaneamente no dicionário.
Se esquecer aspas (‘x’) dá erro.
?5 {‘filha’:’Elisa’, ‘pai’:’Artur’}
.keys (chaves), .values (valores), .items (pares)
Define Tuples and answer: “What is the difference from Tuples to Lists ?
Does tuples uses ( ), [] or { } ?
In Python tuples are very similar to lists, however, unlike lists they are immutable meaning they can not be changed. You would use tuples to present things that shouldn’t be changed, such as days of the week, or dates on a calendar.
Tuples are immutable. Can`t use .append. Can be used to avoid mistakes.
( ) - parentesis
1) Define Set
2) How to create a Set?
3) Como adicionar item ao set?
4) list1 = [‘c’,’Artur’,’b’,1,2,2,1,2,5,4,3,2,6,7,8]
set(list1) >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Sets are an unordered collection of unique elements. We can construct them by using the set() function. Let’s go ahead and make a set to see how it works
set(x)
setname.add (itemname)
[1, 2, 3, 4, 5, 6, 7, 8, ‘Artur’, ‘b’, ‘c’] -> coloca números em ordem ascendente depois palavras em ordem alfabética
”
Cite os 2 Booleans ?
Pra que usamos “None”?
True or False”
We can use None as a placeholder for an object that we don’t want to reassign yet:
x = None
print (x) >>>> None
“What happens if you type:
%%writefile troll.txt
ahuahauhahua
ueheuheuheuh
>>>>> ?1
Como abrir o arquivo criado acima ?2
defina pwd e explique sua função ?3
myfile.read() >>>> ?4
Se executar novamente o comando acima não lê nada, tem que voltar o cursor pro início do texto com myfile.seek(0) ou executar ?2 de novo
Como ler por linhas separadas ?5
“?1: cria um txt na mesma pasta que o ““notebook”” com huahu na primeira linha e huehueh na segunda linha
?2 = open(‘troll.txt’) Ex: myfile
?3 print working location - informa localização do arquivo
?4: lê o txt colocando tudo na mesma linha separado por \n
ahuahauhahua\nueheuheuheuh myfile.readlines()
?5: myfile.readlines()
Para abrir arquivos de pastas diferentes do ““notebook””, devemos usar / ou // ou \ ou \ ?1 Porque ?1
Como fechar um arquivo?2
Comando ““elegante”” para abrir sem precisar fechar o arquivo ?3
Tab + Shift = mode > mode=’w’, mode=’r’, mode=’a’ ?4
?1: \ para não confundir com \n por exemplo
?2:.close( )
?3: with open(.txt) as:
showfile = .read( ) -> pode usar outros comandos
?4:
r: Opens the file in read-only mode. Starts reading from the beginning of the file and is the default mode for the open() function.
a: Opens a file for appending new information to it. The pointer is placed at the end of the file. A new file is created if one with the same name doesn’t exist.
w: Opens in write-only mode. The pointer is placed at the beginning of the file and this will overwrite any existing file with the same name. It will create a new file if one with the same name doesn’t exist.
r+: Opens a file for reading and writing, placing the pointer at the beginning of the file.
w+: Opens a file for writing and reading.
with open(‘.txt’, mode=’: (tem que apertar enter)
showfile = mynewfile.read( ) -> pode usar outros comandos
Exemplo:
with open(‘myfile.txt’, mode=’a’) as mynewfile:
showfile.write(‘\nNEW_LINE’) >>>>
will add a new line wrote NEW_LINE. Withou \n will write NEW_LINE in the last line.
”
1) Define = and ==
2) Define !=
3) > (maior), < (menor), >= (?), <= (?)
1) = is used to assign variable
== is used to equality
2) not equal or different
3) maior ou igual / menor ou igual
and = e (∧ )
or = e / ou (∨)
not = não (¬)
Símbolos matemáticos (Mathematical Thinking), Python não usa os símbolos, somente a idéia
To control the flow of logic we use some keywords: if elif else
Define them.
if = se
if some_condition:
# execute some code
elif = ou se
elif some_other_condition:
# do something different
else = caso contrário
else:
# do something else
local = ‘x’
if local == ‘Praia’:
print(‘Estamos bem’)
elif local == ‘Escola’:
print(‘PQP temos que estudar’)
elif local == ‘Casa’:
print(‘Está na hora de descansar’)
else:
print(‘foda-se’)
>>>>>>>>>>>>>>>>>
1) x = Praia
2) x = Escola
3) x = casa
4) x = Carro
1) Estamos bem
2) PQP temos que estudar
3) foda-se (casa está com inicial minúscula)
4) foda-se
LOOPS
mylist = [1,2,3,4,5,6,7,8,9,10] >>>>
for xyz in mylist:
if xyz % 2 == 0:
# check for even print(xyz) else: print(f'NOT EVEN: {xyz}') \>\>\>\>\>
NOT EVEN
2
NOT EVEN
4
NOT EVEN
6
NOT EVEN
8
NOT EVEN
10