├── AULA.21.7.py ├── AULA10.py ├── AULA19.1.py ├── AULA19.3.py ├── AULA20.1.py ├── AULA20.2.py ├── AULA20.3.py ├── AULA20.py ├── AULA21.1.py ├── AULA21.2.py ├── AULA21.3.py ├── AULA21.4.py ├── AULA21.5.py ├── AULA21.6.py ├── AULA21.8.py ├── AULA21.9.py ├── AULA21.py ├── AULA22.py ├── AULA23.1.py ├── AULA23.py ├── AULA24.5.py ├── AULA24.6.py ├── BOLETINS.py ├── BOLETINS1.py ├── CADASTROJOGADOR.py ├── CADASTROJOGADORES.py ├── CADASTROPESSOAS.py ├── CADASTROPESSOAS1.py ├── CADASTROPESSOAS2.py ├── CADASTROTRABALHADOR.py ├── Desafio 39.py ├── Desafio10.py ├── Desafio13.py ├── Desafio20.py ├── Desafio21.py ├── Desafio22.py ├── Desafio23.py ├── Desafio24.py ├── Desafio25.py ├── Desafio26.py ├── Desafio27.py ├── Desafio28.py ├── Desafio29.py ├── Desafio30.py ├── Desafio34.py ├── Desafio35.py ├── Desafio36.py ├── Desafio37.py ├── Desafio38.py ├── Desafio40.py ├── Desafio41.py ├── Desafio42.py ├── Desafio43.py ├── Desafio44.py ├── Desafio45.py ├── Desafio46.py ├── Desafio47.py ├── Desafio51.py ├── Exercício.py ├── Fizzbuzz.py ├── Jo-Ken-Po.py ├── PALPITESMEGASENA.py ├── PAROUIMPAR.py ├── PYTHONINTERACTIVEHELPSYSTEM.py ├── PythonTeste.py ├── aula10.2.py ├── aula12.py ├── aula14.py ├── aula15.py ├── aula16.py ├── aula17.1.py ├── aula17.2.py ├── aula17.py ├── aula18.1.py ├── aula18.2.py ├── aula18.py ├── aula19.2.py ├── bandnamegenerator.py ├── bankingroulette.py ├── blackjack.py ├── bmicalculator.py ├── bmicalculator2.0.py ├── caesarcipherartart.py ├── caesarciphercommented.py ├── caixaeletronico.py ├── calculator.py ├── daysinmonth.py ├── desafio 67.py ├── desafio 68.py ├── desafio31.py ├── desafio32.py ├── desafio33.py ├── desafio50.py ├── desafio52.py ├── desafio53.py ├── desafio54.py ├── desafio55.py ├── desafio56.py ├── desafio57.py ├── desafio58.py ├── desafio59.py ├── desafio60.py ├── desafio61.py ├── desafio62.py ├── desafio63.py ├── desafio64.py ├── desafio65.py ├── desafio66.py ├── desafionumerosprimos.py ├── desafiooalindromo1.py ├── desafiopa1.py ├── desafiopagamento.py ├── desafiopalindromo.py ├── dungeongame.py ├── ex002.py ├── ex100.py ├── ex101.py ├── ex102.py ├── ex103.py ├── ex104.py ├── ex105.py ├── ex113.py ├── ex114.py ├── ex115a.py ├── ex71.py ├── ex72.py ├── ex73.py ├── ex74.py ├── ex75.2.py ├── ex75.py ├── ex76.py ├── ex77.py ├── ex79.py ├── ex80.py ├── ex81.py ├── ex82.1.py ├── ex82.py ├── ex90.py ├── ex91.py ├── ex92.py ├── ex93.py ├── ex94.py ├── ex95.1.py ├── ex95.py ├── ex96.py ├── exemplos de leitura 2.py ├── exemplos de leitura 3.py ├── exemplos de leitura 4.py ├── exemplos de leitura.py ├── fatorial.py ├── fibonacci.py ├── fibonacci1.py ├── hangmen.py ├── identificadordemaioridade.py ├── identificadordepeso.py ├── joguinhoporco.py ├── jokenpo.py ├── lifeinweeks.py ├── list comprehension condicional infnet.py ├── list comprehesion function infnet.py ├── list n sets comparison.py ├── listagemdepreços.py ├── listapareseimpares.py ├── lojinhamedieval.py ├── lovecalculator.py ├── matriz1.py ├── megasena.py ├── numberconversion.py ├── numberguessinggame.py ├── pa2.0.py ├── passwordgenerator.py ├── primechecker.py ├── progressãoaritmética2.0.py ├── progressãoaritmética3.0.py ├── pseudonyms.py ├── rascunho.py └── samegreedyflashdrives.py /AULA.21.7.py: -------------------------------------------------------------------------------- 1 | #RETORNO DE VALORES 2 | def somar(a=0, b=0, c=0): 3 | s = a + b + c 4 | return s 5 | 6 | 7 | 8 | r1 = somar(5, 6, 3) 9 | r2 = somar(3, 5) 10 | r3 = somar() 11 | r4 = somar(4, 9) 12 | print(f'As somas foram {r1}, {r2}, {r3}, {r4}.') -------------------------------------------------------------------------------- /AULA10.py: -------------------------------------------------------------------------------- 1 | nome=str(input('Qual é seu nome? ')) 2 | if nome == 'Daniel': 3 | print('Que nome lindo você tem!') 4 | else: 5 | print('Mas que nome horrível.') 6 | print('Bom dia, {}!'.format(nome)) 7 | -------------------------------------------------------------------------------- /AULA19.1.py: -------------------------------------------------------------------------------- 1 | pessoas = {'nome': 'Daniel', 'Sexo': 'M', 'Idade': '32'} 2 | pessoas['Peso'] = 100.5 3 | print(f'O {pessoas["nome"]}, tem {pessoas["Idade"]} anos e pesa {pessoas["Peso"]}kg.') 4 | print(pessoas.items()) 5 | print(pessoas.values()) 6 | print(pessoas.keys()) 7 | for k, v in pessoas.items(): 8 | print(f'{k} = {v}') 9 | print('=-='*10) 10 | for k in pessoas.values(): 11 | print(k) 12 | print('=-='*10) 13 | for k in pessoas.keys(): 14 | print(k) -------------------------------------------------------------------------------- /AULA19.3.py: -------------------------------------------------------------------------------- 1 | estado = {} 2 | brasil = [] 3 | for c in range(0,3): 4 | estado['uf'] = str(input('Unidade federativa: ')) 5 | estado['sigla'] = str(input('Sigla do estado: ')) 6 | brasil.append(estado.copy()) 7 | for estado in brasil: 8 | for keys, values in estado.items(): 9 | print(f'O campo {keys} tem valor {values}.') 10 | print('-='*10) 11 | 12 | 13 | -------------------------------------------------------------------------------- /AULA20.1.py: -------------------------------------------------------------------------------- 1 | def contador(* num): 2 | #for valor in num: 3 | #print(f'{valor} ', end='') 4 | tam = len(num) 5 | print(f'Recebi os valores {num} e são ao todo {tam} números.') 6 | # print() 7 | 8 | 9 | 10 | 11 | contador(8, 9, 6) 12 | contador(9, 0) 13 | contador(4, 7, 8, 4, 3, 0) 14 | 15 | -------------------------------------------------------------------------------- /AULA20.2.py: -------------------------------------------------------------------------------- 1 | def dobra(list): 2 | pos = 0 3 | while pos < len(list): 4 | list[pos] *= 2 5 | pos += 1 6 | 7 | 8 | 9 | valores = [3, 5, 8, 3, 1, 9] 10 | dobra(valores) 11 | print(valores) 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /AULA20.3.py: -------------------------------------------------------------------------------- 1 | def soma(*valores): 2 | s = 0 3 | for num in valores: 4 | s += num 5 | print(f'Somando os valores {valores} temos {s}.') 6 | 7 | 8 | soma(4, 9) 9 | soma(5, 8, 5, 7, 9) 10 | soma(9, 1, 4) 11 | -------------------------------------------------------------------------------- /AULA20.py: -------------------------------------------------------------------------------- 1 | def soma(a,b): 2 | print(f'A = {a} e B = {b}.') 3 | s = a + b 4 | print(f'A soma A + B = {s}.') 5 | print(s) 6 | print('_' * 15) 7 | 8 | 9 | soma(b=4, a=6) 10 | soma(9, 5) 11 | soma(7, 14) -------------------------------------------------------------------------------- /AULA21.1.py: -------------------------------------------------------------------------------- 1 | #INTERACTIVE HELP, DOCSTRINGS 2 | def contador(i, f, p): 3 | """ 4 | --->Faz uma contagem e mostra na tela 5 | :param i: Início da contagem 6 | :param f: Fim da contagem 7 | :param p: Passo da contagem 8 | :return: Sem retorno 9 | """ 10 | c = i 11 | while c <= f: 12 | print(f'{c}', end=' ') 13 | c += p 14 | print('FIM') 15 | 16 | 17 | contador(2, 10, 2) 18 | help(contador) -------------------------------------------------------------------------------- /AULA21.2.py: -------------------------------------------------------------------------------- 1 | #PARÂMETROS OPCIONAIS 2 | def somar(a=0, b=0, c=0): #<----- PARÂMETRO OPCIONAL 3 | s = a + b + c 4 | print(f'A soma vale {s}.') 5 | 6 | somar(2, 4, 8) 7 | somar() 8 | somar(c=3, a=654) 9 | somar(b=56) -------------------------------------------------------------------------------- /AULA21.3.py: -------------------------------------------------------------------------------- 1 | #ESCOPO DE VARIÁVEIS 2 | def teste(b): 3 | b +=4 #<-------- ESCOPO LOCAL 4 | c = 2 #<-------- ESCOPO LOCAL 5 | print(f' "a" dentro vale {a}.') 6 | print(f' "b" dentro vale {b}.') 7 | print(f' "c" dentro vale {c}.') 8 | 9 | 10 | a = 5 # <-------- ESCOPO GLOBAL 11 | teste(a) 12 | print(f' "a" fora vale {a}.') 13 | print(f' "b" fora vale {b}.') #<-----ERRO POR FALTA DE ESCOPO 14 | print(f' "c" fora vale {c}.') #<-----ERRO POR FALTA DE ESCOPO -------------------------------------------------------------------------------- /AULA21.4.py: -------------------------------------------------------------------------------- 1 | #ESCOPO DE VARIÁVEIS.1 2 | def teste(b): 3 | a = 8 #<-------- "a" LOCAL 4 | b +=4 #<-------- ESCOPO LOCAL 5 | c = 2 #<-------- ESCOPO LOCAL 6 | print(f' "a" dentro vale {a}.') # VALERÁ 8, POIS É 'LOCAL'. 7 | print(f' "b" dentro vale {b}.') # CONTINUARÁ VALENDO 9, POIS SOMARÁ COM O "a" GLOBAL. 8 | print(f' "c" dentro vale {c}.') 9 | 10 | 11 | a = 5 # <-------- ESCOPO GLOBAL 12 | teste(a) 13 | print(f' "a" fora vale {a}.') 14 | print(f' "b" fora vale {b}.') #<-----ERRO POR FALTA DE ESCOPO 15 | print(f' "c" fora vale {c}.') #<-----ERRO POR FALTA DE ESCOPO -------------------------------------------------------------------------------- /AULA21.5.py: -------------------------------------------------------------------------------- 1 | #ESCOPO DE VARIÁVEIS.3 2 | def funcao(): 3 | n1 = 4 4 | print(f' "n1" dentro vale {n1}.') 5 | 6 | 7 | n1 = 2 8 | funcao() 9 | print(f' "n1" fora vale {n1}.') -------------------------------------------------------------------------------- /AULA21.6.py: -------------------------------------------------------------------------------- 1 | #ESCOPO DE VARIÁVEIS.2 2 | def teste(b): 3 | global a # DEI A ORDEM PARA USAR A VARIÁVEL GLOBAL "a", AGORA A VARIÁVEL DENTRO DA FUNÇÃO SE TORNARÁ GLOBAL. 4 | a = 8 #<-------- "a" LOCAL 5 | b +=4 #<-------- ESCOPO LOCAL 6 | c = 2 #<-------- ESCOPO LOCAL 7 | print(f' "a" dentro vale {a}.') # VALERÁ 8, POIS É 'LOCAL'. 8 | print(f' "b" dentro vale {b}.') # CONTINUARÁ VALENDO 9, POIS SOMARÁ COM O "a" GLOBAL. 9 | print(f' "c" dentro vale {c}.') 10 | 11 | 12 | a = 5 # <-------- ESCOPO GLOBAL 13 | teste(a) 14 | print(f' "a" fora vale {a}.') 15 | -------------------------------------------------------------------------------- /AULA21.8.py: -------------------------------------------------------------------------------- 1 | def fatorial(num=1): 2 | f = 1 3 | for c in range(num, 0, -1): 4 | f *= c 5 | return f 6 | 7 | 8 | n = int(input('Digite um número: ')) 9 | print(f'O fatorial de {n} é igual a {fatorial(n)}.') 10 | 11 | f1 = fatorial(5) 12 | f2 = fatorial(9) 13 | f3 = fatorial(6) 14 | f4 = fatorial(3) 15 | print(f'Os resultados dos fatoriais acima são: {f1}, {f2}, {f3}, {f4}.') -------------------------------------------------------------------------------- /AULA21.9.py: -------------------------------------------------------------------------------- 1 | def par(n=0): 2 | if n % 2 == 0: 3 | return True 4 | else: 5 | return False 6 | 7 | num = int(input('Digite um número: ')) 8 | if par(num): 9 | print(f'É par.') 10 | else: 11 | print(f'É ímpar.') -------------------------------------------------------------------------------- /AULA21.py: -------------------------------------------------------------------------------- 1 | print(input.__doc__) 2 | help(input) -------------------------------------------------------------------------------- /AULA22.py: -------------------------------------------------------------------------------- 1 | import uteis 2 | 3 | num = int(input('Digite um valor: ')) 4 | fat = uteis.fatorial(num) 5 | print(f'O fatorial de {num} é {fat}.') 6 | print(f'O dobro de {num} é {uteis.dobro(num)}') 7 | -------------------------------------------------------------------------------- /AULA23.1.py: -------------------------------------------------------------------------------- 1 | try: 2 | a = int(input('Numerador: ')) 3 | b = int(input('Denominador: ')) 4 | r = a/b 5 | except (ValueError, TypeError): 6 | print('Tivemos um problema com os tipos de dados que você digitou' 7 | '.') 8 | else: 9 | print(f'O resultado é {r}.') 10 | finally: 11 | print('Volte sempre! Muito obrigado!') -------------------------------------------------------------------------------- /AULA23.py: -------------------------------------------------------------------------------- 1 | try: 2 | a = int(input('Numerador: ')) 3 | b = int(input('Denominador: ')) 4 | r = a/b 5 | except (ValueError, TypeError): 6 | print('Tivemos um problema com os tipos de dados que você digitou.') 7 | except ZeroDivisionError: 8 | print('Não é possível dividir por zero') 9 | except KeyboardInterrupt: 10 | print('O usuário preferiu não informar os dados.') 11 | except Exception as erro: 12 | print(f'O erro encontrado foi {erro.__cause__}') 13 | else: 14 | print(f'O resultado é {r}.') 15 | finally: 16 | print('Volte sempre! Muito obrigado!') -------------------------------------------------------------------------------- /AULA24.5.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danimoreira90/Logic_with_python/1e39e0ebf8987e60ec34315d9d3d7ff1c9b35afd/AULA24.5.py -------------------------------------------------------------------------------- /AULA24.6.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danimoreira90/Logic_with_python/1e39e0ebf8987e60ec34315d9d3d7ff1c9b35afd/AULA24.6.py -------------------------------------------------------------------------------- /BOLETINS.py: -------------------------------------------------------------------------------- 1 | ficha = [] 2 | while True: 3 | nome = str(input('Nome: ')) 4 | nota1 = float(input('Nota 1: ')) 5 | nota2 = float(input('Nota 2: ')) 6 | media = (nota1 + nota2)/2 7 | ficha.append([nome, [nota1, nota2], media]) 8 | resp = str(input('Quer continuar? [S/N]: ')) 9 | if resp in 'Nn': 10 | break 11 | print('-='*30) 12 | print(f'{"No.":<4},{"NOME":<10},{"MÉDIA":>8}') 13 | print('_'* 26) 14 | for i, a in enumerate(ficha): 15 | print(f'{i:<4}{a[0]:<10}{a[2]:>8.1f}') 16 | while True: 17 | print('_'* 35) 18 | opc = int(input('Mostrar notas de qual aluno? (999 para interromper): ')) 19 | if opc == 999: 20 | print('FINALIZANDO...') 21 | break 22 | if opc <= len(ficha) -1: 23 | print(f'Notas de {ficha[opc][0]} são {ficha[opc][1]}.') 24 | print('<<< VOLTE SEMPRE!! >>>') 25 | 26 | -------------------------------------------------------------------------------- /BOLETINS1.py: -------------------------------------------------------------------------------- 1 | ficha = [] 2 | while True: 3 | nome = str(input('Nome: ')) 4 | nota1 = float(input('Nota 1: ')) 5 | nota2 = float(input('Nota 2: ')) 6 | media = (nota1 + nota2)/2 7 | ficha.append([nome, [nota1, nota2], media]) 8 | resp = str(input('Quer continuar? [S/N]: ')) 9 | if resp in 'Nn': 10 | break 11 | print('-='*30) 12 | print(f'{"No.":<4},{"NOME":<10},{"MÉDIA":>8}') 13 | print('_'* 26) 14 | for i, a in enumerate(ficha): 15 | print(f'{i:<4}{a[0]:<10}{a[2]:>8.1f}') 16 | while True: 17 | print('_'* 35) 18 | opc = int(input('Mostrar notas de qual aluno? (999 para interromper): ')) 19 | if opc == 999: 20 | print('FINALIZANDO...') 21 | break 22 | if opc <= len(ficha) -1: 23 | print(f'Notas de {ficha[opc][0]} são {ficha[opc][1]}.') 24 | print('<<< VOLTE SEMPRE!! >>>') 25 | 26 | -------------------------------------------------------------------------------- /CADASTROJOGADOR.py: -------------------------------------------------------------------------------- 1 | 2 | player = {} 3 | totgols = [] 4 | pont = 0 5 | gols = [] 6 | player['Nome'] = str(input('Nome do Jogador: ')) 7 | player['Partidas'] = int(input(f'Quantas partidas {player["Nome"]} jogou? ')) 8 | player['Gols'] = totgols 9 | player['Total de Gols'] = pont 10 | for c in range(0, player["Partidas"]): 11 | gols = int(input(f'Quantos gols {player["Nome"]} marcou na {c+1}ª partida? ')) 12 | totgols.append(gols) 13 | pont += gols 14 | player['Total de Gols'] = pont 15 | print('=-'*40) 16 | print(player) 17 | print('=-'*40) 18 | for keys, values in player.items(): 19 | print(f'O Registro {keys} tem informativo {values}.') 20 | print('=-'*40) 21 | print(f'O jogador {player["Nome"]} jogou {player["Partidas"]} partidas.') 22 | for i, v in enumerate(totgols): 23 | print(f' => Na {i+1}ª partida {player["Nome"]} fez {v} gols. ') 24 | print(f'{player["Nome"]} fez um total de {pont} gols.') 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /CADASTROJOGADORES.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /CADASTROPESSOAS.py: -------------------------------------------------------------------------------- 1 | lista = [] 2 | pessoas = {} 3 | totidade = 0 4 | mulheres = {} 5 | listamulheres = [] 6 | while True: 7 | pessoas['Nome'] = str(input('Nome: ')) 8 | pessoas['Sexo'] = str(input('Sexo: [M/F]: ')).strip().upper()[0] 9 | if pessoas['Sexo'] == 'F': 10 | mulheres['Nome'] = pessoas['Nome'] 11 | listamulheres.append(mulheres.copy()) 12 | pessoas['Idade'] = int(input('Idade: ')) 13 | 14 | lista.append(pessoas.copy()) 15 | totidade += pessoas['Idade'] 16 | flag = str(input('Quer continuar [S/N]: ')).strip().upper()[0] 17 | if flag == 'N': 18 | break 19 | print('-='*35) 20 | print(f' - O grupo tem no total {len(lista)} pessoas.') 21 | media = (totidade)/(len(lista)) 22 | print(f' - A média de idade do grupo é de {media} anos.') 23 | #print(lista) 24 | #print(listamulheres) 25 | print(' - As mulheres cadastradas foram: ', end=' ') 26 | for m in range(0, (len(listamulheres))): 27 | print(listamulheres[m]["Nome"], end=' ') 28 | print() 29 | print(f' - Lista de pessoas com idade acima da média: ') 30 | pma = {} 31 | listapma = [] 32 | for i, v in enumerate(lista): 33 | if lista[i]["Idade"] > media: 34 | pma['Nome'] = (lista[i]["Nome"]) 35 | pma['Sexo'] = (lista[i]["Sexo"]) 36 | pma['Idade'] = (lista[i]["Idade"]) 37 | listapma.append(pma.copy()) 38 | #print(listapma) 39 | for i, v in enumerate(listapma): 40 | print(f'Nome: {listapma[i]["Nome"]}; Sexo: {listapma[i]["Sexo"]}; Idade: {listapma[i]["Idade"]}.') 41 | print('<<<<< ENCERRANDO PROGRAMA >>>>>') -------------------------------------------------------------------------------- /CADASTROPESSOAS1.py: -------------------------------------------------------------------------------- 1 | lista = [] 2 | pessoas = {} 3 | totidade = 0 4 | mulheres = {} 5 | listamulheres = [] 6 | pi = {} 7 | listapi = [] 8 | while True: 9 | pessoas['Nome'] = str(input('Nome: ')) 10 | pessoas['Sexo'] = str(input('Sexo: [M/F]: ')).strip().upper()[0] 11 | if pessoas['Sexo'] == 'F': 12 | mulheres['Nome'] = pessoas['Nome'] 13 | listamulheres.append(mulheres.copy()) 14 | pessoas['Idade'] = int(input('Idade: ')) 15 | 16 | lista.append(pessoas.copy()) 17 | totidade += pessoas['Idade'] 18 | flag = str(input('Quer continuar [S/N]: ')).strip().upper()[0] 19 | if flag == 'N': 20 | break 21 | print('-='*35) 22 | print(f' - O grupo tem no total {len(lista)} pessoas.') 23 | media = (totidade)/(len(lista)) 24 | print(f' - A média de idade do grupo é de {media} anos.') 25 | print(lista) 26 | #print(listamulheres) 27 | print(' - As mulheres cadastradas foram: ', end=' ') 28 | for m in range(0, (len(listamulheres))): 29 | print(listamulheres[m]["Nome"], end=' ') 30 | print() 31 | print(f' - Lista de pessoas com idade acima da média: ') 32 | pma = {} 33 | listapma = [] 34 | for i, v in enumerate(lista): 35 | if lista[i]["Idade"] > media: 36 | pma['Nome'] = (lista[i]["Nome"]) 37 | pma['Sexo'] = (lista[i]["Sexo"]) 38 | pma['Idade'] = (lista[i]["Idade"]) 39 | listapma.append(pma.copy()) 40 | print(listapma) 41 | for i, v in enumerate(listapma): 42 | print(f'Nome: {listapma[i]["Nome"]}; Sexo: {listapma[i]["Sexo"]}; Idade: {listapma[i]["Idade"]}.') 43 | print('<<<<< ENCERRANDO PROGRAMA >>>>>') -------------------------------------------------------------------------------- /CADASTROPESSOAS2.py: -------------------------------------------------------------------------------- 1 | lista = [] 2 | pessoas = {} 3 | totidade = 0 4 | mulheres = {} 5 | listamulheres = [] 6 | while True: 7 | pessoas['Nome'] = str(input('Nome: ')) 8 | pessoas['Sexo'] = str(input('Sexo: [M/F]: ')).strip().upper()[0] 9 | if pessoas['Sexo'] == 'F': 10 | mulheres['Nome'] = pessoas['Nome'] 11 | listamulheres.append(mulheres.copy()) 12 | pessoas['Idade'] = int(input('Idade: ')) 13 | 14 | lista.append(pessoas.copy()) 15 | totidade += pessoas['Idade'] 16 | flag = str(input('Quer continuar [S/N]: ')).strip().upper()[0] 17 | if flag == 'N': 18 | break 19 | print('-='*35) 20 | print(f' - O grupo tem no total {len(lista)} pessoas.') 21 | media = (totidade)/(len(lista)) 22 | print(f' - A média de idade do grupo é de {media} anos.') 23 | #print(lista) 24 | #print(listamulheres) 25 | print(' - As mulheres cadastradas foram: ', end=' ') 26 | for m in range(0, (len(listamulheres))): 27 | print(listamulheres[m]["Nome"], end=' ') 28 | print() 29 | print(f' - Lista de pessoas com idade acima da média: ') 30 | pma = {} 31 | listapma = [] 32 | for i, v in enumerate(lista): 33 | if lista[i]["Idade"] > media: 34 | pma['Nome'] = (lista[i]["Nome"]) 35 | pma['Sexo'] = (lista[i]["Sexo"]) 36 | pma['Idade'] = (lista[i]["Idade"]) 37 | listapma.append(pma.copy()) 38 | #print(listapma) 39 | for i, v in enumerate(listapma): 40 | print(f'Nome: {listapma[i]["Nome"]}; Sexo: {listapma[i]["Sexo"]}; Idade: {listapma[i]["Idade"]}.') 41 | print('<<<<< ENCERRANDO PROGRAMA >>>>>') -------------------------------------------------------------------------------- /CADASTROTRABALHADOR.py: -------------------------------------------------------------------------------- 1 | from datetime import date 2 | trabalhador = {} 3 | trabalhador['Nome'] = str(input('Nome: ')) 4 | trabalhador['Nascimento'] = int(input('Ano de nascimento: ')) 5 | trabalhador['CTPS'] = str(input('CTPS (Digite 0 caso não haja registro): ')) 6 | idade = date.today().year - trabalhador['Nascimento'] 7 | 8 | if trabalhador['CTPS'] == 0: 9 | trabalhador['CTPS'] = ('Não há registro.') 10 | print(trabalhador) 11 | else: 12 | trabalhador['Ano de contratação'] = int(input('Insira o ano de contratação: ')) 13 | aposentadoria = trabalhador['Ano de contratação'] + 35 14 | trabalhador['Salário'] = float(input('Insira o salário em R$: ')) 15 | trabalhador['Idade'] = idade 16 | trabalhador['Aposentadoria'] = aposentadoria 17 | print('=-'*15) 18 | print(trabalhador) 19 | print('=-'*15) 20 | for keys, values in trabalhador.items(): 21 | print(f'{keys} tem como registro {values}.') 22 | 23 | -------------------------------------------------------------------------------- /Desafio 39.py: -------------------------------------------------------------------------------- 1 | n1=float(input('Insira a primeira nota: ')) 2 | n2=float(input('Insira a segunda nota: ')) 3 | m=(n1+n2)/2 4 | if m < 5.0: 5 | print('\033[0;34mREPROVADO\033[m') 6 | elif m >= 5.0 and m < 6.9: 7 | print('\033[0;34mRECUPERAÇÃO\033[m') 8 | elif m >= 7.0: 9 | print('\033[0;34mAPROVADO\033[m') -------------------------------------------------------------------------------- /Desafio10.py: -------------------------------------------------------------------------------- 1 | n1 = float(input('Quantos Km seu carro rodou?')) 2 | n2 = float(input('Quantos dias ele foi alugado?')) 3 | n3 = 60*n2 4 | n4 = 0.15*n1 5 | print('O valor a pagar é R${}'.format(n3+n4)) 6 | -------------------------------------------------------------------------------- /Desafio13.py: -------------------------------------------------------------------------------- 1 | import math 2 | a=float(input('insira um angulo')) 3 | seno=math.sin(math.radians(a)) 4 | cosseno=math.cos(math.radians(a)) 5 | tangente=math.tan(math.radians(a)) 6 | print("O angulo é {:.2f} e seu seno, cosseno e tangente são {:.2f" 7 | "},{:.2f} e {:.2f}, respecticamente".format(a, seno, cosseno, tangente)) 8 | -------------------------------------------------------------------------------- /Desafio20.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | pygame.init() 3 | pygame.mixer.music.load('finalcountdown.mp3') 4 | pygame.mixer.music.play() 5 | pygame.event.wait() -------------------------------------------------------------------------------- /Desafio21.py: -------------------------------------------------------------------------------- 1 | nome=input('insira seu nome') 2 | print(nome.upper()) 3 | print(nome.lower()) 4 | print(nome.split()[0]) 5 | print((len(nome))-(nome.count(' '))) 6 | print((nome.find(' '))) 7 | 8 | 9 | -------------------------------------------------------------------------------- /Desafio22.py: -------------------------------------------------------------------------------- 1 | cid=str(input('Insira sua cidade ')).strip() 2 | print(cid[:5].upper()=='SANTO') -------------------------------------------------------------------------------- /Desafio23.py: -------------------------------------------------------------------------------- 1 | frase=str(input('Insira uma frase: ')).upper().strip() 2 | print('A letra a aparece {} vezes nesta frase'.format(frase.count('a'))) 3 | 4 | 5 | -------------------------------------------------------------------------------- /Desafio24.py: -------------------------------------------------------------------------------- 1 | nome=str(input('Insira seu nome completo: ')) 2 | print('Seu nome tem Silva? {}'.format(silva in nome).upper) -------------------------------------------------------------------------------- /Desafio25.py: -------------------------------------------------------------------------------- 1 | nome=str(input('Insira seu nome completo')) 2 | nome1=nome.split() 3 | 4 | print('Seu primeiro nome é {} e o último {}'.format((nome1[0]), (nome1[len(nome1)-1]))) 5 | 6 | 7 | -------------------------------------------------------------------------------- /Desafio26.py: -------------------------------------------------------------------------------- 1 | nome=str(input('Insira seu nome completo')) 2 | nome1=nome.split() 3 | 4 | print('Seu primeiro nome é {} e o último {}'.format((nome1[0]), (nome1[len(nome1)-1]))) 5 | 6 | 7 | -------------------------------------------------------------------------------- /Desafio27.py: -------------------------------------------------------------------------------- 1 | import random 2 | n=random.randint(0,5) 3 | numero=int(input('Insira um número entre 0 e 5')) 4 | if n==numero: 5 | print('você acertou') 6 | else: 7 | print('você errou') 8 | -------------------------------------------------------------------------------- /Desafio28.py: -------------------------------------------------------------------------------- 1 | v=float(input('insira a velocidade: ')) 2 | multa=(v-80)*7 3 | if v >80: 4 | print('você foi multado em {}'.format(multa)) 5 | else: 6 | print('você está abaixo da velocidade limite') 7 | -------------------------------------------------------------------------------- /Desafio29.py: -------------------------------------------------------------------------------- 1 | d=float(input('Insira a distância da viagem em km: ')) 2 | if d <=200: 3 | print('O valor de sua passagem é {}'.format((d*0.5))) 4 | else: 5 | print('O valor de sua passagem é {}'.format((d*0.45))) -------------------------------------------------------------------------------- /Desafio30.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | ano=int(input('Insira o ano a analisar, Insira 0 para analisar o ano atual')) 3 | if ano ==0: 4 | print('O ano inserido é {}'.format(datetime.date.today().year)) 5 | if ano % 4==0 and ano % 100 !=0 or ano % 400 ==0: 6 | print('O ano inserido é bissexto') 7 | else: 8 | print('O ano inserido não é bissexto') 9 | -------------------------------------------------------------------------------- /Desafio34.py: -------------------------------------------------------------------------------- 1 | s = float(input('Insira seu salário em R$: ')) 2 | a1 = ((s * 10) / 100) 3 | a2 = ((s * 15) / 100) 4 | if s > 1250.00: 5 | print('Seu aumento é de R${}'.format(a1)) 6 | if s < 1250.00: 7 | print('Seu aumento é de R${}'.format(a2)) 8 | -------------------------------------------------------------------------------- /Desafio35.py: -------------------------------------------------------------------------------- 1 | a=float(input('insira o comprimento da reta a: ')) 2 | b=float(input('insira o comprimento da reta b: ')) 3 | c=float(input('insira o comprimento da reta c: ')) 4 | if (b-c)a and (a-c)b and (a-b)c: 5 | print('é possível formar um triângulo') 6 | else: 7 | print('não é possível formar um triângulo') 8 | -------------------------------------------------------------------------------- /Desafio36.py: -------------------------------------------------------------------------------- 1 | v=float(input('Qual é o valor da casa em R$? ')) 2 | s=float(input('Qual é o salário do comprador em R$? ')) 3 | a=float(input('Em quantos anos será paga a casa? ')) 4 | if v/(a*12) < (s*30)/100: 5 | print('Seu empréstimo foi aprovado') 6 | else: 7 | print('Seu empréstimo foi recusado') 8 | 9 | -------------------------------------------------------------------------------- /Desafio37.py: -------------------------------------------------------------------------------- 1 | n1 = float(input('Insira o primeiro número: ')) 2 | n2 = float(input('Insira o segundo número: ')) 3 | if n1 > n2: 4 | print('O primeiro número é maior que o segundo') 5 | elif n2 > n1: 6 | print('O segundo número é maior que o primeiro') 7 | elif n1 == n2: 8 | print('Os números são iguais') 9 | -------------------------------------------------------------------------------- /Desafio38.py: -------------------------------------------------------------------------------- 1 | i=int(input('Insira sua idade: ')) 2 | if i < 18: 3 | print('Você ainda irá se alistar. Falta {} anos'.format(18-i)) 4 | elif i == 18: 5 | print('É o momento de ir se alistar.') 6 | elif i > 18: 7 | print('Já passou da data de alistamento. Passaram {} anos.'.format(i-18)) -------------------------------------------------------------------------------- /Desafio40.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | a=int(input('Insira seu ano de nascimento: ')) 3 | 4 | a1= datetime.date.today().year 5 | i = a1 - a 6 | if i < 9: 7 | print('Categoria \033[0;32mMIRIM\033[m') 8 | elif 9 <= i < 14: 9 | print('Categoria \033[0;35mINFANTIL\033[m') 10 | elif 14 <= i < 19: 11 | print('Categoria \033[0;33mJUNIOR\033[m') 12 | elif 19 <= i <= 20: 13 | print('Categoria \033[0;34mSÊNIOR\033[m') 14 | else: 15 | print('Categoria \033[0;31mMASTER\033[m') -------------------------------------------------------------------------------- /Desafio41.py: -------------------------------------------------------------------------------- 1 | a=float(input('insira o comprimento da reta a: ')) 2 | b=float(input('insira o comprimento da reta b: ')) 3 | c=float(input('insira o comprimento da reta c: ')) 4 | if (b-c)a and (a-c)b and (a-b)c: 5 | print('é possível formar um triângulo') 6 | if a > b + c or b > c + a or c > a + b: 7 | print('Não é possível formar um triângulo') 8 | elif a == b == c: 9 | print('Esse triângulo é EQUILÁTERO') 10 | elif a == b !=c or a == c !=b or b == c != a: 11 | print('Esse triângulo é ISOSCELES') 12 | elif a !=b != c: 13 | print('Esse triângulo é ESCALENO') 14 | -------------------------------------------------------------------------------- /Desafio42.py: -------------------------------------------------------------------------------- 1 | a=float(input('insira o comprimento da reta a: ')) 2 | b=float(input('insira o comprimento da reta b: ')) 3 | c=float(input('insira o comprimento da reta c: ')) 4 | if (b-c)a and (a-c)b and (a-b)c: 5 | print('é possível formar um triângulo') 6 | if a > b + c or b > c + a or c > a + b: 7 | print('Não é possível formar um triângulo') 8 | elif a == b == c: 9 | print('Esse triângulo é EQUILÁTERO') 10 | elif a == b !=c or a == c !=b or b == c != a: 11 | print('Esse triângulo é ISOSCELES') 12 | elif a !=b != c: 13 | print('Esse triângulo é ESCALENO') 14 | -------------------------------------------------------------------------------- /Desafio43.py: -------------------------------------------------------------------------------- 1 | p=float(input('Insira seu peso em kg: ')) 2 | a=float(input('Insira sua altura em m: ')) 3 | imc=p/a**2 4 | if imc < 18.5: 5 | print('Você está abaixo do peso') 6 | elif 18.5 <= imc < 25: 7 | print('Você está no peso ideal') 8 | elif 25 <= imc < 30: 9 | print('Você está com sobrepeso') 10 | elif 30 <= imc < 40: 11 | print('Você tem obesidade') 12 | else: 13 | print('Você tem obesidade mórbida') 14 | -------------------------------------------------------------------------------- /Desafio44.py: -------------------------------------------------------------------------------- 1 | p=float(input('Insira o Valor do produto em R$: ')) 2 | cp=str(input('Insira a condição de pagamento: ')).strip() 3 | if cp.find('dinheiro/cheque'): 4 | print('Você pagará R${}'.format(p-(p*10)/100)) 5 | if cp.find('cartão'): 6 | print('Você pagará R${}'.format(p-(p*5)/100)) -------------------------------------------------------------------------------- /Desafio45.py: -------------------------------------------------------------------------------- 1 | import random 2 | x=int(input('Jogue Pedra, Papel ou Tesoura')) 3 | random.randint(a, b, c) 4 | 5 | 6 | -------------------------------------------------------------------------------- /Desafio46.py: -------------------------------------------------------------------------------- 1 | num = int(input('Insira um número inteiro: ')) 2 | print('''Escolha uma das bases para conversão: 3 | [1]Para BINÁRIO 4 | [2]Para OCTAL 5 | [3]Para HEXADECIMAL''') 6 | opção = int(input('Sua opção: ')) 7 | if opção == 1: 8 | print('{} convertido para BINÁRIO é {}'.format(num, bin(num)[2:])) 9 | elif opção == 2: 10 | print('{} convertido para OCTAL é {}'.format(num, oct(num)[2:])) 11 | elif opção == 3: 12 | print('{} convertido para HEXADECIMAL é {}'.format(num, hex(num)[2:])) 13 | else: 14 | print('Opção inválida') 15 | 16 | -------------------------------------------------------------------------------- /Desafio47.py: -------------------------------------------------------------------------------- 1 | num = int(input('Insira um número inteiro: ')) 2 | print('''Escolha uma das bases para conversão: 3 | [1]Para BINÁRIO 4 | [2]Para OCTAL 5 | [3]Para HEXADECIMAL''') 6 | opção = int(input('Sua opção: ')) 7 | if opção == 1: 8 | print('{} convertido para BINÁRIO é {}'.format(num, bin(num)[2:])) 9 | elif opção == 2: 10 | print('{} convertido para OCTAL é {}'.format(num, oct(num)[2:])) 11 | elif opção == 3: 12 | print('{} convertido para HEXADECIMAL é {}'.format(num, hex(num)[2:])) 13 | else: 14 | print('Opção inválida') 15 | 16 | -------------------------------------------------------------------------------- /Desafio51.py: -------------------------------------------------------------------------------- 1 | preço = float(input('Insira o valor do produto em R$: ')) 2 | print('[0]à vista dinheiro/cheque: 10% de desconto' 3 | '\n[1]à vista no cartão: 5% de desconto \n[2]Em até 2x no cartão: preço formal\n[3]3x ou mais no cartão: 20% de juros') 4 | pagamento = int(input('Insira a opção de pagamento: ')) 5 | 6 | if pagamento == 0: 7 | print('Você recebeu 10% de desconto e pagará R${}'.format(preço-(preço*10)/100)) 8 | if pagamento == 1: 9 | print('Você recebeu 5% de desconto e pagará R${}'.format(preço-(preço*5)/100)) 10 | if pagamento == 2: 11 | print('Você pagará o preço formal de R${}, sendo sua parcela R${}'.format(preço, (preço)/2)) 12 | elif pagamento == 3: 13 | print("Você terá 20% de juros, sendo o valor total R${} e sua parcela R${}".format(((preço + (preço * 20) / 100))), 14 | (((preço+(preço*20)/100))) / 3) 15 | -------------------------------------------------------------------------------- /Exercício.py: -------------------------------------------------------------------------------- 1 | name = "Daniel" 2 | print("Hello " + name) 3 | -------------------------------------------------------------------------------- /Fizzbuzz.py: -------------------------------------------------------------------------------- 1 | #Write your code below this row 👇 2 | for n in range(1, 101): 3 | if n % 3 == 0 and n % 5 ==0 : 4 | print('FizzBuzz') 5 | elif n % 3 == 0: 6 | print('Fizz') 7 | elif n % 5 == 0: 8 | print('Buzz') 9 | else: 10 | print(n) 11 | -------------------------------------------------------------------------------- /Jo-Ken-Po.py: -------------------------------------------------------------------------------- 1 | rock = ''' 2 | _______ 3 | ---' ____) 4 | (_____) 5 | (_____) 6 | (____) 7 | ---.__(___) 8 | ''' 9 | 10 | paper = ''' 11 | _______ 12 | ---' ____)____ 13 | ______) 14 | _______) 15 | _______) 16 | ---.__________) 17 | ''' 18 | 19 | scissors = ''' 20 | _______ 21 | ---' ____)____ 22 | ______) 23 | __________) 24 | (____) 25 | ---.__(___) 26 | ''' 27 | 28 | #Write your code below this line 👇 29 | from random import randint 30 | options = [''' 31 | _______ 32 | ---' ____) 33 | (_____) 34 | (_____) 35 | (____) 36 | ---.__(___) 37 | ''', ''' 38 | _______ 39 | ---' ____)____ 40 | ______) 41 | _______) 42 | _______) 43 | ---.__________) 44 | ''', ''' 45 | _______ 46 | ---' ____)____ 47 | ______) 48 | __________) 49 | (____) 50 | ---.__(___) 51 | ''' 52 | ] 53 | choice = options[int(input('What do you choose? Type 0 for Rock, 1 for paper or 2 for scissors.'))] 54 | computerchoice = options[randint(0,2)] 55 | print('You choose:') 56 | print(choice) 57 | print('Computer chose:') 58 | print(computerchoice) 59 | if choice == options[0] and computerchoice == options[0] or choice == options[1] and computerchoice == options[1] or choice == options[2] and computerchoice == options[2]: 60 | print('Draw.') 61 | elif choice == options[1] and computerchoice == options[0]: 62 | print('You win.') 63 | elif choice == options[2] and computerchoice == options[0]: 64 | print('You lose.') 65 | elif choice == options[0] and computerchoice == options[1]: 66 | print('You lose.') 67 | elif choice == options[2] and computerchoice == options[1]: 68 | print('You win.') 69 | elif choice == options[0] and computerchoice == options[2]: 70 | print('You win.') 71 | elif choice == options[1] and computerchoice == options[2]: 72 | print('You lose.') 73 | 74 | -------------------------------------------------------------------------------- /PALPITESMEGASENA.py: -------------------------------------------------------------------------------- 1 | import random 2 | import time 3 | print('__'*30) 4 | print('{:^50}'.format('JOGO DA MEGA SENA')) 5 | print('__'*30) 6 | lista = [] 7 | jogos = [] 8 | quant = int(input('Quantos jogos a serem sorteados? ')) 9 | tot = 1 10 | while tot <= quant: 11 | cont = 0 12 | while True: 13 | num = random.randint(1,60) 14 | if num not in lista: 15 | lista.append(num) 16 | cont += 1 17 | if cont >= 6: 18 | break 19 | lista.sort() 20 | jogos.append(lista[:]) 21 | lista.clear() 22 | tot += 1 23 | print('-='*3, f' SORTEANDO {quant} JOGOS', '-=' *3) 24 | for i, l in enumerate(jogos): 25 | print(f'Jogo {i+1}: {l}') 26 | time.sleep(1) 27 | print('-=' *5, '<< BONS JOGOS!! >>', '-=' *5) 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /PAROUIMPAR.py: -------------------------------------------------------------------------------- 1 | import random 2 | v = 0 3 | print('=-' * 20) 4 | print('VAMOS JOGAR PAR OU ÍMPAR!') 5 | print('=-' * 20) 6 | while True: 7 | computador = random.randint(0, 10) 8 | jogador = int(input('Diga um valor: ')) 9 | resultado = jogador + computador 10 | escolha = ' ' 11 | while escolha not in 'PI': 12 | escolha = str(input('Faça sua escolha: Par ou ímpar [P/I]:')).strip().upper()[0] 13 | print(f"Você jogou {jogador} e o computador {computador}. O resultado foi {resultado}") 14 | if resultado % 2 == 0: 15 | print('O resultado foi PAR!') 16 | else: 17 | print('O resultado foi ÍMPAR!') 18 | if escolha == 'P': 19 | if resultado % 2 == 0: 20 | print('Você VENCEU!') 21 | v += 1 22 | else: 23 | print('Você PERDEU!') 24 | break 25 | elif escolha == 'I': 26 | if resultado % 2 == 1: 27 | print('Você VENCEU!') 28 | v += 1 29 | else: 30 | print('Você PERDEU!') 31 | break 32 | print('Vamos jogar novamente...') 33 | print('Jogo finalizado. Você teve {} vitórias'.format(v)) -------------------------------------------------------------------------------- /PYTHONINTERACTIVEHELPSYSTEM.py: -------------------------------------------------------------------------------- 1 | from time import sleep 2 | c = ('\033[m', #0 - Sem Cores 3 | '\033[0;30;41m', #1 - Vermelho 4 | '\033[0;30;42m', #2 - Verde 5 | '\033[0;30;43m', #3 - Amarelo 6 | '\033[0;30;44m', #4 - Azul 7 | '\033[0;30;45m', #5 - Roxo 8 | '\033[7;30m' #6 - Branco 9 | ) 10 | 11 | def ajuda(com): 12 | título(f'Acessando o manual do comando \'{com}\'', 4) 13 | print(c[6], end='') 14 | help(com) 15 | print(c[0], end='') 16 | sleep(2) 17 | 18 | 19 | def título(msg, cor=0): 20 | tam = len(msg) + 4 21 | print(c[cor], end='') 22 | print('~' * tam) 23 | print(f' {msg}') 24 | print('~' * tam) 25 | print(c[0], end='') 26 | sleep(1) 27 | 28 | #PROGRAMA PRINCIPAL 29 | comando = '' 30 | while True: 31 | título('SISTEMA DE AJUDA PyHELP', 2) 32 | comando = str(input("Função ou biblioteca> ")) 33 | if comando.upper() == 'FIM': 34 | break 35 | else: 36 | ajuda(comando) 37 | título('ATÉ LOGO', 1) -------------------------------------------------------------------------------- /PythonTeste.py: -------------------------------------------------------------------------------- 1 | n1 = int(input('digite um valor')) 2 | n2 = int(input('digite outro valor')) 3 | s = n1 + n2 4 | print('a soma vale, {}'.format(n1+n2)) 5 | -------------------------------------------------------------------------------- /aula10.2.py: -------------------------------------------------------------------------------- 1 | n1=float(input('Digite a primeira nota: ')) 2 | n2=float(input('Digite a segunda nota: ')) 3 | media=(n1+n2)/2 4 | print('A sua média foi {}'.format(media)) 5 | if media>=6: 6 | print('Você teve uma boa média.') 7 | else: 8 | print('Você teve uma média ruim.') 9 | -------------------------------------------------------------------------------- /aula12.py: -------------------------------------------------------------------------------- 1 | import time 2 | import emoji 3 | for c in range(10,0,-1): 4 | time.sleep(1) 5 | print(c) 6 | print('BOOOOOOOOM!!!!!') -------------------------------------------------------------------------------- /aula14.py: -------------------------------------------------------------------------------- 1 | r = 'S' 2 | while r == 'S': 3 | n = int(input('Digite um valor: ')) 4 | r = str=input('Quer continuar [S/N]: ').upper() 5 | print('FIM') -------------------------------------------------------------------------------- /aula15.py: -------------------------------------------------------------------------------- 1 | nome = 'Jose' 2 | idade = 33 3 | salário = 5967.87 4 | print(f'O {nome} tem {idade} anos e recebe {salário} de salário.') 5 | print('O {} tem {} anos e recebe {} de salário.'.format(nome, idade, salário)) -------------------------------------------------------------------------------- /aula16.py: -------------------------------------------------------------------------------- 1 | lanche = ('Hambúrguer', 'Suco', 'Pizza', 'Pudim', 'Batata frita') 2 | for cont in range(0, len(lanche)): 3 | print(f'Irei comer {lanche[cont]}.') 4 | #for comida in lanche: 5 | # print(f'Irei comer {comida}') 6 | for pos, comida in enumerate(lanche): 7 | print(f'Irei comer {comida}.') 8 | 9 | print('SOU OBESO!') -------------------------------------------------------------------------------- /aula17.1.py: -------------------------------------------------------------------------------- 1 | valores = [] 2 | for cont in range(0,5): 3 | valores.append(int(input('Digite um valor: '))) 4 | 5 | for c, v in enumerate(valores): 6 | print(f'Na posição {c}, encontrei o valor {v}!') 7 | print('Cheguei ao final da lista.') -------------------------------------------------------------------------------- /aula17.2.py: -------------------------------------------------------------------------------- 1 | a = [2, 3, 4, 7] 2 | b = a[:] 3 | b[2] = 8 4 | print(f'''Lista A: {a} 5 | Lista B: {b}''') -------------------------------------------------------------------------------- /aula17.py: -------------------------------------------------------------------------------- 1 | num = [5, 6, 9, 0, 4, 7] 2 | num[4] = 3 3 | num.append(12) 4 | num.insert(3, 44) 5 | if 76 in num: 6 | num.remove(76) 7 | else: 8 | print('Não existe o valor 76.') 9 | num.sort() 10 | num.pop() 11 | print(num) 12 | print(f'Essa lista tem {len(num)} números.') -------------------------------------------------------------------------------- /aula18.1.py: -------------------------------------------------------------------------------- 1 | galera = [['João', 19], ['Ana', 33], ['Joaquim', 13], ['Maria', 45]] 2 | for pessoa in galera: 3 | print(f'{pessoa[0]} tem {pessoa[1]} anos de idade.') -------------------------------------------------------------------------------- /aula18.2.py: -------------------------------------------------------------------------------- 1 | galera = list() 2 | dado = list() 3 | totmai = totmen = 0 4 | for c in range(0, 5): 5 | dado.append(str(input('Nome: '))) 6 | dado.append(int(input('Idade: '))) 7 | galera.append(dado[:]) 8 | dado.clear() 9 | 10 | for pessoa in galera: 11 | if pessoa[1] >= 21: 12 | print(f'{pessoa[0]} é maior de idade.') 13 | totmai += 1 14 | else: 15 | print(f'{pessoa[0]} é menor de idade.') 16 | totmen += 1 17 | 18 | print(f'Temos {totmai} maiores de idade e {totmen} menores de idade.') -------------------------------------------------------------------------------- /aula18.py: -------------------------------------------------------------------------------- 1 | teste = [] 2 | teste.append('Daniel') 3 | teste.append(32) 4 | galera = [] 5 | galera.append(teste[:]) 6 | teste[0] = 'Bauer' 7 | teste[1] = 33 8 | galera.append(teste[:]) 9 | print(galera) 10 | -------------------------------------------------------------------------------- /aula19.2.py: -------------------------------------------------------------------------------- 1 | brasil = [] 2 | estado1 = {'uf': 'Rio de Janeiro', 'sigla': 'rj'} 3 | estado2 = {'uf': 'São Paulo', 'sigla': 'sp'} 4 | brasil.append(estado1) 5 | brasil.append(estado2) 6 | print(brasil[0]['uf'], brasil[1]['uf']) -------------------------------------------------------------------------------- /bandnamegenerator.py: -------------------------------------------------------------------------------- 1 | #1. Create a greeting for your program. 2 | print('Welcome to the Band Name generator.') 3 | #2. Ask the user for the city that they grew up in. 4 | city = str(input("What's the name of the city you grew up in? ")) 5 | print(city) 6 | #3. Ask the user for the name of a pet. 7 | pet = str(input("What's your pet's name? ")) 8 | print(pet) 9 | #4. Combine the name of their city and pet and show them their band name. 10 | print(f'Your band name could be {city} {pet}.') 11 | #5. Make sure the input cursor shows on a new line, see the example at: 12 | # https://replit.com/@appbrewery/band-name-generator-end -------------------------------------------------------------------------------- /bankingroulette.py: -------------------------------------------------------------------------------- 1 | # Split string method 2 | names_string = input("Give me everybody's names, separated by a comma. ") 3 | names = names_string.split(", ") 4 | # 🚨 Don't change the code above 👆 5 | 6 | #Write your code below this line 👇 7 | from random import randint 8 | rpindex = randint(0, len(names)) 9 | print(f'{names[rpindex]} is going to buy the meal today!') 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /blackjack.py: -------------------------------------------------------------------------------- 1 | ############### Blackjack Project ##################### 2 | 3 | #Difficulty Normal 😎: Use all Hints below to complete the project. 4 | #Difficulty Hard 🤔: Use only Hints 1, 2, 3 to complete the project. 5 | #Difficulty Extra Hard 😭: Only use Hints 1 & 2 to complete the project. 6 | #Difficulty Expert 🤯: Only use Hint 1 to complete the project. 7 | 8 | ############### Our Blackjack House Rules ##################### 9 | 10 | ## The deck is unlimited in size. 11 | ## There are no jokers. 12 | ## The Jack/Queen/King all count as 10. 13 | ## The the Ace can count as 11 or 1. 14 | ## Use the following list as the deck of cards: 15 | ##cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] 16 | ## The cards in the list have equal probability of being drawn. 17 | ## Cards are not removed from the deck as they are drawn. 18 | ## The computer is the dealer. 19 | 20 | ##################### Hints ##################### 21 | 22 | #Hint 1: Go to this website and try out the Blackjack game: 23 | # https://games.washingtonpost.com/games/blackjack/ 24 | #Then try out the completed Blackjack project here: 25 | # http://blackjack-final.appbrewery.repl.run 26 | 27 | #Hint 2: Read this breakdown of program requirements: 28 | # http://listmoz.com/view/6h34DJpvJBFVRlZfJvxF 29 | #Then try to create your own flowchart for the program. 30 | 31 | #Hint 3: Download and read this flow chart I've created: 32 | # https://drive.google.com/uc?export=download&id=1rDkiHCrhaf9eX7u7yjM1qwSuyEk-rPnt 33 | 34 | #Hint 4: Create a deal_card() function that uses the List below to *return* a random card. 35 | #11 is the Ace. 36 | import random 37 | cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] 38 | def deal_card(): 39 | return random.choice(cards) 40 | 41 | 42 | 43 | #Hint 5: Deal the user and computer 2 cards each using deal_card() and append(). 44 | user_cards = [deal_card(), deal_card()] 45 | # user_cards.append(deal_card()) 46 | # user_cards.append(deal_card()) 47 | computer_cards = [deal_card(), deal_card()] 48 | # print(user_cards) 49 | # print(computer_cards) 50 | 51 | #Hint 6: Create a function called calculate_score() that takes a List of cards as input 52 | #and returns the score. 53 | #Look up the sum() function to help you do this. 54 | def calculate_score(cardlist): 55 | if sum(cardlist) == 21: 56 | return 0 57 | if 11 in cardlist: 58 | if sum(cardlist) > 21: 59 | cardlist.remove(11) 60 | cardlist.append(1) 61 | return sum(cardlist) 62 | 63 | def compare(user_score, computer_score): 64 | #Bug fix. If you and the computer are both over, you lose. 65 | if user_score > 21 and computer_score > 21: 66 | return "You went over. You lose 😤" 67 | 68 | 69 | if user_score == computer_score: 70 | return "Draw 🙃" 71 | elif computer_score == 0: 72 | return "Lose, opponent has Blackjack 😱" 73 | elif user_score == 0: 74 | return "Win with a Blackjack 😎" 75 | elif user_score > 21: 76 | return "You went over. You lose 😭" 77 | elif computer_score > 21: 78 | return "Opponent went over. You win 😁" 79 | elif user_score > computer_score: 80 | return "You win 😃" 81 | else: 82 | return "You lose 😤" 83 | 84 | 85 | #Hint 7: Inside calculate_score() check for a blackjack (a hand with only 2 cards: ace + 10) and return 0 instead of the actual score. 0 will represent a blackjack in our game. 86 | 87 | #Hint 8: Inside calculate_score() check for an 11 (ace). If the score is already over 21, remove the 11 and replace it with a 1. You might need to look up append() and remove(). 88 | 89 | #Hint 9: Call calculate_score(). If the computer or the user has a blackjack (0) or if the user's score is over 21, then the game ends. 90 | while True: 91 | flag = input("Do you want to play a blackjack game? [Y/N]:").upper()[0] 92 | if flag == 'Y': 93 | user_cards = [deal_card(), deal_card()] 94 | computer_cards = [deal_card(), deal_card()] 95 | print('_' * 45) 96 | print(f"Your hand: {user_cards}\nDealer's first card:{computer_cards[0]}") 97 | print('_' * 45) 98 | user = calculate_score(user_cards) 99 | computer = calculate_score(computer_cards) 100 | print(f"Your score: {user}") 101 | if user == 0: 102 | print("You have a Blackjack! You win!") 103 | break 104 | elif computer == 0: 105 | print("The dealer has a Blackjack! You lose.") 106 | break 107 | elif user > 21: 108 | print("You're over 21. You lose.") 109 | break 110 | else: 111 | print("Come back anytime.") 112 | break 113 | while computer != 0 and computer < 17: 114 | computer_cards.append(deal_card()) 115 | computer = calculate_score(computer_cards) 116 | if computer > 17: 117 | break 118 | draw = input("Draw another card?: [Y/N]").upper()[0] 119 | if draw == 'Y': 120 | user_cards.append(deal_card()) 121 | print(f"Your hand: {user_cards}\nYour score: {user}") 122 | print(f"Dealer's hand: {computer_cards}\nDealer's score: {computer}") 123 | print(compare(user, computer)) 124 | if draw =='N': 125 | print(f"Your hand: {user_cards}\nYour score: {user}") 126 | print(f"Dealer's hand: {computer_cards}\nDealer's score: {computer}") 127 | print(compare(user, computer)) 128 | 129 | #Hint 10: If the game has not ended, ask the user if they want to draw another card. If yes, then use the deal_card() function to add another card to the user_cards List. If no, then the game has ended. 130 | 131 | #Hint 11: The score will need to be rechecked with every new card drawn and the checks in Hint 9 need to be repeated until the game ends. 132 | 133 | #Hint 12: Once the user is done, it's time to let the computer play. The computer should keep drawing cards as long as it has a score less than 17. 134 | 135 | #Hint 13: Create a function called compare() and pass in the user_score and computer_score. If the computer and user both have the same score, then it's a draw. If the computer has a blackjack (0), then the user loses. If the user has a blackjack (0), then the user wins. If the user_score is over 21, then the user loses. If the computer_score is over 21, then the computer loses. If none of the above, then the player with the highest score wins. 136 | 137 | #Hint 14: Ask the user if they want to restart the game. If they answer yes, clear the console and start a new game of blackjack and show the logo from art.py. 138 | 139 | -------------------------------------------------------------------------------- /bmicalculator.py: -------------------------------------------------------------------------------- 1 | # 🚨 Don't change the code below 👇 2 | height = input("enter your height in m: ") 3 | weight = input("enter your weight in kg: ") 4 | # 🚨 Don't change the code above 👆 5 | 6 | #Write your code below this line 👇 7 | w = float(weight) 8 | h = float(height) 9 | bmi = round(w/h**2) 10 | print(bmi) 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /bmicalculator2.0.py: -------------------------------------------------------------------------------- 1 | 2 | height = float(input("enter your height in m: ")) 3 | weight = float(input("enter your weight in kg: ")) 4 | 5 | 6 | 7 | bmi = round(weight/height**2) 8 | if bmi < 18.5: 9 | print(f'Your BMI is {bmi}, you are \033[1munderweight\033[0m.') 10 | elif 18.5 < bmi < 25: 11 | print(f'Your BMI is {bmi}, you have a \033[1mnormal weight\033[0m.') 12 | elif 25 < bmi < 30: 13 | print(f'Your BMI is {bmi}, you are \033[1mslightly overweight\033[0m.') 14 | elif 30 < bmi < 35: 15 | print(f'Your BMI is {bmi}, you are \033[1mobese\033[0m.') 16 | else: 17 | print(f'Your BMI is {bmi}, you are \033[1mclinically obese\033[0m.') 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /caesarcipherartart.py: -------------------------------------------------------------------------------- 1 | logo = """ 2 | ,adPPYba, ,adPPYYba, ,adPPYba, ,adPPYba, ,adPPYYba, 8b,dPPYba, 3 | a8" "" "" `Y8 a8P_____88 I8[ "" "" `Y8 88P' "Y8 4 | 8b ,adPPPPP88 8PP""""""" `"Y8ba, ,adPPPPP88 88 5 | "8a, ,aa 88, ,88 "8b, ,aa aa ]8I 88, ,88 88 6 | `"Ybbd8"' `"8bbdP"Y8 `"Ybbd8"' `"YbbdP"' `"8bbdP"Y8 88 7 | 88 88 8 | "" 88 9 | 88 10 | ,adPPYba, 88 8b,dPPYba, 88,dPPYba, ,adPPYba, 8b,dPPYba, 11 | a8" "" 88 88P' "8a 88P' "8a a8P_____88 88P' "Y8 12 | 8b 88 88 d8 88 88 8PP""""""" 88 13 | "8a, ,aa 88 88b, ,a8" 88 88 "8b, ,aa 88 14 | `"Ybbd8"' 88 88`YbbdP"' 88 88 `"Ybbd8"' 88 15 | 88 16 | 88 17 | """ -------------------------------------------------------------------------------- /caesarciphercommented.py: -------------------------------------------------------------------------------- 1 | from art import logo 2 | alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] 3 | 4 | def caesar(start_text, shift_amount, cipher_direction): 5 | print('_' * 50) 6 | end_text = "" 7 | if cipher_direction == "decode": 8 | shift_amount *= -1 9 | for char in start_text: 10 | if char in alphabet: 11 | position = alphabet.index(char) 12 | new_position = position + shift_amount 13 | end_text += alphabet[new_position] 14 | else: 15 | end_text += char 16 | #TODO-3: What happens if the user enters a number/symbol/space? 17 | #Can you fix the code to keep the number/symbol/space when the text is encoded/decoded? 18 | #e.g. start_text = "meet me at 3" 19 | #end_text = "•••• •• •• 3" 20 | 21 | print(f"Here's the {cipher_direction}d result: {end_text}") 22 | 23 | #TODO-1: Import and print the logo from art.py when the program starts. 24 | print(logo) 25 | 26 | #TODO-4: Can you figure out a way to ask the user if they want to restart the cipher program? 27 | #e.g. Type 'yes' if you want to go again. Otherwise type 'no'. 28 | #If they type 'yes' then ask them for the direction/text/shift again and call the caesar() function again? 29 | #Hint: Try creating a while loop that continues to execute the program if the user types 'yes'. 30 | while True: 31 | print('_' * 50) 32 | direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n") 33 | print('_' * 50) 34 | text = input("Type your message:\n").lower() 35 | print('_' * 50) 36 | shift = int(input("Type the shift number:\n")) 37 | print('_' * 50) 38 | #TODO-2: What if the user enters a shift that is greater than the number of letters in the alphabet? 39 | #Try running the program and entering a shift number of 45. 40 | #Add some code so that the program continues to work even if the user enters a shift number greater than 26. 41 | #Hint: Think about how you can use the modulus (%). 42 | shift = shift % 26 43 | caesar(start_text=text, shift_amount=shift, cipher_direction=direction) 44 | run = str(input("type 'yes' if you want to go again. Otherwise, type 'no'.")).lower() 45 | if run == 'no': 46 | break 47 | print('Goodbye! Come back whenever!') -------------------------------------------------------------------------------- /caixaeletronico.py: -------------------------------------------------------------------------------- 1 | print('==' * 30) 2 | print('{:^30}'.format('BANCO DANIELS')) 3 | print('==' * 30) 4 | valor = int(input('Que valor você quer sacar? R$')) 5 | total = valor 6 | ced = 50 7 | totced = 0 8 | while True: 9 | if total >= ced: 10 | total -= ced 11 | totced += 1 12 | else: 13 | if totced > 0: 14 | print(f'Total de {totced} cédulas de R${ced}') 15 | if ced == 50: 16 | ced = 20 17 | elif ced == 20: 18 | ced = 10 19 | elif ced == 10: 20 | ced = 1 21 | totced = 0 22 | if total == 0: 23 | break -------------------------------------------------------------------------------- /calculator.py: -------------------------------------------------------------------------------- 1 | def add(n1, n2): 2 | return n1 + n2 3 | 4 | def subtract(n1, n2): 5 | return n1 - n2 6 | 7 | def multiply(n1, n2): 8 | return n1 * n2 9 | 10 | def divide(n1, n2): 11 | return n1 / n2 12 | 13 | ops = { 14 | "+":add, 15 | "-":subtract, 16 | "*":multiply, 17 | "/":divide 18 | } 19 | def calculator(): 20 | 21 | num1 = float(input("What's the first number?: ")) 22 | for symbol in ops: 23 | print(symbol) 24 | 25 | while True: 26 | operations = input("Pick an operation: ") 27 | num2 = float(input("What's the next number?: ")) 28 | calculation = ops[operations] 29 | answer = calculation(num1, num2) 30 | print(f"{num1} {operations} {num2} = {answer}") 31 | 32 | flag = input(f"Type 'y' to continue calculating with {answer} or type 'n' to start a new calculation: [y/n]").lower()[0] 33 | 34 | if flag == 'n': 35 | break 36 | elif flag == 'y': 37 | num1 = answer 38 | calculator() 39 | calculator() 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | # def operations(a, b, c): 49 | # if b == '+': 50 | # add(a, c) 51 | # elif b == '-': 52 | # return subtract(a, c) 53 | # elif b == '*': 54 | # return multiply(a, c) 55 | # elif b == '/': 56 | # return divide(a, c) 57 | #answer = operations(num1, symbol, num2) 58 | # print(f"{num1} {symbol} {num2} = {first_answer}") 59 | # print('_' * 50) 60 | # symbol = input("Pick another operation: ") 61 | # print('_' * 50) 62 | # num3 = int(input("What's the next number?: ")) 63 | # operations = ops[symbol] 64 | # second_answer = operations(operations(num1, num2), num3) 65 | # print('_' * 50) 66 | 67 | # print(f"{first_answer} {symbol} {num3} = {second_answer}") 68 | -------------------------------------------------------------------------------- /daysinmonth.py: -------------------------------------------------------------------------------- 1 | def is_leap(year): 2 | if year % 4 == 0: 3 | if year % 100 == 0: 4 | if year % 400 == 0: 5 | return True 6 | else: 7 | return False 8 | else: 9 | return True 10 | else: 11 | return False 12 | 13 | def days_in_month(year, month): 14 | if month > 12 or month < 1: 15 | return "Invalid month." 16 | month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] 17 | if is_leap(year) and month == 2: 18 | return 29 19 | return month_days[month - 1] 20 | 21 | 22 | #🚨 Do NOT change any of the code below 23 | year = int(input("Enter a year: ")) 24 | month = int(input("Enter a month: ")) 25 | days = days_in_month(year, month) 26 | print(days) 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /desafio 67.py: -------------------------------------------------------------------------------- 1 | n = s = cont = 0 2 | while True: 3 | n = int(input('Digite um número:')) 4 | s += n 5 | cont += 1 6 | if n == 999: 7 | s -= 999 8 | cont -= 1 9 | if n == 999: 10 | break 11 | 12 | print(f'A soma entre os números foi de {s} e o total de números somados foi de {cont}.') -------------------------------------------------------------------------------- /desafio 68.py: -------------------------------------------------------------------------------- 1 | print('-' * 40) 2 | print('{:^40}'.format('PROGRAMA TABUADA')) 3 | print('-' * 40) 4 | while True: 5 | n = int(input('Insira um número para calcular sua tabuada:')) 6 | if n < 0: 7 | break 8 | for c in range (1, 11): 9 | print(f'{n} x {c} = {n*c}') 10 | 11 | print('PROGRAMA FINALIZADO.') 12 | -------------------------------------------------------------------------------- /desafio31.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | ano=int(input('Insira o ano a analisar, Insira 0 para analisar o ano atual')) 3 | if ano ==0: 4 | print('O ano inserido é {}'.format(datetime.date.today().year)) 5 | if ano % 4==0 and ano % 100 !=0 or ano % 400 ==0: 6 | print('O ano inserido é bissexto') 7 | else: 8 | print('O ano inserido não é bissexto') 9 | -------------------------------------------------------------------------------- /desafio32.py: -------------------------------------------------------------------------------- 1 | n1=float(input('Insira o primeiro número: ')) 2 | n2=float(input('Insira o segundo número: ')) 3 | n3=float(input('Insira o terceiro número: ')) 4 | #MENORES 5 | if n1 < n2 and n1 < n3 : 6 | print('n1 é o menor valor') 7 | if n2 < n1 and n2 < n3: 8 | print('n2 é o menor valor') 9 | if n3 < n1 and n3 < n2: 10 | print('n3 é o menor valor') 11 | #MAIORES 12 | if n1 > n2 and n1 > n3: 13 | print('n1 é o maior valor') 14 | if n2 > n1 and n2 > n3: 15 | print('n2 é o maior valor') 16 | if n3 > n2 and n3 > n1: 17 | print('n3 é o maior valor') 18 | -------------------------------------------------------------------------------- /desafio33.py: -------------------------------------------------------------------------------- 1 | n1=float(input('Insira o primeiro número: ')) 2 | n2=float(input('Insira o segundo número: ')) 3 | n3=float(input('Insira o terceiro número: ')) 4 | #MENORES 5 | if n1 < n2 and n1 < n3 : 6 | print('n1 é o menor valor') 7 | if n2 < n1 and n2 < n3: 8 | print('n2 é o menor valor') 9 | if n3 < n1 and n3 < n2: 10 | print('n3 é o menor valor') 11 | #MAIORES 12 | if n1 > n2 and n1 > n3: 13 | print('n1 é o maior valor') 14 | if n2 > n1 and n2 > n3: 15 | print('n2 é o maior valor') 16 | if n3 > n2 and n3 > n1: 17 | print('n3 é o maior valor') 18 | -------------------------------------------------------------------------------- /desafio50.py: -------------------------------------------------------------------------------- 1 | import random 2 | import time 3 | lista = ('PEDRA', 'PAPEL', 'TESOURA') 4 | 5 | print('{:=^40}'.format('JOKEMPO!')) 6 | print('''Insira a opção da sua jogada 7 | [0]PEDRA 8 | [1]PAPEL 9 | [2]TESOURA''') 10 | jogada=int(input('Opção a jogar: ')) 11 | 12 | computador=random.randint(0,2) 13 | time.sleep(1) 14 | print('JO...') 15 | time.sleep(1) 16 | print('KEN...') 17 | time.sleep(1) 18 | print('PO!!!') 19 | print('O computador escolheu {}'.format(lista[computador])) 20 | print('O jogador jogou {}'.format(lista[jogada])) 21 | if computador == 0: 22 | if jogada == 0: 23 | print('EMPATE!') 24 | elif jogada == 1: 25 | print('VOCÊ VENCEU!') 26 | elif jogada == 2: 27 | print('O COMPUTADOR VENCEU. Tente novamente.') 28 | else: 29 | print('JOGADA INVÁLIDA') 30 | 31 | 32 | if computador == 1: 33 | if jogada == 0: 34 | print('O COMPUTADOR VENCEU. Tente novamente.') 35 | elif jogada == 1: 36 | print('EMPATE!') 37 | elif jogada == 2: 38 | print('VOCÊ VENCEU!') 39 | else: 40 | print('JOGADA INVÁLIDA') 41 | 42 | 43 | if computador == 2: 44 | if jogada == 0: 45 | print('VOCÊ VENCEU!') 46 | elif jogada == 1: 47 | print('O COMPUTADOR VENCEU. Tente novamente.') 48 | elif jogada == 2: 49 | print('EMPATE!') 50 | else: 51 | print('JOGADA INVÁLIDA') 52 | 53 | -------------------------------------------------------------------------------- /desafio52.py: -------------------------------------------------------------------------------- 1 | for c in range(2, 51, 2): 2 | print(c) -------------------------------------------------------------------------------- /desafio53.py: -------------------------------------------------------------------------------- 1 | soma = 0 2 | cont = 0 3 | for c in range(1, 501, 2): 4 | if c % 3 == 0: 5 | soma = soma + c 6 | cont = cont+ 1 7 | print(" A soma de todos os {} valores é de {}".format(cont, soma)) 8 | -------------------------------------------------------------------------------- /desafio54.py: -------------------------------------------------------------------------------- 1 | n=float(input('Insira um número: ')) 2 | for c in range(1,11): 3 | print(n*c) -------------------------------------------------------------------------------- /desafio55.py: -------------------------------------------------------------------------------- 1 | frase=str(input('Insira sua frase: ')).strip().upper() 2 | palavras=frase.split() 3 | junto=''.join(palavras) 4 | inverso='' 5 | for letra in range (len(junto)-1, -1, -1): 6 | inverso = inverso + junto[letra] 7 | print(junto, inverso) 8 | if inverso == junto: 9 | print('Temos um palíndromo!') 10 | else: 11 | print('Não temos um palíndromo!') -------------------------------------------------------------------------------- /desafio56.py: -------------------------------------------------------------------------------- 1 | pt = int(input('Insira o primeiro termo da PA: ')) 2 | r = int(input('Insira a razão da PA: ')) 3 | for c in range(pt, (pt + (10 * r)), r): 4 | print(c) 5 | -------------------------------------------------------------------------------- /desafio57.py: -------------------------------------------------------------------------------- 1 | s = 0 2 | for c in range(1, 7): 3 | n = int(input('Insira um número: ')) 4 | if n % 2 == 0: 5 | s = s + n 6 | print('O somatório dos valores foi {}'.format(s)) 7 | -------------------------------------------------------------------------------- /desafio58.py: -------------------------------------------------------------------------------- 1 | num=int(input('Insira um número inteiro: ')) 2 | tot = 0 3 | for c in range(1, num+1): 4 | if num % c == 0: 5 | print('\033[33m', end=' ') 6 | tot = tot + 1 7 | else: 8 | print('\033[31m', end=' ') 9 | print('{}'.format(c), end=' ') 10 | print('\n\033[mO número {} foi dividido {} vezes'.format(num, tot)) 11 | if tot == 2: 12 | print('Ele é um número primo') 13 | else: 14 | print('Ele não é um número primo') 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /desafio59.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | atual = datetime.date.today().year 4 | cont1 = 0 5 | cont2 = 0 6 | for c in range(0, 7): 7 | ano = int(input('Insira seu ano de nascimento: ')) 8 | idade = atual - ano 9 | if idade >= 21: 10 | cont1 = cont1 + 1 11 | else: 12 | cont2 = cont2 + 1 13 | print('{} pessoas são maiores e {} menores'.format(cont1, cont2)) 14 | 15 | 16 | -------------------------------------------------------------------------------- /desafio60.py: -------------------------------------------------------------------------------- 1 | maior = 0 2 | menor = 0 3 | for p in range(1, 6): 4 | peso = float(input('Insira o {}º peso em kg: '.format(p))) 5 | if p == 1: 6 | maior = peso 7 | menor = peso 8 | else: 9 | if peso > maior: 10 | maior = peso 11 | if peso < menor: 12 | menor = peso 13 | print('O maior peso lido foi de {}kg'.format(maior)) 14 | print('O menor peso lido foi de {}kg'.format(menor)) 15 | -------------------------------------------------------------------------------- /desafio61.py: -------------------------------------------------------------------------------- 1 | 2 | sexo = str(input('Digite seu sexo: ')).upper().strip()[0] 3 | while sexo not in 'MF': 4 | sexo = str(input('Dados inválidos. Digite seu sexo: ')).upper().strip()[0] 5 | print('Sexo {} registrado com sucesso.'.format(sexo)) 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /desafio62.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | n = random.randint(0,10) 4 | acertou = False 5 | palpites = 0 6 | while not acertou: 7 | jogador = int(input('Insira um valor entre 0 e 10: ')) 8 | palpites += 1 9 | if jogador == n: 10 | acertou = True 11 | else: 12 | if jogador < n: 13 | print('Mais...Tente novamente.') 14 | elif jogador > n: 15 | print('Menos...Tente novamente.') 16 | print('Acertou com {} tentativas!'.format(palpites)) -------------------------------------------------------------------------------- /desafio63.py: -------------------------------------------------------------------------------- 1 | n1 = int(input('Insira o primeiro valor: ')) 2 | n2 = int(input('Insira o segundo valor: ')) 3 | menu = int(input('''Escolha a opção desejada: 4 | [1]Soma 5 | [2]Multiplicação 6 | [3]Maior valor 7 | [4]Novos números 8 | [5]Finalizar programa''')) 9 | while menu != 5: 10 | if menu == 1: 11 | soma = n1 + n2 12 | print('A soma do primeiro e do segundo valor é {}'.format(soma)) 13 | if menu == 2: 14 | mult = n1*n2 15 | print('O produto entre o primeiro e o segundo valor é {}'.format(mult)) 16 | if menu == 3: 17 | if n1 > n2: 18 | print('O primeiro valor é maior que o segundo') 19 | else: 20 | print('O segundo valor é maior que o primeiro') 21 | if menu == 4: 22 | print('Insira novos valores: ') 23 | n1 = int(input('Insira o primeiro valor: ')) 24 | n2 = int(input('Insira o segundo valor: ')) 25 | 26 | print('Programa finalizado.') 27 | 28 | menu = int(input('''Escolha a opção desejada: 29 | [1]Soma 30 | [2]Multiplicação 31 | [3]Maior valor 32 | [4]Novos números 33 | [5]Finalizar programa''')) 34 | 35 | print('Programa finalizado.') 36 | -------------------------------------------------------------------------------- /desafio64.py: -------------------------------------------------------------------------------- 1 | n = int(input('Insira um valor para calcular seu fatorial: ')) 2 | c = n 3 | f = c 4 | print('Calculando {}! ='.format(n)) 5 | while c > 0: 6 | print('{}'.format(c), end='') 7 | print('x'if c > 1 else '=', end = '') 8 | f = f*c 9 | c -= 1 10 | print('{}'.format(f)) -------------------------------------------------------------------------------- /desafio65.py: -------------------------------------------------------------------------------- 1 | n = 0 2 | while n > 0: 3 | n = int(input('Insira um número: ')) 4 | -------------------------------------------------------------------------------- /desafio66.py: -------------------------------------------------------------------------------- 1 | n = int(input('Insira o primeiro termo da PA: ')) 2 | r = int(input('Insira a razão da PA: ')) 3 | t = -------------------------------------------------------------------------------- /desafionumerosprimos.py: -------------------------------------------------------------------------------- 1 | num=int(input('Insira um número inteiro: ')) 2 | tot = 0 3 | for c in range(1, num+1): 4 | if num % c == 0: 5 | print('\033[33m', end=' ') 6 | tot = tot + 1 7 | else: 8 | print('\033[31m', end=' ') 9 | print('{}'.format(c), end=' ') 10 | print('\n\033[mO número {} foi dividido {} vezes'.format(num, tot)) 11 | if tot == 2: 12 | print('Ele é um número primo') 13 | else: 14 | print('Ele não é um número primo') 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /desafiooalindromo1.py: -------------------------------------------------------------------------------- 1 | frase = str(input('Insira sua frase: ')).strip().upper() 2 | palavras = frase.split() 3 | junto =''.join(palavras) 4 | inverso ='' 5 | for letra in range (len(junto)-1, -1, -1): 6 | inverso = inverso + junto[letra] 7 | print(junto, inverso) 8 | if inverso == junto: 9 | print('Temos um palíndromo!') 10 | else: 11 | print('Não temos um palíndromo!') -------------------------------------------------------------------------------- /desafiopa1.py: -------------------------------------------------------------------------------- 1 | pt = int(input('Insira o primeiro termo da PA: ')) 2 | r = int(input('Insira a razão da PA: ')) 3 | for c in range(pt, (pt + (10 * r)), r): 4 | print(c) 5 | -------------------------------------------------------------------------------- /desafiopagamento.py: -------------------------------------------------------------------------------- 1 | p=float(input('Insira o Valor do produto em R$: ')) 2 | cp=str(input('Insira a condição de pagamento: ')).strip() 3 | if cp.find('dinheiro/cheque'): 4 | print('Você pagará R${}'.format(p-(p*10)/100)) 5 | if cp.find('cartão'): 6 | print('Você pagará R${}'.format(p-(p*5)/100)) -------------------------------------------------------------------------------- /desafiopalindromo.py: -------------------------------------------------------------------------------- 1 | import random 2 | import time 3 | lista = ('PEDRA', 'PAPEL', 'TESOURA') 4 | 5 | print('{:=^40}'.format('JOKEMPO!')) 6 | print('''Insira a opção da sua jogada 7 | [0]PEDRA 8 | [1]PAPEL 9 | [2]TESOURA''') 10 | jogada=int(input('Opção a jogar: ')) 11 | 12 | computador=random.randint(0,2) 13 | time.sleep(1) 14 | print('JO...') 15 | time.sleep(1) 16 | print('KEN...') 17 | time.sleep(1) 18 | print('PO!!!') 19 | print('O computador escolheu {}'.format(lista[computador])) 20 | print('O jogador jogou {}'.format(lista[jogada])) 21 | if computador == 0: 22 | if jogada == 0: 23 | print('EMPATE!') 24 | elif jogada == 1: 25 | print('VOCÊ VENCEU!') 26 | elif jogada == 2: 27 | print('O COMPUTADOR VENCEU. Tente novamente.') 28 | else: 29 | print('JOGADA INVÁLIDA') 30 | 31 | 32 | if computador == 1: 33 | if jogada == 0: 34 | print('O COMPUTADOR VENCEU. Tente novamente.') 35 | elif jogada == 1: 36 | print('EMPATE!') 37 | elif jogada == 2: 38 | print('VOCÊ VENCEU!') 39 | else: 40 | print('JOGADA INVÁLIDA') 41 | 42 | 43 | if computador == 2: 44 | if jogada == 0: 45 | print('VOCÊ VENCEU!') 46 | elif jogada == 1: 47 | print('O COMPUTADOR VENCEU. Tente novamente.') 48 | elif jogada == 2: 49 | print('EMPATE!') 50 | else: 51 | print('JOGADA INVÁLIDA') 52 | 53 | -------------------------------------------------------------------------------- /dungeongame.py: -------------------------------------------------------------------------------- 1 | print(''' 2 | ******************************************************************************* 3 | | | | | 4 | _________|________________.=""_;=.______________|_____________________|_______ 5 | | | ,-"_,="" `"=.| | 6 | |___________________|__"=._o`"-._ `"=.______________|___________________ 7 | | `"=._o`"=._ _`"=._ | 8 | _________|_____________________:=._o "=._."_.-="'"=.__________________|_______ 9 | | | __.--" , ; `"=._o." ,-"""-._ ". | 10 | |___________________|_._" ,. .` ` `` , `"-._"-._ ". '__|___________________ 11 | | |o`"=._` , "` `; .". , "-._"-._; ; | 12 | _________|___________| ;`-.o`"=._; ." ` '`."\` . "-._ /_______________|_______ 13 | | | |o; `"-.o`"=._`` '` " ,__.--o; | 14 | |___________________|_| ; (#) `-.o `"=.`_.--"_o.-; ;___|___________________ 15 | ____/______/______/___|o;._ " `".o|o_.--" ;o;____/______/______/____ 16 | /______/______/______/_"=._o--._ ; | ; ; ;/______/______/______/_ 17 | ____/______/______/______/__"=._o--._ ;o|o; _._;o;____/______/______/____ 18 | /______/______/______/______/____"=._o._; | ;_.--"o.--"_/______/______/______/_ 19 | ____/______/______/______/______/_____"=.o|o_.--""___/______/______/______/____ 20 | /______/______/______/______/______/______/______/______/______/______/_____ / 21 | ******************************************************************************* 22 | ''') 23 | print("Welcome to Treasure Island.") 24 | print("Your mission is to find the treasure.") 25 | 26 | #https://www.draw.io/?lightbox=1&highlight=0000ff&edit=_blank&layers=1&nav=1&title=Treasure%20Island%20Conditional.drawio#Uhttps%3A%2F%2Fdrive.google.com%2Fuc%3Fid%3D1oDe4ehjWZipYRsVfeAx2HyB7LCQ8_Fvi%26export%3Ddownload 27 | 28 | #Write your code below this line 👇 29 | print('_' * 40) 30 | print('You arrive at the lsland and there are two options. On the left side there is a cave, on the right, a lake. Enter the cave or dive in the lake?') 31 | option1 = str(input('Cave or lake? (right or left) [R/L]: ')).upper() 32 | print('_' * 40) 33 | if option1 == 'L': 34 | print('You just entered the dark cave.') 35 | print('When entering the dark cave, you see three doors, one with a face of a lion, another with a face of the tiger and the last with the face of a bear. Which do you enter?') 36 | option2 = str(input("Enter 'L' for Lion, 'T' for Tiger, and 'B' for Bear.")).upper() 37 | print('_' * 40) 38 | if option2 == 'L': 39 | print("You see the red eyes of the starving lion staring from the back of the room, it's ready too make its move. But there's still hope, in the corner of the room you see two weapons, and axe and a sword, which do you pick?") 40 | option3 = str(input("'A' for axe or 'S' for sword? [A/S]:")).upper() 41 | print('_' * 40) 42 | if option3 == 'S': 43 | print("You desperately run for the sword. Grab it and when the beast jumps over you with its mouth wide open you luckily crave the blade into its throat. Good move. You may proceed into the cave.") 44 | print("As you go further the path splits in two, you take left or right?") 45 | option6 = str(input("Left 'L' or Right 'R' ?")).upper() 46 | if option6 == 'R': 47 | print("Good job! You found the chest! Don't go spend your fortune in candies and drugs!") 48 | else: 49 | print("Suddenly you stepped in an interruptor which opened a traphole full of spikes beneath you. Game over.") 50 | else: 51 | print('You grab the axe. Unfortunately, you swing it towards the beast but there is no use, you end up being ripped apart by its claws and teeth. Game over.') 52 | print('_' * 40) 53 | elif option2 == 'T': 54 | print("As expected. You see the giant tiger but there is no where to run or hide, the beast comes and slashes and bites you with everything its got. No match for you. You're dead. Game over.") 55 | print('_' * 40) 56 | elif option2 == 'B': 57 | print("As you enter the bear room, you can't see quite well because there's not much torches in this area, but is barely visible a giant sillouette of a huge grizzly bear in front of you. Luckily, the beast in entertained with a gigantic pot of honey which seems not to end up fast and for that it did not sense your presence in the room. As time passes by, you spot a table with a shotgun at the other corner of the room, but there's still something telling you that you could try and sneak around the bear wuthout being spotted. what do you do?") 58 | option5 = int(input('1 for sneak around or 2 for shotgun?')) 59 | print('_' * 40) 60 | if option5 == 1: 61 | print('You quietly passed around the beast without being seen. Good job. Proceed to the depths of the cave.') 62 | print("As you go further the path splits in two, you take left or right?") 63 | option7 = str(input("Left 'L' or Right 'R' ?")).upper() 64 | if option7 == 'R': 65 | print("Good job! You found the chest! Don't go spend your fortune in candies and drugs!") 66 | else: 67 | print("Suddenly you stepped in an interruptor which opened a traphole full of spikes beneath you. Game over.") 68 | print('_' * 40) 69 | else: 70 | print("You walk for the shotgun and try to fire it. It was unloaded, but the beast hears the click of the trigger. You shouldn't have done that. Game over.") 71 | else: 72 | print('When you jumped into the lake you were drawn into a deadly whirlpool that crushed your bones and ripped your skin and organs. Game over.') 73 | 74 | 75 | 76 | -------------------------------------------------------------------------------- /ex002.py: -------------------------------------------------------------------------------- 1 | n1=int(input('digite um número')) 2 | n2=int(input('digite outro numero')) 3 | s=n1+n2 4 | print('a soma vale,{}'.format(s)) -------------------------------------------------------------------------------- /ex100.py: -------------------------------------------------------------------------------- 1 | from datetime import date 2 | def voto(an=0): 3 | if 65 > date.today().year - an > 18: 4 | return print(f'Com {date.today().year - an} anos, VOTO OBRIGATÓRIO.') 5 | if date.today().year - an < 18: 6 | return print(f'Com {date.today().year - an} anos, VOTO NEGADO.') 7 | if date.today().year - an > 65: 8 | return print(f'Com {date.today().year - an} anos, VOTO OPCIONAL') 9 | 10 | an = int(input((f'Em que ano você nasceu? '))) 11 | voto(an) 12 | 13 | -------------------------------------------------------------------------------- /ex101.py: -------------------------------------------------------------------------------- 1 | def fatorial(num=1, show=False): 2 | """ 3 | fatorial(n, show=False) 4 | -->Calcula o fatorial de um número. 5 | :param num:O número a ser calculado. 6 | :param show:(Opcional) Mostrar ou não o processo de conta. 7 | :return:O valor do Fatorial de um número "n". 8 | """ 9 | f = 1 10 | for c in range(num, 0, -1): 11 | f *= c 12 | 13 | if show == True: 14 | c = num 15 | while c > 0: 16 | print(f'{c}', end='') 17 | if c > 1: 18 | print(f' x ', end='') 19 | else: 20 | print(f' = ', end='') 21 | c -= 1 22 | 23 | return f 24 | print('=-'*25) 25 | print(fatorial(9, show=True)) 26 | help(fatorial) -------------------------------------------------------------------------------- /ex102.py: -------------------------------------------------------------------------------- 1 | def ficha(jog='', gol=0): 2 | print(f'O jogador {jog} fez {gol} gol(s) no campeonato.') 3 | 4 | 5 | n = str(input('Nome do jogador: ')) 6 | g = str(input('Número de gols: ')) 7 | if g.isnumeric(): 8 | g = int(g) 9 | else: 10 | g = 0 11 | if n.strip() == '': 12 | ficha(gol=g) 13 | else: 14 | ficha(n, g) 15 | 16 | -------------------------------------------------------------------------------- /ex103.py: -------------------------------------------------------------------------------- 1 | def leiaint(msg): 2 | ok = False 3 | valor = 0 4 | while True: 5 | n = str(input(msg)) 6 | if n.isnumeric(): 7 | valor = int(n) 8 | ok = True 9 | else: 10 | print('\033[0;31mERRO! Digite um número inteiro válido.\033[m') 11 | if ok: 12 | break 13 | return valor 14 | 15 | 16 | n = leiaint('Digite um número: ') 17 | print(f'Você acabou de digitar o número {n}.') -------------------------------------------------------------------------------- /ex104.py: -------------------------------------------------------------------------------- 1 | def notas(*n, sit=False): 2 | """ 3 | --> Função que calcula a média e situação de diversos alunos devolvendo um dicionário. 4 | :param n: Uma ou mais notas dos alunos. 5 | :param sit: Situação mediante a média das notas inseridas. 6 | :return: Dicionário com informações sobre as notas e situação da turma. 7 | """ 8 | r = {} 9 | r['Total'] = len(n) 10 | r['Maior Nota'] = max(n) 11 | r['Menor Nota'] = min(n) 12 | r['Média das Notas'] = sum(n)/len(n) 13 | if sit: 14 | if r['Média das Notas'] >= 7: 15 | r['Situação'] = 'BOA' 16 | elif r['Média das Notas'] >= 5: 17 | r['Situação'] = 'RAZOÁVEL' 18 | else: 19 | r['Situação'] = 'RUIM' 20 | 21 | return r 22 | 23 | 24 | resp = notas(7.5, 3.9, 4.7, 9.8, sit=True) 25 | print(resp) 26 | help(notas) -------------------------------------------------------------------------------- /ex105.py: -------------------------------------------------------------------------------- 1 | from time import sleep 2 | c = ('\033[m', #0 - Sem Cores 3 | '\033[0;30;41m', #1 - Vermelho 4 | '\033[0;30;42m', #2 - Verde 5 | '\033[0;30;43m', #3 - Amarelo 6 | '\033[0;30;44m', #4 - Azul 7 | '\033[0;30;45m', #5 - Roxo 8 | '\033[7;30m' #6 - Branco 9 | ) 10 | 11 | def ajuda(com): 12 | título(f'Acessando o manual do comando \'{com}\'', 4) 13 | print(c[6], end='') 14 | help(com) 15 | print(c[0], end='') 16 | sleep(2) 17 | 18 | 19 | def título(msg, cor=0): 20 | tam = len(msg) + 4 21 | print(c[cor], end='') 22 | print('~' * tam) 23 | print(f' {msg}') 24 | print('~' * tam) 25 | print(c[0], end='') 26 | sleep(1) 27 | 28 | #PROGRAMA PRINCIPAL 29 | comando = '' 30 | while True: 31 | título('SISTEMA DE AJUDA PyHELP', 2) 32 | comando = str(input("Função ou biblioteca> ")) 33 | if comando.upper() == 'FIM': 34 | break 35 | else: 36 | ajuda(comando) 37 | título('ATÉ LOGO', 1) -------------------------------------------------------------------------------- /ex113.py: -------------------------------------------------------------------------------- 1 | def leiaint(msg): 2 | while True: 3 | try: 4 | n = int(input(msg)) 5 | except (ValueError, TypeError): 6 | print('\033[31mERRO: por favor, digite um número inteiro válido\033[m.') 7 | continue 8 | except(KeyboardInterrupt): 9 | print('\n\033[31mO usuário preferiu não digitar o valor.\033[m') 10 | return 0 11 | else: 12 | return n 13 | 14 | def leiafloat(msg): 15 | while True: 16 | try: 17 | n = float(input(msg)) 18 | except (ValueError, TypeError): 19 | print('\033[31mERRO: por favor digite um número real válido.\033[m') 20 | continue 21 | except (KeyboardInterrupt): 22 | print('\n\033[31mO usuário preferiu não digitar esse valor.\033[m') 23 | return 0 24 | else: 25 | return n 26 | 27 | 28 | n1 = leiaint('Digite um valor inteiro: ') 29 | n2 = leiafloat('Digite um valor real: ') 30 | print(f'O valor inteiro digitado foi {n1} e o real foi {n2}.') -------------------------------------------------------------------------------- /ex114.py: -------------------------------------------------------------------------------- 1 | import urllib 2 | import urllib.request 3 | 4 | try: 5 | site = urllib.request.urlopen('http://www.pudim.com.br') 6 | except urllib.error.URLError: 7 | print('O site "Pudim" não está acessível no momento.') 8 | else: 9 | print('Consegui acessar o site com sucesso.') 10 | print(site.read()) -------------------------------------------------------------------------------- /ex115a.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danimoreira90/Logic_with_python/1e39e0ebf8987e60ec34315d9d3d7ff1c9b35afd/ex115a.py -------------------------------------------------------------------------------- /ex71.py: -------------------------------------------------------------------------------- 1 | cont = ('zero', 'um', 'dois', 'três', 'quatro', 'cinco', 2 | 'seis', 'sete', 'oito', 'nove', 'dez', 'onze', 'doze', 3 | 'treze', 'catorze', 'quinze', 'dezesseis', 'dezessete', 4 | 'dezoito', 'dezenove', 'vinte') 5 | while True: 6 | num = int(input('Digite um número entre 0 e 20: ')) 7 | if 0 <= num <= 20: 8 | break 9 | print('Tente novamente', end='') 10 | print(f'Você digitou o número {cont[num]}') 11 | -------------------------------------------------------------------------------- /ex72.py: -------------------------------------------------------------------------------- 1 | clubes = ('América-MG', 'Athletico-PR', 'Atlético-GO', 'Atlético-MG', 2 | 'Avaí', 'Botafogo', 'Ceará', 'Corinthians', 'Coritiba', 'Cuiabá', 3 | 'Flamengo', 'Fluminense', 'Fortaleza', 'Goiás', 'Internacional', 4 | 'Juventude', 'Palmeiras', 'Bragantino', 'Santos', 'São Paulo') 5 | print('=-='*20) 6 | print(f'Lista de times do Brasileirão: {clubes}') 7 | print('=-='*20) 8 | print(f'Os 5 primeiros da lista são {clubes[0:5]}') 9 | print('=-='*20) 10 | print(f'Os quatro últimos da lista são {clubes[16:20]}') 11 | print('=-='*20) 12 | print(f'Os times em ordem alfabética são: {sorted(clubes)}') 13 | print('=-='*20) 14 | print(f'O Bragantino está na {clubes.index("Bragantino")+1}ª posição ') -------------------------------------------------------------------------------- /ex73.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | print('=-=-'*20) 3 | print('{:^60}'.format('GERADOR DE NÚMEROS')) 4 | print('=-=-'*20) 5 | tupla = (randint(0,10), randint(0,10), randint(0,10), randint(0,10), randint(0,10)) 6 | tuplasorted = sorted(tupla) 7 | print(f'Os números gerados foram: {tupla}') 8 | print(f'O maior número gerado foi {tuplasorted[0]} e o menor número foi {tuplasorted[4]}') 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /ex74.py: -------------------------------------------------------------------------------- 1 | n1 = int(input('Digite um número: ')) 2 | n2 = int(input('Digite um número: ')) 3 | n3 = int(input('Digite um número: ')) 4 | n4 = int(input('Digite um número: ')) 5 | tupla = (n1, n2, n3, n4) 6 | print(f'Os números inseridos foram {tupla}.') 7 | 8 | if n1 or n2 or n3 or n4 == 9: 9 | print(f'O número 9 foi digitado {tupla.count(9)} vezes.') 10 | 11 | if n1 or n2 or n3 or n4 == 3: 12 | if 3 in tupla: 13 | print(f'O número 3 está na {tupla.index(3)+1} posição.') 14 | else: 15 | print(f'O número 3 não foi digitado.') 16 | print(f'Os valores pares digitados foram', end='') 17 | for c in tupla: 18 | if c % 2 == 0: 19 | print(c, end=' ') 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /ex75.2.py: -------------------------------------------------------------------------------- 1 | listanum = [] 2 | maior = 0 3 | menor = 0 4 | for c in range(0, 5): 5 | listanum.append(int(input(f'Digite um valor para a posição {c}: '))) 6 | if c == 0: 7 | maior = menor = listanum[c] 8 | else: 9 | if listanum[c] > maior: 10 | maior = listanum[c] 11 | if listanum[c] < menor: 12 | menor = listanum[c] 13 | print('=-'*30) 14 | print(f'Você digitou os valores {listanum}.') 15 | print(f'O maior valor digitado foi {maior}, nas posições: ', end='') 16 | for i, v in enumerate(listanum): 17 | if v == maior: 18 | print(f'{i}...', end='') 19 | print() 20 | print(f'O menor valor digitado foi {menor}, nas posições: ', end='') 21 | for i, v in enumerate(listanum): 22 | if v == menor: 23 | print(f'{i}...', end='') 24 | print() 25 | 26 | -------------------------------------------------------------------------------- /ex75.py: -------------------------------------------------------------------------------- 1 | valores = [] 2 | maior = 0 3 | menor = 0 4 | for cont in range(0,5): 5 | valores.append(int(input(f'Digite um valor para a posição {cont}: '))) 6 | print('=-'*30) 7 | print(f'Você digitou os valores {valores}.') 8 | 9 | 10 | print(f'O maior valor digitado foi {max(valores)} na posição {valores.index(max(valores))}.') 11 | print(f'O menor valor digitado foi {min(valores)} na posição {valores.index(min(valores))}.') 12 | -------------------------------------------------------------------------------- /ex76.py: -------------------------------------------------------------------------------- 1 | valores = [] 2 | while True: 3 | 4 | v = (int(input('Digite um valor: '))) 5 | if v not in valores: 6 | valores.append(v) 7 | print('Valor adicionado com sucesso.') 8 | else: 9 | print('Valor duplicado. Não adicionado.') 10 | 11 | flag = str(input('Deseja continuar? [S/N]: ')).strip().upper() 12 | if flag not in 'SN': 13 | flag = str(input('Opção inválida. Deseja continuar? [S/N]: ')).strip().upper() 14 | if flag == 'S': 15 | continue 16 | if flag == 'N': 17 | break 18 | print(valores) -------------------------------------------------------------------------------- /ex77.py: -------------------------------------------------------------------------------- 1 | valores = [] 2 | for c in range(0,5): 3 | n = int(input('Digite um valor: ')) 4 | if c == 0 or n > valores[-1]: 5 | valores.append(n) 6 | print('Valor adicionado ao final da lista.') 7 | else: 8 | pos = 0 9 | while pos < len(valores): 10 | if n <= valores[pos]: 11 | valores.insert(pos, n) 12 | print(f'Adicionado na posição {pos} da lista.') 13 | break 14 | pos += 1 15 | print('=-'*30) 16 | print(f'Os valores adicionados em ordem foram {valores}.') 17 | 18 | -------------------------------------------------------------------------------- /ex79.py: -------------------------------------------------------------------------------- 1 | lista = [] 2 | while True: 3 | n = int(input('Digite um número: ')) 4 | lista.append(n) 5 | flag = str(input('Quer continuar [S/N]:')).strip().upper() 6 | while flag not in 'SN': 7 | flag = str(input('Tente novamente. Quer continuar [S/N]:')).strip().upper() 8 | if flag == 'S': 9 | continue 10 | if flag == 'N': 11 | break 12 | if 5 in lista: 13 | print(f'O valor 5 foi digitado e está na lista na posição {lista.index(5)}') 14 | else: 15 | print('O valor 5 não está na lista') 16 | lista.sort(reverse=True) 17 | 18 | print(f'Você digitou {len(lista)} valores') 19 | print(f'A lista em ordem decrescente é {lista}') 20 | 21 | 22 | -------------------------------------------------------------------------------- /ex80.py: -------------------------------------------------------------------------------- 1 | listatotal = [] 2 | listapares = [] 3 | listaimpares = [] 4 | while True: 5 | n = int(input('Digite um valor:')) 6 | listatotal.append(n) 7 | if n % 2 == 0: 8 | listapares.append(n) 9 | if n % 2 == 1: 10 | listaimpares.append(n) 11 | flag = str(input('Quer continuar [S/N]: ')).strip().upper() 12 | while flag not in 'SN': 13 | flag = str(input('Opção inválida. Quer continuar [S/N]: ')).strip().upper() 14 | if flag == 'S': 15 | continue 16 | if flag == 'N': 17 | break 18 | print(f'A lista com todos os valores é {listatotal}.') 19 | print(f'A lista com os valores pares é {listapares}.') 20 | print(f'A lista com os valores ímpares é {listaimpares}.') 21 | -------------------------------------------------------------------------------- /ex81.py: -------------------------------------------------------------------------------- 1 | pessoas = [] 2 | dados = [] 3 | maispes = maislev = 0 4 | while True: 5 | dados.append(str(input('Nome: '))) 6 | dados.append(float(input('Peso em Kg: '))) 7 | if len(pessoas) == 0: 8 | maispes = maislev = dados[1] 9 | else: 10 | if dados[1] > maispes: 11 | maispes = dados[1] 12 | if dados[1] < maislev: 13 | maislev = dados[1] 14 | pessoas.append(dados[:]) 15 | dados.clear() 16 | 17 | flag = str(input('Deseja continuar [S/N]: ')).strip().upper() 18 | while flag not in 'SN': 19 | flag = str(input('Opção inválida. Deseja continuar [S/N]: ')).strip().upper() 20 | if flag == 'S': 21 | 22 | continue 23 | if flag == 'N': 24 | break 25 | print('=-' *40) 26 | print(f'Você cadastrou ao todo {len(pessoas)} pessoas.') 27 | print(f'O maior peso cadastrado foi de {maispes}kg. Peso de ', end='') 28 | for pessoa in pessoas: 29 | if pessoa[1] == maispes: 30 | print(f'[{p[0]}] ', end='') 31 | print() 32 | print(f'O menor peso cadastrado foi de {maislev}kg. Peso de ', end='') 33 | for pessoa in pessoas: 34 | if pessoa[1] == maislev: 35 | print(f'[{p[0]}] ', end='') 36 | print() 37 | 38 | -------------------------------------------------------------------------------- /ex82.1.py: -------------------------------------------------------------------------------- 1 | valores = [[], []] 2 | for c in range(1, 8): 3 | n = int(input(f'Digite o {c}ºvalor: ')) 4 | if n % 2 == 0: 5 | valores[0].append(n) 6 | else: 7 | valores[1].append(n) 8 | print('=-'*30) 9 | valores[0].sort() 10 | valores[1].sort() 11 | print(f'Os valores pares digitados foram {valores[0]}') 12 | print(f'Os valores ímpares digitados foram {valores[1]}') -------------------------------------------------------------------------------- /ex82.py: -------------------------------------------------------------------------------- 1 | lista = [] 2 | listapares = [] 3 | listaimpares = [] 4 | for c in range(1,8): 5 | n = int(input(f'Digite o {c}º valor: ')) 6 | lista.append(n) 7 | for v in lista: 8 | if v % 2 == 0: 9 | listapares.append(v) 10 | listapares.sort() 11 | if v % 2 == 1: 12 | listaimpares.append(v) 13 | listaimpares.sort() 14 | print(f'Os valores pares digitados foram {listapares}.') 15 | print(f'Os valores ímpares digitados foram {listaimpares}') 16 | 17 | -------------------------------------------------------------------------------- /ex90.py: -------------------------------------------------------------------------------- 1 | alunos = {} 2 | alunos['Nome'] = str(input('Nome: ')) 3 | alunos['Média'] = float(input('Média: ')) 4 | print(f'Nome é igual a {alunos["Nome"]}.') 5 | print(f'Média é igual a {alunos["Média"]} ') 6 | 7 | if alunos['Média'] >= 7: 8 | print('Situação: APROVADO') 9 | else: 10 | print('situação: REPROVADO') -------------------------------------------------------------------------------- /ex91.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | from time import sleep 3 | from operator import itemgetter 4 | 5 | jogadores = {} 6 | jogadores['Jogador1'] = randint(1,6) 7 | jogadores['Jogador2'] = randint(1,6) 8 | jogadores['Jogador3'] = randint(1,6) 9 | jogadores['Jogador4'] = randint(1,6) 10 | Ranking = [] 11 | Ranking = sorted(jogadores.items(), key=itemgetter(1), reverse=True) 12 | print(' VALORES SORTEADOS') 13 | for keys, values in jogadores.items(): 14 | print(f'O {keys} tirou o número {values}.') 15 | sleep(1) 16 | print('=-'*20) 17 | print(' Ranking dos jogadores ') 18 | for pos, v in enumerate(Ranking): 19 | print(f'{pos+1}º Lugar ==> {v[0]} com {v[1]}.') 20 | 21 | -------------------------------------------------------------------------------- /ex92.py: -------------------------------------------------------------------------------- 1 | def area(larg, comp): 2 | area = (larg * comp) 3 | print(f'A área de um terreno de {larg}m x {comp}m é de {area}m².') 4 | 5 | 6 | print('CONTROLE DE TERRENOS') 7 | print('_'*20) 8 | l = float(input('LARGURA em (m): ')) 9 | h = float(input('COMPRIMENTO em (m): ')) 10 | area(l, h) 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /ex93.py: -------------------------------------------------------------------------------- 1 | def escreva(msg): 2 | tam = len(msg) 3 | print('~'* tam) 4 | print(msg) 5 | print('~' * tam) 6 | 7 | 8 | escreva('Inconstitucionável') 9 | escreva('Abrupto') 10 | escreva('Dúbio') 11 | escreva('Supercalifragilisticexpialidocious') -------------------------------------------------------------------------------- /ex94.py: -------------------------------------------------------------------------------- 1 | from time import sleep 2 | def contador(i, f, p): 3 | if p < 0: 4 | p *= 1 5 | if p == 0: 6 | p = 1 7 | print('-=' * 20) 8 | print(f'Contagem de {i} até {f} de {p} em {p}.') 9 | sleep(2.5) 10 | 11 | if i < f: 12 | cont = i 13 | while cont <= f: 14 | print(f'{cont} ', end='') 15 | sleep(0.5) 16 | cont += p 17 | print('FIM') 18 | else: 19 | cont = i 20 | while cont >= f: 21 | print(f'{cont} ', end='') 22 | sleep(0.5) 23 | cont -= p 24 | print('FIM') 25 | 26 | 27 | #PROGRAMA PRINCIPAL 28 | contador(1, 10, 1) 29 | contador(10, 0, 2) 30 | print('-=' * 20) 31 | print('Agora é a sua vez de personalizar a contagem.') 32 | ini = int(input('Início: ')) 33 | fim = int(input('Fim: ')) 34 | pas = int(input('Passo: ')) 35 | contador(ini, fim, pas) -------------------------------------------------------------------------------- /ex95.1.py: -------------------------------------------------------------------------------- 1 | from time import sleep 2 | 3 | 4 | def maior(* num): 5 | mai = 0 6 | cont = 0 7 | print('-='*25) 8 | print('Analisando os valores informados...') 9 | for valor in num: 10 | print(f'{valor}', end=' ') 11 | sleep(0.3) 12 | if cont == 0: 13 | mai = valor 14 | else: 15 | if valor > mai: 16 | mai = valor 17 | cont += 1 18 | print(f'Foram informados {cont} valores.') 19 | print(f'O maior valor informado foi {mai}.') 20 | 21 | 22 | 23 | 24 | 25 | 26 | maior(1,8,7,6,5,4,3) 27 | maior(5,67,4,3,8) 28 | maior(0) 29 | maior(-4, 3, 7, 567) -------------------------------------------------------------------------------- /ex95.py: -------------------------------------------------------------------------------- 1 | from time import sleep 2 | def maior(* valores): 3 | mai = men = 0 4 | cont = 0 5 | print('-='*25) 6 | print('Analisando os valores informados...') 7 | sleep(2.0) 8 | print(valores, end='', flush=True) 9 | sleep(0.5) 10 | print(f' Foram informados {len(valores)} no total ') 11 | print(f'O maior valor informado foi {max(valores)}') 12 | 13 | 14 | 15 | maior(1,8,7,6,5,4,3) 16 | maior(5,67,4,3,8) 17 | maior(0) 18 | maior(-4, 3, 7, 567) 19 | 20 | -------------------------------------------------------------------------------- /ex96.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | from time import sleep 3 | 4 | 5 | def sorteia(lista): 6 | print('Sortando 5 valores da lista: ', end='') 7 | for cont in range(0,5): 8 | n = randint(1, 10) 9 | lista.append(n) 10 | print(f'{n} ', end='') 11 | sleep(0.3) 12 | print('PRONTO!') 13 | 14 | 15 | def somaPar(lista): 16 | soma = 0 17 | for valor in lista: 18 | if valor % 2 == 0: 19 | soma += valor 20 | print(f'Somando os valores pares de {lista}, temos {soma}.') 21 | 22 | 23 | números = [] 24 | sorteia(números) 25 | somaPar(números) 26 | -------------------------------------------------------------------------------- /exemplos de leitura 2.py: -------------------------------------------------------------------------------- 1 | # abre o arquivo para leitura 2 | dados = open('ex-leitura.txt', 'r') 3 | 4 | # usando um iterador para ler linha a linha... 5 | for linha in dados: 6 | print(linha, end='') # mostra na tela 7 | 8 | dados.close() # fecha o arquivo -------------------------------------------------------------------------------- /exemplos de leitura 3.py: -------------------------------------------------------------------------------- 1 | # abre o arquivo para leitura 2 | dados = open('ex-leitura.txt', 'r') 3 | 4 | # usando um iterador para ler linha a linha... 5 | for linha in dados: 6 | print(linha, end='') # mostra na tela 7 | 8 | dados.close() # fecha o arquivo -------------------------------------------------------------------------------- /exemplos de leitura 4.py: -------------------------------------------------------------------------------- 1 | # abre o arquivo para leitura 2 | dados = open('ex-leitura.txt', 'r') 3 | 4 | # lê todas as linhas para uma lista 5 | linhas = dados.readlines() 6 | 7 | # iterando sobre a lista... 8 | for linha in linhas: 9 | print(linha, end='') # mostra na tela 10 | 11 | dados.close() # fecha o arquivo -------------------------------------------------------------------------------- /exemplos de leitura.py: -------------------------------------------------------------------------------- 1 | # abre o arquivo para leitura 2 | dados = open('ex-leitura.txt', 'r') 3 | 4 | # lê primeira linha 5 | linha = dados.readline() 6 | 7 | while linha != '': # enquanto não é o fim... 8 | print(linha, end='') # mostra na tela 9 | linha = dados.readline() # lê próxima linha 10 | 11 | dados.close() # fecha o arquivo -------------------------------------------------------------------------------- /fatorial.py: -------------------------------------------------------------------------------- 1 | n = int(input('Insira um valor para calcular seu fatorial: ')) 2 | c = n 3 | f = c 4 | print('Calculando {}! ='.format(n), end=' ') 5 | while c > 0: 6 | print('{}'.format(c), end='') 7 | print(' x'if c > 1 else ' =', end = ' ') 8 | f = f*c 9 | c -= 1 10 | print('{}'.format(f)) -------------------------------------------------------------------------------- /fibonacci.py: -------------------------------------------------------------------------------- 1 | n = cont = soma = 0 2 | n = int(input('Digite um número [999 para parar]:')) 3 | while n != 999: 4 | cont += 1 5 | soma += n 6 | n = int(input('Digite um número [999 para parar]: ')) 7 | print('Foram digitados {} números e sua soma é {}.'.format(cont, soma)) 8 | print('Programa finalizado.') -------------------------------------------------------------------------------- /fibonacci1.py: -------------------------------------------------------------------------------- 1 | print('-'*30) 2 | print('SEQUÊNCIA DE FIBONACCI') 3 | print('-'*30) 4 | n = int(input("Quantos termos você quer mostrar: ")) 5 | t1 = 0 6 | t2 = 1 7 | print('~'*30) 8 | print('{} → {}'.format(t1, t2), end = ' ') 9 | cont = 3 10 | while cont <= n: 11 | t3 = t1 + t2 12 | print('→ {}'.format(t3), end = ' ') 13 | t1 = t2 14 | t2 = t3 15 | cont += 1 16 | print('FIM') 17 | -------------------------------------------------------------------------------- /hangmen.py: -------------------------------------------------------------------------------- 1 | #Step 1 2 | 3 | word_list = ["ardvark", "baboon", "camel"] 4 | 5 | #TODO-1 - Randomly choose a word from the word_list and assign it to a variable called chosen_word. 6 | 7 | #TODO-2 - Ask the user to guess a letter and assign their answer to a variable called guess. Make guess lowercase. 8 | 9 | #TODO-3 - Check if the letter the user guessed (guess) is one of the letters in the chosen_word. 10 | import random 11 | stages = [''' 12 | +---+ 13 | | | 14 | O | 15 | /|\ | 16 | / \ | 17 | | 18 | ========= 19 | ''', ''' 20 | +---+ 21 | | | 22 | O | 23 | /|\ | 24 | / | 25 | | 26 | ========= 27 | ''', ''' 28 | +---+ 29 | | | 30 | O | 31 | /|\ | 32 | | 33 | | 34 | ========= 35 | ''', ''' 36 | +---+ 37 | | | 38 | O | 39 | /| | 40 | | 41 | | 42 | =========''', ''' 43 | +---+ 44 | | | 45 | O | 46 | | | 47 | | 48 | | 49 | ========= 50 | ''', ''' 51 | +---+ 52 | | | 53 | O | 54 | | 55 | | 56 | | 57 | ========= 58 | ''', ''' 59 | +---+ 60 | | | 61 | | 62 | | 63 | | 64 | | 65 | ========= 66 | '''] 67 | 68 | chosen_word = random.choice(word_list) 69 | print(chosen_word) 70 | lives = 6 71 | display = [] 72 | word_length = len(chosen_word) 73 | for _ in range(word_length): 74 | display += '_' 75 | #print(display) 76 | end_of_game = False 77 | 78 | while not end_of_game: 79 | guess = str(input('Guess a letter: ')).lower() 80 | for position in range(0, word_length): 81 | letter = chosen_word[position] 82 | if letter == guess: 83 | display[position] = letter 84 | if guess not in chosen_word: 85 | lives -= 1 86 | if lives == 0: 87 | end_of_game = True 88 | print('You lose.') 89 | 90 | print(f"{' '.join(display)}") 91 | 92 | if '_' not in display: 93 | end_of_game = True 94 | print('You win!') 95 | 96 | print(stages[lives]) 97 | -------------------------------------------------------------------------------- /identificadordemaioridade.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | atual = datetime.date.today().year 4 | cont1 = 0 5 | cont2 = 0 6 | for c in range(0, 7): 7 | ano = int(input('Insira seu ano de nascimento: ')) 8 | idade = atual - ano 9 | if idade >= 21: 10 | cont1 = cont1 + 1 11 | else: 12 | cont2 = cont2 + 1 13 | print('{} pessoas são maiores e {} menores'.format(cont1, cont2)) 14 | 15 | 16 | -------------------------------------------------------------------------------- /identificadordepeso.py: -------------------------------------------------------------------------------- 1 | maior = 0 2 | menor = 0 3 | for p in range(1, 6): 4 | peso = float(input('Insira o {}º peso em kg: '.format(p))) 5 | if p == 1: 6 | maior = peso 7 | menor = peso 8 | else: 9 | if peso > maior: 10 | maior = peso 11 | if peso < menor: 12 | menor = peso 13 | print('O maior peso lido foi de {}kg'.format(maior)) 14 | print('O menor peso lido foi de {}kg'.format(menor)) 15 | -------------------------------------------------------------------------------- /joguinhoporco.py: -------------------------------------------------------------------------------- 1 | n1 = int(input('Insira o primeiro valor: ')) 2 | n2 = int(input('Insira o segundo valor: ')) 3 | menu = int(input('''Escolha a opção desejada: 4 | [1]Soma 5 | [2]Multiplicação 6 | [3]Maior valor 7 | [4]Novos números 8 | [5]Finalizar programa''')) 9 | while menu != 5: 10 | if menu == 1: 11 | soma = n1 + n2 12 | print('A soma do primeiro e do segundo valor é {}'.format(soma)) 13 | if menu == 2: 14 | mult = n1*n2 15 | print('O produto entre o primeiro e o segundo valor é {}'.format(mult)) 16 | if menu == 3: 17 | if n1 > n2: 18 | print('O primeiro valor é maior que o segundo') 19 | else: 20 | print('O segundo valor é maior que o primeiro') 21 | if menu == 4: 22 | print('Insira novos valores: ') 23 | n1 = int(input('Insira o primeiro valor: ')) 24 | n2 = int(input('Insira o segundo valor: ')) 25 | 26 | print('Programa finalizado.') 27 | 28 | menu = int(input('''Escolha a opção desejada: 29 | [1]Soma 30 | [2]Multiplicação 31 | [3]Maior valor 32 | [4]Novos números 33 | [5]Finalizar programa''')) 34 | 35 | print('Programa finalizado.') 36 | -------------------------------------------------------------------------------- /jokenpo.py: -------------------------------------------------------------------------------- 1 | import random 2 | import time 3 | lista = ('PEDRA', 'PAPEL', 'TESOURA') 4 | 5 | print('{:=^40}'.format('JOKEMPO!')) 6 | print('''Insira a opção da sua jogada 7 | [0]PEDRA 8 | [1]PAPEL 9 | [2]TESOURA''') 10 | jogada=int(input('Opção a jogar: ')) 11 | 12 | computador=random.randint(0,2) 13 | time.sleep(1) 14 | print('JO...') 15 | time.sleep(1) 16 | print('KEN...') 17 | time.sleep(1) 18 | print('PO!!!') 19 | print('O computador escolheu {}'.format(lista[computador])) 20 | print('O jogador jogou {}'.format(lista[jogada])) 21 | if computador == 0: 22 | if jogada == 0: 23 | print('EMPATE!') 24 | elif jogada == 1: 25 | print('VOCÊ VENCEU!') 26 | elif jogada == 2: 27 | print('O COMPUTADOR VENCEU. Tente novamente.') 28 | else: 29 | print('JOGADA INVÁLIDA') 30 | 31 | 32 | if computador == 1: 33 | if jogada == 0: 34 | print('O COMPUTADOR VENCEU. Tente novamente.') 35 | elif jogada == 1: 36 | print('EMPATE!') 37 | elif jogada == 2: 38 | print('VOCÊ VENCEU!') 39 | else: 40 | print('JOGADA INVÁLIDA') 41 | 42 | 43 | if computador == 2: 44 | if jogada == 0: 45 | print('VOCÊ VENCEU!') 46 | elif jogada == 1: 47 | print('O COMPUTADOR VENCEU. Tente novamente.') 48 | elif jogada == 2: 49 | print('EMPATE!') 50 | else: 51 | print('JOGADA INVÁLIDA') 52 | 53 | -------------------------------------------------------------------------------- /lifeinweeks.py: -------------------------------------------------------------------------------- 1 | # 🚨 Don't change the code below 👇 2 | age = input("What is your current age?") 3 | # 🚨 Don't change the code above 👆 4 | 5 | #Write your code below this line 👇 6 | 7 | days_lived = int(age) * 365 8 | weeks_lived = int(age) * 52 9 | months_lived = int(age) * 12 10 | limit_age_d = (90 * 365 - (days_lived)) 11 | limit_age_w = (90 * 52 - (weeks_lived)) 12 | limit_age_m = (90 * 12 - (months_lived)) 13 | print(f'You have {limit_age_d} days, {limit_age_w} weeks and {limit_age_m} months left.') 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /list comprehension condicional infnet.py: -------------------------------------------------------------------------------- 1 | linha = input() 2 | 3 | # usando list comprehension E expressão condicional c/ if else 4 | lista = [palavra.capitalize() if palavra.startswith('m') else palavra 5 | for palavra in linha.split()] 6 | 7 | # usando estruturas de repetição e condicional convencionais 8 | for palavra in linha.split(): 9 | if palavra.startswith('m'): 10 | lista.append(palavra.capitalize()) 11 | else: 12 | lista.append(palavra) -------------------------------------------------------------------------------- /list comprehesion function infnet.py: -------------------------------------------------------------------------------- 1 | def gols_time(tabela, time): 2 | gols = [] 3 | for linha in tabela: 4 | if linha[1] == time: 5 | gols.append(linha[2]) 6 | return sum(gols) 7 | 8 | def gols_time_lc(tabela, time): 9 | gols = [linha[2] for linha in tabela if linha[1] == time] 10 | return sum(gols) 11 | 12 | 13 | tabela = [['Pedro', 'Flamengo', 12], 14 | ['Lucas', 'Vélez', 7], 15 | ['Rafel', 'Palmeiras', 7], 16 | ['Rony', 'Palmeiras', 7], 17 | ['Gabigol', 'Flamengo', 6]] 18 | 19 | print('Flamengo:', gols_time_lc(tabela, 'Flamengo')) 20 | print('Palmeiras:', gols_time_lc(tabela, 'Palmeiras')) -------------------------------------------------------------------------------- /list n sets comparison.py: -------------------------------------------------------------------------------- 1 | import time 2 | l = [i for i in range(8000000)] 3 | inicio = time.time() 4 | print(99999999999 in l) 5 | fim = time.time() 6 | print(f'{(fim - inicio):.7f}') 7 | 8 | 9 | c = {i for i in range(8000000)} 10 | inicio = time.time() 11 | print(99999999999 in c) 12 | fim = time.time() 13 | print(f'{(fim - inicio):.7f}') -------------------------------------------------------------------------------- /listagemdepreços.py: -------------------------------------------------------------------------------- 1 | print('__'*20) 2 | print('{:^40}'.format('LISTAGEM DE PREÇOS')) 3 | print('__'*20) 4 | listagem = ('Espada', 27.55, 'Escudo', 30.40, 'Arco', 40.75, 'Armadura', 120.75, 5 | 'Talismã', 70.90, 'Botas', 20.60, 'Luvas', 15.45, 'Elmo', 35.60) 6 | print(f'''{listagem[0]}...................$ {listagem[1]:.2f} 7 | {listagem[2]}...................$ {listagem[3]:.2f} 8 | {listagem[4]}.....................$ {listagem[5]:.2f} 9 | {listagem[6]}.................$ {listagem[7]:.2f} 10 | {listagem[8]}..................$ {listagem[9]:.2f} 11 | {listagem[10]}....................$ {listagem[11]:.2f} 12 | {listagem[12]}....................$ {listagem[13]:.2f} 13 | {listagem[14]}.....................$ {listagem[15]:.2f}''') -------------------------------------------------------------------------------- /listapareseimpares.py: -------------------------------------------------------------------------------- 1 | listatotal = [] 2 | listapares = [] 3 | listaimpares = [] 4 | while True: 5 | n = int(input('Digite um valor:')) 6 | listatotal.append(n) 7 | if n % 2 == 0: 8 | listapares.append(n) 9 | if n % 2 == 1: 10 | listaimpares.append(n) 11 | flag = str(input('Quer continuar [S/N]: ')).strip().upper() 12 | while flag not in 'SN': 13 | flag = str(input('Opção inválida. Quer continuar [S/N]: ')).strip().upper() 14 | if flag == 'S': 15 | continue 16 | if flag == 'N': 17 | break 18 | print(f'A lista com todos os valores é {listatotal}.') 19 | print(f'A lista com os valores pares é {listapares}.') 20 | print(f'A lista com os valores ímpares é {listaimpares}.') 21 | -------------------------------------------------------------------------------- /lojinhamedieval.py: -------------------------------------------------------------------------------- 1 | print('__'*20) 2 | print('{:^40}'.format('LISTAGEM DE PREÇOS')) 3 | print('__'*20) 4 | listagem = ('Espada', 27.55, 'Escudo', 30.40, 'Arco', 40.75, 'Armadura', 120.75, 5 | 'Talismã', 70.90, 'Botas', 20.60, 'Luvas', 15.45, 'Elmo', 35.60) 6 | print(f'''{listagem[0]}...................$ {listagem[1]} 7 | {listagem[2]}...................$ {listagem[3]} 8 | {listagem[4]}.....................$ {listagem[5]} 9 | {listagem[6]}.................$ {listagem[7]} 10 | {listagem[8]}..................$ {listagem[9]} 11 | {listagem[10]}....................$ {listagem[11]} 12 | {listagem[12]}....................$ {listagem[13]} 13 | {listagem[14]}.....................$ {listagem[15]}''') 14 | print('__'*20) -------------------------------------------------------------------------------- /lovecalculator.py: -------------------------------------------------------------------------------- 1 | # 🚨 Don't change the code below 👇 2 | print("Welcome to the Love Calculator!") 3 | name1 = input("What is your name? \n") 4 | name2 = input("What is their name? \n") 5 | # 🚨 Don't change the code above 👆 6 | 7 | #Write your code below this line 👇 8 | totalname = (name1 + name2).lower() 9 | true = totalname.count('t') + totalname.count('r') + totalname.count('u') + totalname.count('e') 10 | true = str(true) 11 | love = totalname.count('l') + totalname.count('o') + totalname.count('v') + totalname.count('e') 12 | love = str(love) 13 | score = true + love 14 | score = int(score) 15 | if score < 10 or score > 90: 16 | print(f'Your score is {score}, you go together like coke and mentos.') 17 | if 40 < score < 50: 18 | print(f'Your score is {score}, you are alright together.') 19 | if 10 < score < 40 or 50 < score < 90: 20 | print(f'Your score is {score}.') 21 | 22 | 23 | -------------------------------------------------------------------------------- /matriz1.py: -------------------------------------------------------------------------------- 1 | matriz = [[0,0,0],[0,0,0],[0,0,0]] 2 | for l in range(0,3): 3 | for c in range(0,3): 4 | matriz[l][c] = int(input(f'Digite um valor para [{l}, {c}]: ')) 5 | print('=-'*30) 6 | for l in range(0, 3): 7 | for c in range(0, 3): 8 | print(f'[{matriz[l][c]:^5}]', end='') 9 | print() 10 | -------------------------------------------------------------------------------- /megasena.py: -------------------------------------------------------------------------------- 1 | import random 2 | import time 3 | print('__'*30) 4 | print('{:^50}'.format('JOGO DA MEGA SENA')) 5 | print('__'*30) 6 | lista = [] 7 | jogos = [] 8 | quant = int(input('Quantos jogos a serem sorteados? ')) 9 | tot = 1 10 | while tot <= quant: 11 | cont = 0 12 | while True: 13 | num = random.randint(1,60) 14 | if num not in lista: 15 | lista.append(num) 16 | cont += 1 17 | if cont >= 6: 18 | break 19 | lista.sort() 20 | jogos.append(lista[:]) 21 | lista.clear() 22 | tot += 1 23 | print('-='*3, f' SORTEANDO {quant} JOGOS', '-=' *3) 24 | for i, l in enumerate(jogos): 25 | print(f'Jogo {i+1}: {l}') 26 | time.sleep(1) 27 | print('-=' *5, '<< BONS JOGOS!! >>', '-=' *5) 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /numberconversion.py: -------------------------------------------------------------------------------- 1 | # 🚨 Don't change the code below 👇 2 | two_digit_number = input("Type a two digit number: ") 3 | # 🚨 Don't change the code above 👆 4 | 5 | #################################### 6 | #Write your code below this line 👇 7 | 8 | a = int(two_digit_number[0]) 9 | b = int(two_digit_number[1]) 10 | final = a + b 11 | print(final) 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /numberguessinggame.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | 3 | EASY_LEVEL_TURNS = 10 4 | HARD_LEVEL_TURNS = 5 5 | 6 | turns = 0 7 | def check_answer(guess, answer, turns): 8 | if guess > answer: 9 | print("Too high.") 10 | return turns - 1 11 | elif guess < answer: 12 | print("Too low.") 13 | return turns - 1 14 | else: 15 | print(f"You got it! The answer was {answer}.") 16 | 17 | 18 | def set_difficulty(): 19 | level = input("Choose a difficulty. Type 'easy' or 'hard':") 20 | if level == 'easy': 21 | return EASY_LEVEL_TURNS 22 | else: 23 | return HARD_LEVEL_TURNS 24 | 25 | 26 | 27 | def number_guessing_game(): 28 | #Choosing a number between 1 and 100. 29 | print("Welcome to the Number Guessing Game!") 30 | print("I'm thinking of a number between 1 and 100.") 31 | answer = randint(1, 100) 32 | #Make a function to set difficulty. 33 | turns = set_difficulty() 34 | 35 | guess = 0 36 | while guess != answer: 37 | print(f"You have {turns} attempts remaining to guess the number.") 38 | #Let the user guess a number. 39 | guess = int(input("Make a guess: ")) 40 | 41 | turns = check_answer(guess, answer, turns) 42 | if turns == 0: 43 | print("You've run out of guesses, you lose.") 44 | print(f"The answer was {answer}") 45 | return 46 | elif guess != answer: 47 | print("Guess again.") 48 | 49 | 50 | number_guessing_game() 51 | #Function to check the user's guess against the actual number. 52 | 53 | #Track the number of turns and reduce by 1 if they get it wrong. 54 | 55 | #Repeat the guessing functionality if they get it wrong. -------------------------------------------------------------------------------- /pa2.0.py: -------------------------------------------------------------------------------- 1 | n = int(input('Insira um número para calcularmos sua P.A.: ')) 2 | r = int(input('Insira a razão da P.A.: ')) 3 | cont = '' 4 | while -------------------------------------------------------------------------------- /passwordgenerator.py: -------------------------------------------------------------------------------- 1 | #Password Generator Project 2 | import random 3 | letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] 4 | numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] 5 | symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+'] 6 | 7 | print("Welcome to the PyPassword Generator!") 8 | nr_letters= int(input("How many letters would you like in your password?\n")) 9 | nr_symbols = int(input(f"How many symbols would you like?\n")) 10 | nr_numbers = int(input(f"How many numbers would you like?\n")) 11 | 12 | #Eazy Level - Order not randomised: 13 | #e.g. 4 letter, 2 symbol, 2 number = JduE&!91 14 | 15 | # password = '' 16 | 17 | # for char in range(1, nr_letters + 1): 18 | # password += random.choice(letters) 19 | 20 | # for char in range(1, nr_symbols + 1): 21 | # password += random.choice(symbols) 22 | 23 | # for char in range(1, nr_numbers + 1): 24 | # password += random.choice(numbers) 25 | 26 | # print(password) 27 | 28 | #Hard Level - Order of characters randomised: 29 | #e.g. 4 letter, 2 symbol, 2 number = g^2jk8&P 30 | 31 | password_list = [] 32 | 33 | for char in range(1, nr_letters + 1): 34 | password_list.append(random.choice(letters)) 35 | 36 | for char in range(1, nr_symbols + 1): 37 | password_list += random.choice(symbols) 38 | 39 | for char in range(1, nr_numbers + 1): 40 | password_list += random.choice(numbers) 41 | 42 | random.shuffle(password_list) 43 | 44 | password = '' 45 | for char in password_list: 46 | password += char 47 | 48 | print(f'Your password is {password}.') 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /primechecker.py: -------------------------------------------------------------------------------- 1 | #Write your code below this line 👇 2 | def prime_checker(number): 3 | is_prime = True 4 | for i in range(2, number): 5 | if number % i == 0: 6 | is_prime = False 7 | if is_prime: 8 | print("It's a prime number.") 9 | else: 10 | print("It's not a prime number.") 11 | 12 | 13 | 14 | 15 | 16 | #Write your code above this line 👆 17 | 18 | #Do NOT change any of the code below👇 19 | n = int(input("Check this number: ")) 20 | prime_checker(number=n) 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /progressãoaritmética2.0.py: -------------------------------------------------------------------------------- 1 | print('=-'*20) 2 | print('GERADOR DE P.A.') 3 | print('=-'*20) 4 | primeiro = int(input('Insira o primeiro termo para calcularmos sua P.A.: ')) 5 | razão = int(input('Insira a razão da P.A.: ')) 6 | cont = 1 7 | total = 0 8 | mais = 10 9 | termo = primeiro 10 | while mais != 0: 11 | total = total + mais 12 | while cont <= total: 13 | print('{} →'.format(termo), end = ' ') 14 | termo = termo + razão 15 | cont += 1 16 | print('PAUSA') 17 | mais = int(input('Quantos termos você quer mostrar a mais: ')) 18 | print('FIM. Progressão finalizada com {} termos mostrados.'.format(total)) 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /progressãoaritmética3.0.py: -------------------------------------------------------------------------------- 1 | print('=-'*20) 2 | print('GERADOR DE P.A.') 3 | print('=-'*20) 4 | primeiro = int(input('Insira o primeiro termo para calcularmos sua P.A.: ')) 5 | razão = int(input('Insira a razão da P.A.: ')) 6 | cont = 1 7 | total = 0 8 | mais = 10 9 | termo = primeiro 10 | while mais != 0: 11 | total = total + mais 12 | while cont <= total: 13 | print('{} →'.format(termo), end = ' ') 14 | termo = termo + razão 15 | cont += 1 16 | print('PAUSA') 17 | mais = int(input('Quantos termos você quer mostrar a mais: ')) 18 | print('FIM. Progressão finalizada com {} termos mostrados.'.format(total)) 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /pseudonyms.py: -------------------------------------------------------------------------------- 1 | """Generate funny names by randomly combining names from 2separate tuples""" 2 | 3 | import sys 4 | import random 5 | 6 | 7 | print('Welcome to the Psych "Sidekick Name Picker".\n') 8 | print('A name just like Sean would pick for Gus:\n\n') 9 | 10 | first = ('Baby Oil', 'Bad News', 'Big Burps', "Bill 'Beenie-Weenie'", 11 | "Bob 'Stinkbug'", 'Bowel Noises', 'Boxelder', "Bud 'Lite' ", 12 | 'Butterbean', 'Buttermilk', 'Buttocks', 'Chad', 'Chesterfield', 13 | 'Chewy', 'Chigger', 'Cinnabuns', 'Cleet', 'Cornbread', 14 | 'Crab-Meat', 'Crapps', 'Dark Skies', 'Dennis Clawhammer', 15 | 'Dicman', 'Elphonso', 'Fancypants', 'Figgs', 'Foncy', 'Gootsy', 16 | 'Greasy Jim', 'Huckleberry', 'Huggy', 'Ignatious', 'Jimbo', 17 | "Joe 'Pottin´ Soil'", 'Johnny', 'Lemongrass', 'Lil´ Debil', 18 | 'Longbranch', '"Lunch Money"', 'Mergatroid', '"Mr. Peabody"', 19 | 'Oil-Can', 'Oinks', 'Old-Scratch', 'Ovaltine', 'Pennywhistle', 20 | 'Pitchfork Ben', 'Potato Bug', 'Pushmeet', 'Rock Candy', 'Schlomo', 21 | 'Stratchensniff', 'Scut', "Sid 'The Squirts'", 'Skidmark', 'Slaps', 22 | 'Snakes', 'Snoobs', 'Snorki', 'Soupcan Sam', 'Spitzitout', 'Squids', 23 | 'Stinky', 'Storyboard', 'Sweet Tea', 'TeeTee', 'Wheezy Joe', 24 | "Winston 'Jazz-Hands'", 'Worms') 25 | 26 | last = ('Appleyard', 'Bigmeat', 'Bloominshine', 'Boogerbottom', 27 | 'Breedslovetrout', 'Butterbaugh', 'Clovenhoof', 'Clutterbuck', 28 | 'Cocktoasten', 'Endicott', 'Fewhairs', 'Gooberdapple', 'Goodensmith', 29 | 'Goodpasture', 'Guster', 'Henderson', 'Hooperbag', 'Hoosenater', 30 | 'Hootkins', 'Jefferson', 'Jenkins', 'Jingley-Schmidt', 'Johnson', 31 | 'Kingfish', 'Listenbee', "M'Bembo", 'McFadden', 'Moonshine', 'Nettles', 32 | 'Noseworthy', 'Olivetti', 'Outerbridge', 'Overpeck', 'Overturf', 33 | 'Oxhandler', 'Pealike', 'Peterson', 'Pipelow', 'Pinkerton', 'Porkins', 34 | 'Putney', 'Quakenbush', 'Rainwater', 'Rosenthal', 'Rubbins', 'Sackrider', 35 | 'Snuggleshine', 'Splern', 'Stevens', 'Stroganoff', 'Sugar-Gold', 36 | 'Swackhammer', 'Tippins', 'Turnipseed', 'Vinaigrette', 'Walkingstick', 37 | 'Wallbanger', 'Weemax', 'Weiners', 'Whipkey', 'Wigglesworth', 'Wimplesnatch', 38 | 'Winterkorn', 'Woolysocks') 39 | 40 | while True: 41 | first_Name = random.choice(first) 42 | 43 | last_Name = random.choice(last) 44 | 45 | print('\n\n') 46 | print(f'{first_Name} {last_Name}', file=sys.stderr) 47 | print('\n\n') 48 | 49 | try_again = input('\n\nTry again? (Press Enter else n to quit)\n') 50 | if try_again.lower() == 'n': 51 | break 52 | 53 | input('\nPress Enter to exit.') 54 | -------------------------------------------------------------------------------- /rascunho.py: -------------------------------------------------------------------------------- 1 | def processa_resultado(num_1, num_2): 2 | result = (num_1 + num_2) % 2 3 | return result 4 | 5 | 6 | def imprime_resultado(resp, jog_par, jog_impar): 7 | print(f'\n Resultado Par, venceu o jogador(a) {jog_par} ') if resp == 0 else print(f'\n Resultado Ímpar, venceu o jogador(a) {jog_impar} ') 8 | 9 | 10 | def inicio(): 11 | jogador_Par, jogador_Impar = input('Informe o nome do jogador(a), opçãoo PAR: '), input('Informe o nome do jogador(a), opçãoo ÍMPAR: ') 12 | 13 | try: 14 | num_jogador_Par, num_jogador_Impar = int(input(f'Jogador(a) {jogador_Par}, informe seu número: ')), int(input(f'Jogador(a) {jogador_Impar}, informe seu número: ')) 15 | except: 16 | print('\nOps... você errou!\nDa próxima vez digite um número inteiro. Comece novamente...\n') 17 | inicio() 18 | else: 19 | resp = processa_resultado(num_jogador_Par, num_jogador_Impar) 20 | imprime_resultado(resp, jogador_Par, jogador_Impar) 21 | 22 | 23 | 24 | 25 | inicio() -------------------------------------------------------------------------------- /samegreedyflashdrives.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | 3 | df = {'email': ['p@gmail.com;m@gmail.com;i@gmail.com', 4 | 'a@gmail.com,b@gmail.com', 5 | 'c@gmail.com', 6 | '']} 7 | 8 | df = pd.DataFrame(df) 9 | 10 | print(df) 11 | print() 12 | 13 | df = (df['email'].str.split('[,;]', expand=True) 14 | .fillna('') 15 | .rename(columns={i: col for i,col in enumerate(['email_1', 'email_2', 'email_3'])})) 16 | 17 | print(df) --------------------------------------------------------------------------------