Python Flashcards

1
Q

Define:

1) Integers
2) Float numbers
3) //
4) %

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

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

A

1)

2) //
3) % (module)
4) **
5) ** 1/(raiz desejada)
6) **, * e /, + e -

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Assignment: dar nome a algo
a = 10

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

a = a + a

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

a = 3 * a

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

print(a)

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

X

A

X = 60

O próprio objeto pode mudar sua definição

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

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?

A

1) Não. Sim.
2) __ (underline)
3) Não. Exemplo: :’””,<>/?|!@#%^&*~-+
4) lower case. Elegante

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Defina:

1) +=
2) -=
3) *=
4) /=
5) **=
6) %=

A

mais igual, menos igual, vezes igual, dividido igual, módulo igual

x = 3

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

x += 2

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

print x

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

5

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Como verificar qual o tipo de determinado objeto?

int (integers), float, str (string), list, tuple, dict (dictionary), set. bool (boolean True or False)

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

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)

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

“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, 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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

“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

A

?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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

f’ method

name = Artur

age = 33
print(f’{name} is {age} years old.’)

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

A

“Artur is 33 years old.”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Define List

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

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””

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Define Dictionary

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

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

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Define Tuples and answer: “What is the difference from Tuples to Lists ?

Does tuples uses ( ), [] or { } ?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

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

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Cite os 2 Booleans ?

Pra que usamos “None”?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

“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

A

?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()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

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

A

?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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

1) Define = and ==

2) Define !=

3) > (maior), < (menor), >= (?), <= (?)

A

1) = is used to assign variable

== is used to equality

2) not equal or different

3) maior ou igual / menor ou igual

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

and = e (∧ )

or = e / ou (∨)

not = não (¬)

A

Símbolos matemáticos (Mathematical Thinking), Python não usa os símbolos, somente a idéia

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

To control the flow of logic we use some keywords: if elif else

Define them.

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

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

A

1) Estamos bem

2) PQP temos que estudar

3) foda-se (casa está com inicial minúscula)

4) foda-se

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

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}') \>\>\>\>\>
A

NOT EVEN

2

NOT EVEN

4

NOT EVEN

6

NOT EVEN

8

NOT EVEN

10

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
mylist = [0,1,2,3,4,5,6,7,8,9,10] soma = 0 for xyz in mylist: soma = soma + xyz print(soma) **\>\>\>\>\>\> ?1** soma = 0 for xyz in mylist: soma = soma + xyz print(soma) **\>\>\>\>\>\> ?2** **OBS: diferença é posição do print(soma)**
**?1** 55 **?2** 1 3 6 10 15 21 28 36 45 55
26
"for xyz in 'Elisa é Linda': print(xyz) **\>\>\>\>\> ?1** textinho = 'Elisa é Linda' for xyz in textinho: print(xyz) **\>\>\>\>\> ?2** "
"**?1 = ?2** E l i s a é l i n d a "
27
" mylist = [(1,2), (3,4), (5,6), (7,8)] for (a,b) in mylist: print(b) **\>\>\>\>\> ?1** mylist = [(1,2), (3,4), (5,6), (7,8)] for a,b in mylist: print(b) **\>\>\>\>\> ?2** **OBS: diferença é ( ) em a,b**
"Tuples inside Lists **\>\>\>\>\> ?1 = ?2** 2 4 6 8 "
28
"mylist = [(2,3,5), (7,11,13), (17,19,23)] for a,b,c in mylist: print(b + c) **\>\>\>\>\>\>\>\>\>\>\>\>\>\>**
8 24 42
29
dic = {'k1':1, 'k2':2, 'k3':3} for chave,valor in dic.items(): print(valor) **\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>**
1 2 3 (dicionário tem que lembrar do .items( ) or .keys( ) or.values( ) no fim
30
While Loops while some\_boolean\_condition: # do something else # do something different **1)** Define: x += 1
x == x += 1
31
x = [1,2,3] for xyz in x: #comment print('end') **\>\>\>\>\> ?1** x = [1,2,3] for xyz in x: #comment pass print('end') **\>\>\>\>\> ?2**
**?1** Error Message **?2** end pass: Does nothing at all.
32
mystring = 'Marcele' for letra in mystring: if letra == 'a': continue if letra == 'e': continue print(letra) **\>\>\>\> ?1** mystring = 'Marcele' for letra in mystring: if letra == 'a': break print(letra) **\>\>\>\> ?2** x = 0 while x \< 5: if x == 4: break print(x) x = x + 2 **\>\>\>\> ?3** "
"**\>\>\>\> ?1** M r c l **\>\>\>\> ?2** M **\>\>\>\> ?3** 0 2 "
33
Define "continue" and "break"
continue: Goes to the top of the closest enclosing loop. break: Breaks out of the current closest enclosing loop.
34
"for numero in range(7): print(numero) **\>\>\>\>\> ?1** for numero in range(0,12,3): print(numero) **\>\>\>\>\> ?2** list(range(0,12,3)) **\>\>\>\>\> ?3** "
"**\>\>\>\>\> ?1** 0 1 2 3 4 5 6 **\>\>\>\>\> ?2** 0 3 6 9 **\>\>\>\>\> ?3** [0, 3, 6, 9] "
35
"index\_contador = 0 for letra in 'abcde': print('Na posição {} a letra é {}'.format(index\_contador,letra)) index\_contador += 1 **\>\>\>\>\>\> ?1** ``` index\_contador = 0 palavra = 'abcde' ``` for letra in palavra: print(palavra[index\_contador]) index\_contador += 1 **\>\>\>\>\>\> ?2** "
Na posição 0 a letra é a Na posição 1 a letra é b Na posição 2 a letra é c Na posição 3 a letra é d Na posição 4 a letra é e ``` ``` a b c d e
36
palavra = 'abcde' for index,letra in enumerate(palavra): print(letra) print('\n') print(index) print('\n') print('\n') **\>\>\>\>\>\> ?**
a \<\> 0 \<\> \<\> b \<\> 1 \<\> \<\> etc obs: \<\> é só pra marcar linha, é vazio na verdade
37
What ""in zip"" does **?1** for troll in zip(mylist1,mylist2): print(troll) **\>\>\>\>\> ?2** list(zip(mylist1,mylist2)) **\>\>\>\>\> ?3**
cria pares (""tuples""), sempre compatíveis com menor lista. Pode criar trios, quartetos, etc 2 - (1, 'a') (2, 'b') (3, 'c') 3 - [(1, 'a'), (2, 'b'), (3, 'c')]
38
mylist = [10,20,30,40,100] min(mylist) + max(mylist) **\>\>\>\>\>**
110
39
mylist1 = ['a','b','c','d','e'] from random import shuffle shuffle(mylist1) mylist1 **\>\>\>\>\>\>**
['d', 'a', 'e', 'c', 'b'] or ['e', 'a', 'c', 'b', 'd'] or ['a', 'b', 'c', 'd', 'e'] ! ! ! ! ! ! etc
40
from random import randint randint(0,5) **\>\>\>\>\>\> ?1** (quais são os resultados possíveis?) mynum = randint(0,100) **\>\>\>\>\>\>** mynum **\>\>\>\>\>\> ?2** mynum **\>\>\>\>\>\> ?3** mynum **\>\>\>\>\>\> ?4**
"**\>\>\>\>\>\> ?1** 0 ou 1 ou 2 ou 3 ou 4 ou 5 (pega um número aleatório do intervalo definido, mas pode ser o menor ou o maior número citado no intervalo **\>\>\>\>\>\> ?2 = ?3 = ?4** mynum pode ser qualquer número de 0 a 100, porém ao repetir o comando "mynum" sempre vai aparecer o mesmo, ao contrário do exemplo anterior em que sempre se gera um aleatório
41
input('Enter your daughter name here') \>\>\>\>\> Vai aparecer um espaço pra digitar o que eu quiser (ex: Elisa) Out será 'Elisa' (String) ... resultado = input('Favorite Number: ') **\>\>\>\>** (digito 13) resultado **\>\>\>\>\>**'13' int(resultado) **\>\>\>\>\>** 13 Qual a diferença do resultado da 2a e 3a linha acima **?**
resultado cria string int(resultado) cria integer
42
mystring = 'Elisa' mylist = [] for letra in mystring: mylist.append(letra) mylist **\>\>\>\>\>\>\>\> ?1** mystring1 = 'Marcele' mylist1 = [letra for letra in mystring1] mylist1 **\>\>\>\>\>\>\>\> ?2**
**\>\>\>\>\>\>\>\> ?1** ['E', 'l', 'i', 's', 'a'] **\>\>\>\>\>\>\>\> ?2** ['M', 'a', 'r', 'c', 'e', 'l', 'e']
43
mylist = [numero\*\*2 for numero in range(0,11+1)] mylist **\>\>\>\>\>\>\> ?1** mylist = [numero\*\*2 for numero in range(0,11+1) if numero%2!=0] mylist **\>\>\>\>\>\>\> ?2** celsius = [-273,-100,0,10,20,30,40,50,100] fahrenheit = [(9/5\*temp + 32) for temp in celsius] fahrenheit **\>\>\>\>\>\>\> ?3**
**\>\>\>\>\>\>\> ?1** [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121] **\>\>\>\>\>\>\> ?2** [1, 9, 25, 49, 81, 121] **\>\>\>\>\>\>\> ?3** [-459.40000000000003, -148.0, 32.0, 50.0, 68.0, 86.0, 104.0, 122.0, 212.0]
44
results = [x if x%2==0 else 'ODD' for x in range(0,11)] results **\>\>\>\>\> ?**
[0, 'ODD', 2, 'ODD', 4, 'ODD', 6, 'ODD', 8, 'ODD', 10]
45
mylist = [] for x in [2,3,5,7]: for y in [11,13,17,19]: mylist.append(x\*y) mylist **\>\>\>\>\> ?2** mylist = [x\*y for x in [2,3,5,7] for y in [11,13,17,19]] mylist **\>\>\>\>\> ?3**
**?2 ==** **?3** [22, 26, 34, 38, 33, 39, 51, 57, 55, 65, 85, 95, 77, 91, 119, 133]
46
"dicionario = {'Pai':'Artur','Mae':'Marcele','Filha':'Elisa'} for x,y in dicionario.items(): print(y) **\>\>\>\>\>\>\>?**
Artur Marcele Elisa
47
contador = 0 for letra in 'abcde': print(""{} {}"".format(contador,letra)) contador += 1 **\>\>\>\>\>\>\>\>\>\>**
0 a 1 b 2 c 3 d 4 e
48
"for numero in range(1,20+1): if numero % 15 == 0: print('FizzBuzz') elif numero%3 == 0: print('Fizz') elif numero%5 == 0: print('Buzz') else: print(numero) **\>\>\>\>\>\>\>\>\>\>\>\>\>**
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Detalhe é: primeiro pega os múltiplos de 15 e só depois de 3 ou 5, caso contrário dá errado. poderia ser: if numero%3 == 0 and numero%5 == 0 (na segunda linha)
49
st = 'Create a list of the first letters of every word in this string' [palavra[0] for palavra in st.split()] **\>\>\>\>\>\>\>**
['C', 'a', 'l', 'o', 't', 'f', 'l', 'o', 'e', 'w', 'i', 't', 's']
50
Which of the following codes are from Python or from other codes? a) ?????????? if (x) if(y) code-statement; else another-code-statement; b)????????? if x: if y: code-statement else: another-code-statement
a) Python b) Other codes Python uses colon, whitespace and “Indentation”
51
**xxxxxxx** Statements in Python allows us to tell the computer to perform alternative actions based on a certain set of results. Verbally, we can imagine we are telling the computer: ""Hey if this case happens, perform some action"" We can then expand the idea further with **yyyyyyy** and **zzzzzzz** statements, which allow us to tell the computer: ""Hey if this case happens, perform some action. Else, if another case happens, perform some other action. Else, if none of the above cases happened, perform this action."" Let's go ahead and look at the syntax format for if statements to get a better idea of this: xxxxxxx case1: perform action1 yyyyyyy case2: perform action2 zzzzzzz: perform action3
X = if Y = elif Z = else
52
x = False if x: print('x was True!') xxxxxxxxxx: print('I will be printed in any case where x is not true') \>\>\>\>\>\>\>\>\>\>\>\>\>\>\> I will be printed in any case where x is not true
xxx = else
53
loc = 'Bank' xxxxxxxxxx loc == 'Auto Shop': print('Welcome to the Auto Shop!') yyyyyyyyyy loc == 'Bank': zzzzzzzz('Welcome to the bank!') else: print('Where are you?') \>\>\>\>\>\>\>\>\>\>\>\>\>\>\> Welcome to the bank!
X = if Y = elif Z = print
54
list1 = [1:10+1] xxxxxxx yyyyyyy zzzzzzz list1: print(num) \>\>\>\>\>\>\>\>\>\>\>\>\>\>\> 1 2 3 4 5 6 7 8 9 10
**X** **for** **Y** **Num** **Z** **in**
55
list1 = [1,2,3,4,5,6,7,8,9,10] for num in list1: xxxxxxxx num % 2 == 0: print(num) \>\>\>\>\>\>\>\>\>\>\>\>\>\>\> 2 4 6 8 10
X = if
56
list1 = [1,2,3,4,5,6,7,8,9,10] **xxxxxx** num **yyyyyy** list1: **wwwwww** num % 2 == 0: print(num) **zzzzzzzzz:** print('Odd number') \>\>\>\>\>\>\>\>\>\>\>\>\>\>\> Odd number 2 Odd number 4 Odd number 6 Odd number 8 Odd number 10
X = for Y = in W = if Z = else
57
list1 = [1,2,3,4,5,6,7,8,9,10] list\_sum = **?????** for num in list1: **xxxxxxxx** **= yyyyyyy** + num print(list\_sum) \>\>\>\>\>\>\>\>\>\>\>\>\>\>\> 55
**???????? == 0** **X == Y == list\_sum**
58
**xxxxxx** letter **yyyyyy**'This is a string.': print(**zzzzzz**) \>\>\>\>\>\>\>\>\>\>\>\>\>\>\> T h i s i s a s t r i n g .
**X = for** **Y = in** **Z = letter**
59
tup = (1,2,3,4,5) for **xxxxxxxxx** in tup: print(**yyyyyyy**) \>\>\>\>\>\>\>\>\>\>\>\>\>\>\> 1 2 3 4 **5**
"**X = Y, they can be any word or letter**"
60
list2 = [(2,4),(6,8),(10,12)] for (t1,t2) in list2: print(**xxxxxxx**x) \>\>\>\>\>\>\>\>\>\>\>\>\>\>\> 2 6 10
**X == t1**
61
dict = {'k1':1,'k2':2,'k3':3} for **xxxxxx,yyyyyyy** in dict.items(): print(**wwwww**) print(**zzzzzzzz**) \>\>\>\>\>\>\>\>\>\>\>\>\>\>\> k1 1 k2 2 k3 3 **list(dict.keys())** \>\>\>\>\>\>\>\>\>\>\>\>\>\>\> **sorted(dict.values())** \>\>\>\>\>\>\>\>\>\>\>\>\>\>\>
X==W e Y==Z ['k1', 'k2', 'k3'] [1, 2, 3]
62
x = 0 **?????????** x \< 10: print('x is currently: ',x) print(' x is still less than 10, adding 1 to x') x+=1 else: print('All Done!') \>\>\>\>\>\>\>\>\>\>\>\>\>\>\> x is currently: 0 x is still less than 10, adding 1 to x x is currently: 1 x is still less than 10, adding 1 to x x is currently: 2 x is still less than 10, adding 1 to x x is currently: 3 x is still less than 10, adding 1 to x x is currently: 4 x is still less than 10, adding 1 to x x is currently: 5 x is still less than 10, adding 1 to x x is currently: 6 x is still less than 10, adding 1 to x x is currently: 7 x is still less than 10, adding 1 to x x is currently: 8 x is still less than 10, adding 1 to x x is currently: 9 x is still less than 10, adding 1 to x All Done!
while
63
while x \< 10: print('x is currently: ',x) print(' x is still less than 10, adding 1 to x') x+=1 if x==3: print('Breaking because x==3') **xxxxxxxx** else: print('continuing...') continue \>\>\>\>\>\>\>\>\>\>\>\>\>\>\> x is currently: 0 x is still less than 10, adding 1 to x continuing... x is currently: 1 x is still less than 10, adding 1 to x continuing... x is currently: 2 x is still less than 10, adding 1 to x Breaking because x==3
**X = break**
64
while x \< 10: print('x is currently: ',x) print(' x is still less than 10, adding 1 to x') x+=1 if x==3: print('x==3') else: print('continuing...') **xxxxxxxxxxx** \>\>\>\>\>\>\>\>\>\>\>\>\>\>\> x is currently: 0 x is still less than 10, adding 1 to x continuing... x is currently: 1 x is still less than 10, adding 1 to x continuing... x is currently: 2 x is still less than 10, adding 1 to x x==3 x is currently: 3 x is still less than 10, adding 1 to x continuing... x is currently: 4 x is still less than 10, adding 1 to x continuing... x is currently: 5 x is still less than 10, adding 1 to x continuing... x is currently: 6 x is still less than 10, adding 1 to x continuing... x is currently: 7 x is still less than 10, adding 1 to x continuing... x is currently: 8 x is still less than 10, adding 1 to x continuing... x is currently: 9 x is still less than 10, adding 1 to x continuing...
**X = continue**
65
list(**xxxxxxxx**(0,11)) \>\>\>\>\>\>\>\>\>\>\>\>\>\>\> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] list(**xxxxxxxx**(0,11, **yyyyyyyy**)) \>\>\>\>\>\>\>\>\>\>\>\>\>\>\> [0, 2, 4, 6, 8, 10]
**X = range** **Y = 2**
66
index\_count = 0 for letter in 'abcde': print("At index {} the letter is {}".format(index\_count,letter)) index\_count += 1 \>\>\>\>\>\>\>\>\>\>\>\>\>\>\> At index 0 the letter is a At index 1 the letter is b At index 2 the letter is c At index 3 the letter is d At index 4 the letter is e for xyz,letter in **xxxxxxxx**('abcde'): print("At index {} the letter is {}".format(xyz,letter)) \>\>\>\>\>\>\>\>\>\>\>\>\>\>\> At index 0 the letter is a At index 1 the letter is b At index 2 the letter is c At index 3 the letter is d At index 4 the letter is e
**X ==** **enumerate**
67
list(**xxxxxxxx**('abcde')) \>\>\>\>\>\>\>\>\>\>\>\>\>\>\> [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')]
**X == enumerate**
68
mylist1 = [1,2,3,4,5] mylist2 = ['a','b','c','d','e'] list(**xxxxxxxx**(mylist1,mylist2)) \>\>\>\>\>\>\>\>\>\>\>\>\>\>\> [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')] for item1, item2 in **xxxxxxxx**(mylist1,mylist2): print('For this tuple, first item was {} and second item was {}'.format(item1,item2)) \>\>\>\>\>\>\>\>\>\>\>\>\>\>\> For this tuple, first item was 1 and second item was a For this tuple, first item was 2 and second item was b For this tuple, first item was 3 and second item was c For this tuple, first item was 4 and second item was d For this tuple, first item was 5 and second item was e
**X == zip**
69
**'x' in ['x','y','z']** **\>\>\>\>\>\>\>\>\>\>\>\>\>\>\> 1** **'x' in [1,2,3]** **\>\>\>\>\>\>\>\>\>\>\>\>\>\>\> 2**
**True** **False** OBS: Booleans
70
mylist = [10,20,30,40,100] from **xxxxxxx** import **yyyyyyy** Mylist \>\>\>\>\>\>\>\>\>\>\>\>\>\>\> [40, 10, 100, 30, 20]
**X == random** **Y == shuffle**
71
from random import randint randint(0,100) \>\>\>\>\>\>\>\>\>\>\>\>\>\>\>
any number from 0 top 100 (including both 0 and 100 -\> testei)
72
input('Enter Something into this box: ') \>\>\>\>\>\>\>\>\>\>\>\>\>\>\>
Enter Something into this box: \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_ (espaço para digitar)
73
**xxxxxx** = [x for x in 'word'] **xxxxxx** \>\>\>\>\>\>\>\>\>\>\>\>\>\>\> ['w', 'o', 'r', 'd']
X = qualquer coisa
74
**xxxxxx** = [x\*\*2 for x in range(0,11)] **xxxxxx** \>\>\>\>\>\>\>\>\>\>\>\>\>\>\> [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
X = qualquer\_coisa
75
**xxxxxx** = [x for x in range(11) if x % 2 == 0] **xxxxxx** \>\>\>\>\>\>\>\>\>\>\>\>\>\>\> [0, 2, 4, 6, 8, 10] "
**X = qualquer\_palavra**
76
celsius = [0,10,20.1,34.5] fahrenheit = [((9/5)\***xxxxxx** + 32) for **xxxxxx** in celsius] fahrenheit \>\>\>\>\>\>\>\>\>\>\>\>\>\>\> [32.0, 50.0, 68.18, 94.1] "
X = qualquer\_palavra
77
**xxxxxx** = [x\*\*2 for x in [x\*\*2 for x in range(11)]] **xxxxxx** \>\>\>\>\>\>\>\>\>\>\>\>\>\>\> [0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000]
**X = qualquer\_palavra**
78
How to get help for a list method? Example: Help for list called lista and method called insert ? (there are two ways)
help(lista.insert) \>\>\>\>\> or lista.insert
79
"Link for most useful part of ""Python wiki""?"
"https://docs.python.org/3.7/library/"
80
What is these commands? * append ( ) * count ( ) * extend ( ) * insert ( ) * pop ( ) * remove ( ) * reverse ( ) * sort ( )
Methods for a List
81
"def name\_function(): print('Hello!') name\_function **\>\>\>\>\>\>\>\>\>\>\> ?1** name\_function() **\>\>\>\>\>\>\>\>\>\>\> ?2**
1 - error 2 - Hello!
82
"def name\_function(): ''' DOCSTRING: information about the function INPUT: no input... OUTPUT: Hello... ''' print('Hello!') \>\>\>\>\>\>\>\>\>\>\>\>\> **xxxxxx(yyyyyy)** \>\>\>\>\>\>\>\>\>\>\>\>\> Help on function name\_function in module \_\_main\_\_: name\_function() DOCSTRING: information about the function INPUT: no input... OUTPUT: Hello... "
X == help Y == name\_function (pode ser qualquer palavra na verdade)
83
**xxxxxx** sayhello(anyword): print('Hello '+anyword) sayhello('Artur') \>\>\>\>\>\>\> Hello Artur
**X == def**
84
"def sayhello(name='NOME'): print('Hello '+name) **\>\>\>\>\>\>\>\>\>** sayhello() **\>\>\>\>\>\>\>\>\> ?1** sayhello('Elisa) **\>\>\>\>\>\>\>\>\> ?2**
Hello NOME Hello Elisa
85
"def sayhello(name): return 'hello '+name **\>\>\>\>\>\>\>\>\>\>\>\>\>\>** **xxxxxxx** = sayhello('Suedy') **\>\>\>\>\>\>\>\>\>\>\>\>\>\>** **yyyyyyy** **\>\>\>\>\>\>\>\>\>\>\>\>\>\>** 'hello Suedy' "
**X = Y = any word**
86
"def **xxxxx**(n1,n2): return n1\*n2 resultado = **yyyyy(**3,5) resultado **\>\>\>\>\>\>\>\>\>\>\>\>** 15 "
**X = Y = any word**
87
``` def xxxxx(n1,n2): return n1\*n2 resultado = yyyyy(3,5) resultado ``` **\>\>\>\>\>\>\>\>\>** 15
**X = Y**
88
What is the best / most elegant way to say: ``` def dogcheck(mystring): if 'dog' in mystring.lower(): return True else: return False ``` dogcheck('any string')
``` def dogcheck(mystring): return 'dog' in mystring.lower() ``` dogcheck('any string')
89
**xxxxxxx** piglatin(palavra): letra0 = palavra[0] if letra0 in 'aeiou': pigword = palavra + 'ay' else: pigword = palavra[1:] + letra0 + 'ay' **yyyyyyy** pigword **\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>** piglatin('argentina') **\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>** 'argentinaay' piglatin('brasil') **\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>** 'rasilbay' "
**X == def** **Y == return**
90
"def greeting(name): print('Hello %s' %(name)) greeting('Elisa') **\>\>\>\>\>\>\>\>\>\>\>** Hello Elisa **Porque é preciso dos % ???** "
Não sei
91
``` def add\_num(num1,num2): return num1+num2 ``` **\>\>\>\>\>\>\>\>\>\>\>\>** add\_num(4,5) **\>\>\>\>\>\>\>\>\>\> ?1** add\_num('one','two') **\>\>\>\>\>\>\>\>\>\> ?2**
**?1 == 9** **?2 == 'onetwo'**
92
Write a function called myfunc that prints the string 'Hello World'
``` def myfunc(): print('Hello World') ```
93
Define a function called myfunc that takes in a name, and prints 'Hello Name'
``` def myfunc(name): print('Hello {}'.format(name)) ```
94
Define a function called myfunc that takes in a Boolean value (True or False). If True, return 'Hello', and if False, return 'Goodbye'
def myfunc(x): if x == True: return 'Hello' else: return 'Goodbye'
95
# Define a function called myfunc that makes three arguments, x, y and z. If z is True, return x. If z is False, return y.
``` def myfunc(x,y,z): if z == True: return x elif z == False: return y ```
96
Define a funcion called myfunc that takes in two arguments and returns their sum of them.
``` def myfunc(x,y): return x+y ```
97
Define a function called is\_even that takes in one argument, and returns True if the passed-in value is even, False if it is not.
def is\_even(x): if x%2==0: return True else: return False
98
Define a function called is\_greater that takes in two arguments, and returns True if the first value is greater than the second, False if it is less than or equal to the second
``` def is\_greater(x,y): if x\>y: return True elif x\<=y: return False ```
99
``` def myfunc (a,b,c,d,e): return sum((a,b,c,d,e)) / 20 ``` \>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\> myfunc(10,20,30,40,50) \>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\> 7.5 myfunc(10,20,30) \>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\> error myfunc (10,20,30,40,50,60) \>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\> error but def myfunc (\*xxxxx): return sum(xxxxx) myfunc then can have any numbers(members) we want!!!! What is the standard word we use instead of xxxxx?
\*args args
100
"def myfunc(\*\*yyyyy): if 'fruit' in yyyyy: print('My fruit of choice is {}'.format(yyyyy['fruit'])) else: print('I did not find any fruit here') **\>\>\>\>\>\>\>\>\>\>\>\>\>\>** myfunc(fruit='apple',veggie='lettuce') **\>\>\>\>\>\>\>\>\>\>\>\>\>\>** My fruit of choice is apple what is the standard word we use instead of yyyyy? (what really means is \*\* before first yyyyy) why do we use this trick?
"\*\*kwargs kwargs kwargs Because if we don't use, we need to use all dic keys in a function. It would have returned error message instead of ""My fruit of choice is apple''.
101
You can pass `*args` and `**kwargs` into the same function, but `*args` have to appear before `**kwargs` def myfunc(\*args, \*\*kwargs): if 'fruit' and 'juice' in kwargs: print(f""I like {' and '.join(args)} and my favorite fruit is {kwargs['fruit']}"") print(f""May I have some {kwargs['juice']} juice?"") else: pass myfunc('eggs','spam',fruit='cherries',juice='orange')
I like eggs and spam and my favorite fruit is cherries May I have some orange juice?
102
Define a function called myfunc that takes in a string and returns a matching string where every even letter is uppercase, and every odd letter is lowercase. Assume that the incoming string only contains letters, and don`t worry about numbers, spaces or punctuation. The output string can start with either an uppercase or lowercase letter, so long as letters alternate throughout the string.
def myfunc(word): result = ' ' for i,a in enumerate (word): if i %2==1: result+=a.upper() else: result+=a.lower() return result
103
"def myfunc (word): for i,a in enumerate (word): if i %2==1: print (a.upper() ,end="""") else: print (a.lower() ,end="""") myfunc ('Anthropomorphism')"
aNtHrOpOmOrPhIsM
104
Define a function called myfunc that takes in an arbitrary number of arguments, and returns a list containing only those arguments that are even
``` def myfunc(\*args): return [num for num in args if num %2 == 0] ```
105
Define a function called myfunc that takes in an arbitrary number of arguments, and returns the sum of those arguments.
``` def myfunc(\*troll): return sum(troll) ```
106
LESSER OF TWO EVENS: Write a function that returns the lesser of two given numbers if both numbers are even, but returns the greater if one or both numbers are odd **lesser\_of\_two\_evens(2,4) --\> 2 lesser\_of\_two\_evens(2,5) --\> 5**
def lesser\_of\_two\_evens(a,b): if a%2==0 and b%2==0: if a \< b: result = a if b \< a: result = b else: if a \> b: result = a if b \> a: result = b return result or def lesser\_of\_two\_evens(a,b): if a%2 == 0 and b%2 == 0: return min(a,b) else: return max(a,b)
107
ANIMAL CRACKERS: Write a function takes a two-word string and returns True if both words begin with same letter animal\_crackers('Levelheaded Llama') --\> True animal\_crackers('Crazy Kangaroo') --\> False
``` def animal\_crackers(text): wordlist = text.lower().split() first = wordlist[0] second = wordlist[1] return first[0]==second[0] ``` or ``` def animal\_crackers(text): wordlist = text.lower().split() return wordlist[0][0] == wordlist[1][0] ```
108
MAKES TWENTY: Given two integers, return True if the sum of the integers is 20 or if one of the integers is 20. If not, return False makes\_twenty(20,10) --\> True makes\_twenty(12,8) --\> True makes\_twenty(2,3) --\> False
def makes\_twenty(n1,n2): if n1+n2==20: return True if n1==20 or n2==20: return True else: return False or ``` def makes\_twenty(n1,n2): return (n1+n2)==20 or n1==20 or n2==20 ```
109
OLD MACDONALD: Write a function that capitalizes the first and fourth letters of a name old\_macdonald('macdonald') --\> MacDonald
``` def old\_macdonald(name): first = name[0] second = name[1] third = name[2] forth = name[3] rest = name[4:] return first.upper() + second + third + forth.upper() + rest ``` or ``` def old\_macdonald(name): half1 = name[:3] half2 = name[3:] return half1.capitalize() + half2.capitalize() ```
110
"MASTER YODA: Given a sentence, return a sentence with the words reversed master\_yoda('I am home') --\> 'home am I' master\_yoda('We are ready') --\> 'ready are We' Note: The .join() method may be useful here. The .join() method allows you to join together strings in a list with some connector string. For example, some uses of the .join() method: `>>> ""--"".join(['a','b','c']) >>> 'a--b--c'` This means if you had a list of words you wanted to turn back into a sentence, you could just join them with a single space string: `>>> "" "".join(['Hello','world']) >>> ""Hello world""`
``` def master\_yoda(text): lista = text.split() inversa = lista[::-1] return ' '.join(inversa) ```
111
ALMOST THERE: Given an integer n, return True if n is within 10 of either 100 or 200 almost\_there(90) --\> True almost\_there(104) --\> True almost\_there(150) --\> False almost\_there(209) --\> True NOTE: `abs(num)` returns the absolute value of a number
``` def quase(n): if n - 100 in range (-10,11): return True elif n - 200 in range (-10,11): return True else: return False ``` or def quase(n): return (abs(100-n) \<=10) or (abs(200-n) \<= 10)
112
FIND 33: Given a list of ints, return True if the array contains a 3 next to a 3 somewhere. `has_33([1, 3, 3]) → True ` `has_33([1, 3, 1, 3]) → False ` `has_33([3, 1, 3]) → False`
``` def has\_33(n): for l in range(0, len(n)-1): if n[l] == 3 and n[l+1] == 3: return True return False ``` or ``` def has\_33(n): for l in range(0, len(n)-1): if n[l:l+2] == [3,3]: return True return False ```
113
``` def square(n): return n\*\*2 ``` myn = [1,2,3,4,5] **\>\>\>\>\>\>\>\>\>\>\>\>\>\>** for item in **xxxxx**(square, myn): print(item) **\>\>\>\>\>\>\>\>\>\>\>\>\>\>** 1 4 9 16 25 list(**xxxxx**(square, myn)) **\>\>\>\>\>\>\>\>\>\>\>\>\>\>** [1, 4, 9, 16, 25] "
**X = map**
114
``` def splicer(mystring): if len(mystring)%2==0: return 'Even' else: return mystring[0] ``` **\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>** names = ['Artur', 'Elisa', 'Marcele', 'Suedy', 'Hélio', 'Heitor'] **\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>** list(**xxxxx**(splicer, names)) **\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>** ['A', 'E', 'M', 'S', 'H', 'Even']
**X = map**
115
``` def check\_even(num): return num%2 == 0 ``` mynums = [1,2,3,4,5,6] **\>\>\>\>\>\>\>\>\>\>\>** list(**xxxxxx**(check\_even,mynums)) **\>\>\>\>\>\>\>\>\>\>\>** [2, 4, 6] for n in **xxxxxx**(check\_even,mynums): print(n) **\>\>\>\>\>\>\>\>\>\>\>** 2 4 6
**X = filter**
116
The following functions are equivalents. What substitutes X? def square(num): return num \*\* 2 square = **xxxxxx** num: num\*\*2"
**X = lambda**
117
myn = [1,2,3,4,5] **\>\>\>\>\>\>\>\>\>\>\>\>\>\>** ``` def square(n): return n\*\*2 ``` list(map(square, myn)) **\>\>\>\>\>\>\>\>\>\>\>\>\>\>** [1, 4, 9, 16, 25] list(map(**xxxxxx** n: n\*\*2,myn)) **\>\>\>\>\>\>\>\>\>\>\>\>\>\>** [1, 4, 9, 16, 25]
**X = lambda**
118
what makes the following 2 and 3 expressions equivalent? mynums = [1,2,3,4,5,6] **\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>** ``` def check\_even(num): return num%2 == 0 ``` list(filter(check\_even,mynums)) **\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>** list(filter(**xxxxx** num: num%2==0, mynums)) **\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>**
**X = lambda**
119
"PAPER DOLL: Given a string, return a string where for every character in the original there are three characters paper\_doll('Hello') --\> 'HHHeeellllllooo' paper\_doll('Mississippi') --\> 'MMMiiissssssiiippppppiii'
def paper\_doll(text): result = '' for letra in text: result += letra\*3 return result
120
BLACKJACK: Given three integers between 1 and 11, if their sum is less than or equal to 21, return their sum. If their sum exceeds 21 and there's an eleven, reduce the total sum by 10. Finally, if the sum (even after adjustment) exceeds 21, return 'BUST' blackjack(5,6,7) --\> 18 blackjack(9,9,9) --\> 'BUST' blackjack(9,9,11) --\> 19
def blackjack(a,b,c): if sum((a,b,c)) \<= 21: return sum((a,b,c)) elif sum((a,b,c)) \<=31 and 11 in (a,b,c): return sum((a,b,c)) - 10 else: return 'BUST'
121
SUMMER OF '69: Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 9 (every 6 will be followed by at least one 9). Return 0 for no numbers. summer\_69([1, 3, 5]) --\> 9 summer\_69([4, 5, 6, 7, 8, 9]) --\> 9 summer\_69([2, 1, 6, 9, 11]) --\> 14
def summer\_69(mylist): total = 0 add = True for num in mylist: while add: if num!=6: total+=num break else: add = False while not add: if num!=9: break else: add = True break return total
122
SPY GAME: Write a function that takes in a list of integers and returns True if it contains 007 in order spy\_game([1,2,4,0,0,7,5]) --\> True spy\_game([1,0,2,4,0,5,7]) --\> True spy\_game([1,7,2,0,4,5,0]) --\> False
def spy\_game(nums): code = [0,0,7,'x'] # [0,7,'x'] -\> [7,'x'] -\> ['x'] Lenght=1 for num in nums: if num==code[0]: code.pop(0) return len(code)==1
123
COUNT PRIMES: Write a function that returns the number of prime numbers that exist up to and including a given number count\_primes(100) --\> 25 By convention, 0 and 1 are not prime.
**def count\_primes(num):** * *if num \<2:** * *return 0** * *primes = [2]** * *x = 3** * *while x\<=num:** * *for y in range(3,x,2):** * *if x%y==0:** * *x+=2** * *break** * *else:** * *primes.append(x)** * *x+=2** * *print(primes)** * *return len(primes)** **Or** **def count\_primes(num):** * *if num \<2:** * *return 0** * *primes = [2]** * *x = 3** * *while x\<=num:** * *for y in primes:** * *if x%y==0:** * *x+=2** * *break** * *else:** * *primes.append(x)** * *x+=2** * *print(primes)** * *return len(primes)** "
124
x = 25 ``` def printer(): x = 50 return x ``` ``` print(x) # print(printer()) ``` \>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\> print(x) **\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\> XXXXX** print(printer( )) **\>\>\>\>\>\>\>\>\>\>\>\> YYYYY**
X = 25 Y = 50 Now that we have gone over writing our own functions, it's important to understand how Python deals with the variable names you assign. When you create a variable name in Python the name is stored in a name-space. Variable names also have a scope, the scope determines the visibility of that variable name to other parts of your code. Interesting! But how does Python know which x you're referring to in your code? This is where the idea of scope comes in. Python has a set of rules it follows to decide what variables (such as x in this case) you are referencing in your code. Lets break down the rules: This idea of scope in your code is very important to understand in order to properly assign and call variable names. In simple terms, the idea of scope can be described by 3 general rules: Name assignments will create or change local names by default. Name references search (at most) four scopes, these are: local enclosing functions global built-in Names declared in global and nonlocal statements map assigned names to enclosing module and function scopes. LEGB rule! Local \> Enclosing \> Global (module) \> Built-in (Python) LEGB Rule: L: Local — Names assigned in any way within a function (def or lambda), and not declared global in that function. E: Enclosing function locals — Names in the local scope of any and all enclosing functions (def or lambda), from inner to outer. G: Global (module) — Names assigned at the top-level of a module file, or declared global in a def within the file. B: Built-in (Python) — Names preassigned in the built-in names module : open, range, SyntaxError,...
125
name = 'This is a global name' ``` def greet(): # Enclosing function name = 'Sammy' ``` ``` def hello(): print('Hello '+name) ``` hello() greet() **\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\> ???????????**
Hello Sammy Enclosing function locals This occurs when we have a function inside a function (nested functions) Note how Sammy was used, because the hello() function was enclosed inside of the greet function! if: print(name) \>\>\>\>\>\>\>\>\> This is a global name (Global)
126
x = 50 ``` def func(x): print('x is', x) x = 2 print('Changed local x to', x) ``` ``` func(x) print('x is still', x) ``` \>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>.
x is 50 Changed local x to 2 x is still 50 Local Variables When you declare variables inside a function definition, they are not related in any way to other variables with the same names used outside the function - i.e. variable names are local to the function. This is called the scope of the variable. All variables have the scope of the block they are declared in starting from the point of definition of the name. The first time that we print the value of the name x with the first line in the function’s body, Python uses the value of the parameter declared in the main block, above the function definition. Next, we assign the value 2 to x. The name x is local to our function. So, when we change the value of x in the function, the x defined in the main block remains unaffected. With the last print statement, we display the value of x as defined in the main block, thereby confirming that it is actually unaffected by the local assignment within the previously called function.
127
x = 50 ``` def func(): global x print('This function is now using the global x!') print('Because of global x is: ', x) x = 2 print('Ran func(), changed global x to', x) ``` ``` print('Before calling func(), x is: ', x) func() print('Value of x (outside of func()) is: ', x) ``` \>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>.
Before calling func(), x is: 50 This function is now using the global x! Because of global x is: 50 Ran func(), changed global x to 2 Value of x (outside of func()) is: 2 The global statement If you want to assign a value to a name defined at the top level of the program (i.e. not inside any kind of scope such as functions or classes), then you have to tell Python that the name is not local, but it is global. We do this using the global statement. It is impossible to assign a value to a variable defined outside a function without the global statement. You can use the values of such variables defined outside the function (assuming there is no variable with the same name within the function). However, this is not encouraged and should be avoided since it becomes unclear to the reader of the program as to where that variable’s definition is. Using the global statement makes it amply clear that the variable is defined in an outermost block. The global statement is used to declare that x is a global variable - hence, when we assign a value to x inside the function, that change is reflected when we use the value of x in the main block. You can specify more than one global variable using the same global statement e.g. global x, y, z.
128
Write a function that computes the volume of a sphere given its radius. The volume of a sphere is given as (4/3) x (pi) x (r) x (r) x (r)
``` def vol(rad): vol = (4 / 3) \* 3.14159265359 \* rad \*\* 3 return vol ``` or ``` def vol(rad): return (4/3)\*(3.14)\*(rad\*\*3) ```
129
Write a function that checks whether a number is in a given range (inclusive of high and low)
def ran\_check(num,low,high): if low \< num \< high: return '{} is in the range between {} and {}'.format(num, low, high) else: return '{} is not in the range between {} and {}'.format(num, low, high) pass or def ran\_bool(num,low,high): if low \< num \< high: return True else: return false or ``` def ran\_check(num,low,high): #Check if num is between low and high (including low and high) if num in range(low,high+1): print('{} is in the range between {} and {}'.format(num,low,high)) else: print('The number is outside the range.') ``` or ``` def ran\_bool(num,low,high): return num in range(low,high+1) ```
130
Write a Python function that accepts a string and calculates the number of upper case letters and lower case letters. Sample String : 'Hello Mr. Rogers, how are you this fine Tuesday?' Expected Output : No. of Upper case characters : 4 No. of Lower case Characters : 33 HINT: Two string methods that might prove useful: .isupper() and .islower()
def up\_low(s): d={'up':0, 'low':0} for c in s: if c.isupper(): d['up']+=1 elif c.islower(): d['low']+=1 else: continue print(s) print('Numero de maiúsculas é : ', d['up']) print('Numero de minúsculas é : ', d['low']) or def up\_low(s): d={"upper":0, "lower":0} for c in s: if c.isupper(): d["upper"]+=1 elif c.islower(): d["lower"]+=1 else: pass print("Original String : ", s) print("No. of Upper case characters : ", d["upper"]) print("No. of Lower case Characters : ", d["lower"])
131
Write a Python function that takes a list and returns a new list with unique elements of the first list. Sample List : [1,1,1,1,2,2,3,3,3,3,4,5] Unique List : [1, 2, 3, 4, 5]
``` def unique\_list(lista): unique\_list = set(lista) troll = list(unique\_list) return troll ``` or def unique\_list(lst): # Also possible to use list(set()) x = [] for a in lst: if a not in x: x.append(a) return x
132
Write a Python function to multiply all the numbers in a list. Sample List : [1, 2, 3, -4] Expected Output : -24
def multiply(numbers): total = numbers[0] for n in numbers: total \*= n return total
133
Write a Python function that checks whether a passed string is palindrome or not. Note: A palindrome is word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run.
def palindrome(s): if s == s[::-1]: return True else: return False pass (fiz incompleto) or def palindrome(s): s = s.replace(' ','') # This replaces all spaces ' ' with no space ''. (Fixes issues with strings that have spaces) return s == s[::-1] # Check through slicing
134
Write a Python function to check whether a string is pangram or not. Note : Pangrams are words or sentences containing every letter of the alphabet at least once. For example : "The quick brown fox jumps over the lazy dog" string.ascii\_lowercase \>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\>\> 'abcdefghijklmnopqrstuvwxyz'
import string ``` def ispangram(str1, alphabet=string.ascii\_lowercase): alphaset = set(alphabet) return alphaset \<= set(str1.lower()) ```