├── .gitignore
├── README.md
├── banco_dados
├── .gitignore
├── .vscode
│ └── settings.json
├── alterar_tabela.py
├── associar_grupo_contato.py
├── atualizar_contato.py
├── bd.py
├── conexao_teste.py
├── configuracao.py
├── contatos_com_grupo.py
├── contatos_com_grupo_v2.py
├── criar_banco.py
├── criar_grupo.py
├── criar_tabela.py
├── excluir_contato.py
├── excluir_tabela.py
├── incluir_contato.py
├── incluir_varios_contatos.py
├── listar_bancos.py
├── listar_tabelas.py
├── ordenar_contatos.py
├── povoar_grupo.py
├── requerimentos.py
├── requirements.txt
├── selecionar_campos.py
├── selecionar_com_filtro.py
├── selecionar_contatos.py
├── selecionar_contatos_limit.py
├── selecionar_contatos_limit_offset.py
├── selecionar_filtro_parcial.py
├── selecionar_sem_sql_injection.py
├── selecionar_um_registro.py
└── sqllite.py
├── estruturas_controle
├── break_continue.py
├── desafio_set.py
├── for_1.py
├── for_2.py
├── for_3.py
├── for_4.py
├── for_com_else.py
├── for_sem_else.py
├── if_else_1.py
├── if_else_2.py
├── switch_1.py
├── switch_2.py
└── while_1.py
├── estruturas_controle_projetos
├── exemplo_recursao.py
├── fibonacci_recursive_v1.py
├── fibonacci_recursive_v2.py
├── fibonacci_v1.py
├── fibonacci_v2.py
├── fibonacci_v3.py
├── fibonacci_v4.py
├── fibonacci_v5.py
└── fibonacci_v6.py
├── funcoes
├── Untitled-1.py
├── callable_object.py
├── callable_packing.py
├── callable_packing_nomeado.py
├── correcao_arg_padrao_mutavel.py
├── decorator.py
├── desafio_html.py
├── gerador_html_v1.py
├── gerador_html_v2.py
├── gerador_html_v3.py
├── gerador_html_v4.py
├── gerador_html_v5.py
├── packing.py
├── packing_nomeado.py
├── problema_arg_padrao_mutavel.py
├── prog_funcional_spoiler.py
├── todos_parametros.py
└── unpacking_nomeado.py
├── fundamentos
├── builtins.py
├── coercao_automatica.py
├── comentarios.py
├── conjunto.py
├── conversao_tipos.py
├── dicionario.py
├── interpolacao.py
├── lista.py
├── mais_operadores.py
├── operadores_aritmeticos.py
├── operadores_atribuicao.py
├── operadores_logicos.py
├── operadores_relacionais.py
├── operadores_ternarios.py
├── operadores_unarios.py
├── primeiros_exemplos.py
├── tipo_string.py
├── tipos_basicos.py
├── tipos_numericos_1.py
├── tipos_numericos_2.py
├── tupla.py
└── variaveis.py
├── fundamentos_projetos
├── __pycache__
│ ├── area_circulo_v6.cpython-37.pyc
│ ├── area_circulo_v7.cpython-37.pyc
│ ├── area_circulo_v8.cpython-37.pyc
│ └── area_circulo_v9.cpython-37.pyc
├── area_circulo
├── area_circulo_v1.py
├── area_circulo_v10.py
├── area_circulo_v11.py
├── area_circulo_v12.py
├── area_circulo_v13.py
├── area_circulo_v14.py
├── area_circulo_v15.py
├── area_circulo_v2.py
├── area_circulo_v3.py
├── area_circulo_v4.py
├── area_circulo_v5.py
├── area_circulo_v6.py
├── area_circulo_v7.py
├── area_circulo_v8.py
├── area_circulo_v9.py
├── encoding_teste.py
└── nota_aluno.py
├── list_comprehension
├── comprehension_v1.py
├── comprehension_v2.py
├── comprehension_v3.py
├── comprehension_v4.py
├── comprehension_v5.py
└── switch_3.py
├── manipulacao_arquivos
├── __pycache__
│ └── io_desafio_csv.cpython-37.pyc
├── desafio-ibge.csv
├── io_csv.py
├── io_desafio_csv.py
├── io_v1.py
├── io_v2.py
├── io_v3.py
├── io_v4.py
├── io_v5.py
├── io_v6.py
├── pessoas.csv
└── pessoas.txt
├── notas
├── .ipynb_checkpoints
│ ├── Fundamentos-checkpoint.ipynb
│ └── Testando Jupyter-checkpoint.ipynb
├── Fundamentos.ipynb
└── Testando Jupyter.ipynb
├── pacotes
├── app
│ ├── __init__.py
│ ├── negocio
│ │ ├── __init__.py
│ │ └── backend.py
│ └── utils
│ │ ├── __init__.py
│ │ └── gerador.py
├── calc
│ └── __init__.py
├── desafio_package.py
├── pacote1
│ ├── __init__.py
│ ├── modulo1.py
│ └── modulo2.py
├── pacote2
│ ├── __init__.py
│ └── modulo1.py
├── pacote_v1.py
├── pacote_v2.py
├── pacote_v3.py
├── pacote_v4.py
└── pacote_v5.py
├── pip
└── requirements.txt
├── poo
├── data_v1.py
├── data_v2.py
├── desafio_carro.py
├── desafio_loja.py
├── loja
│ ├── __init__.py
│ ├── cliente.py
│ ├── compra.py
│ ├── pessoa.py
│ └── vendedor.py
├── todo_v1.py
├── todo_v2.py
├── todo_v3.py
├── todo_v4.py
├── todo_v5.py
├── todo_v6.py
├── todo_v7.py
└── todo_v8.py
├── poo_avancada
├── contador_objetos.py
├── evolucao_v1.py
├── evolucao_v2.py
├── evolucao_v3.py
├── evolucao_v4.py
├── evolucao_v5.py
├── evolucao_v6.py
├── iterator.py
├── mixins.py
└── multipla.py
├── programacao_funcional
├── closure.py
├── desafio_mdc.py
├── fatorial_recursivo.py
├── filter.py
├── funcao_alta_ordem.py
├── funcao_primeira_classe.py
├── funcoes_imutabilidade_v1.py
├── funcoes_imutabilidade_v2.py
├── funcoes_lambda.py
├── funcoes_lambda_alternativa.py
├── generators_v1.py
├── generators_v2.py
├── generators_v3.py
├── imperativo.py
├── implementando_map_v1.py
├── implementando_map_v2.py
├── imutabilidade_v1.py
├── imutabilidade_v2.py
├── map.py
└── reduce.py
└── projeto-teste
├── .gitignore
└── requirements.txt
/.gitignore:
--------------------------------------------------------------------------------
1 | __pycache__
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # curso-python
--------------------------------------------------------------------------------
/banco_dados/.gitignore:
--------------------------------------------------------------------------------
1 | .venv
2 | __pycache__
--------------------------------------------------------------------------------
/banco_dados/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "python.pythonPath": "/Users/leonardomleitao/Desktop/curso-python/banco_dados/.venv/bin/python3"
3 | }
--------------------------------------------------------------------------------
/banco_dados/alterar_tabela.py:
--------------------------------------------------------------------------------
1 | from mysql.connector.errors import ProgrammingError
2 | from bd import nova_conexao
3 |
4 | sql = 'ALTER TABLE contatos ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY'
5 |
6 | with nova_conexao() as conexao:
7 | try:
8 | cursor = conexao.cursor()
9 | cursor.execute(sql)
10 | except ProgrammingError as e:
11 | print(f'Erro: {e.msg}')
--------------------------------------------------------------------------------
/banco_dados/associar_grupo_contato.py:
--------------------------------------------------------------------------------
1 | from mysql.connector.errors import ProgrammingError
2 | from bd import nova_conexao
3 |
4 | selecionar_grupo = 'SELECT id FROM grupos WHERE descricao = %s'
5 | atualizar_contato = 'UPDATE contatos SET grupo_id = %s WHERE nome = %s'
6 |
7 | contato_grupo = {
8 | 'Ana': 'Casa',
9 | 'Bia': 'Trabalho',
10 | 'Lucas Yuri': 'Casa',
11 | 'Lu': 'Casa',
12 | 'Gui': 'Trabalho',
13 | 'Beca': 'Trabalho',
14 | 'Pedro': 'Trabalho',
15 | 'Luca': 'Casa',
16 | }
17 |
18 | with nova_conexao() as conexao:
19 | try:
20 | cursor = conexao.cursor()
21 | for contato, grupo in contato_grupo.items():
22 | cursor.execute(selecionar_grupo, (grupo,))
23 | grupo_id = cursor.fetchone()[0]
24 | cursor.execute(atualizar_contato, (grupo_id, contato))
25 | conexao.commit()
26 | except ProgrammingError as e:
27 | print(f'Erro: {e.msg}')
28 | else:
29 | print('contatos associados')
--------------------------------------------------------------------------------
/banco_dados/atualizar_contato.py:
--------------------------------------------------------------------------------
1 | from mysql.connector.errors import ProgrammingError
2 | from bd import nova_conexao
3 |
4 | sql = 'UPDATE contatos SET nome = %s WHERE id = %s'
5 | args = ('Lucas Yuri', 44)
6 |
7 | with nova_conexao() as conexao:
8 | try:
9 | cursor = conexao.cursor()
10 | cursor.execute(sql, args)
11 | conexao.commit()
12 | except ProgrammingError as e:
13 | print(f'Erro: {e.msg}')
14 | else:
15 | print(f'{cursor.rowcount} registro(s) alterado(s).')
--------------------------------------------------------------------------------
/banco_dados/bd.py:
--------------------------------------------------------------------------------
1 | from mysql.connector import connect
2 | from contextlib import contextmanager
3 |
4 | parametros = dict(
5 | host='localhost',
6 | port=3306,
7 | user='root',
8 | passwd='12345678',
9 | database='agenda'
10 | )
11 |
12 | @contextmanager
13 | def nova_conexao():
14 | conexao = connect(**parametros)
15 | try:
16 | yield conexao
17 | finally:
18 | if (conexao and conexao.is_connected()):
19 | conexao.close()
--------------------------------------------------------------------------------
/banco_dados/conexao_teste.py:
--------------------------------------------------------------------------------
1 | from bd import nova_conexao
2 |
3 | with nova_conexao() as conexao:
4 | if conexao.is_connected():
5 | print('Conectado!')
6 |
7 | print('Fim :)')
--------------------------------------------------------------------------------
/banco_dados/configuracao.py:
--------------------------------------------------------------------------------
1 | from mysql.connector import connect
2 |
3 | conexao = connect(
4 | passwd='12345678',
5 | port=3306,
6 | user='root',
7 | host='localhost',
8 | )
9 |
10 | print(conexao)
--------------------------------------------------------------------------------
/banco_dados/contatos_com_grupo.py:
--------------------------------------------------------------------------------
1 | from bd import nova_conexao
2 | from mysql.connector.errors import ProgrammingError
3 |
4 | sql = """
5 | SELECT
6 | grupos.descricao AS grupo,
7 | contatos.nome AS nome
8 | FROM contatos
9 | INNER JOIN grupos ON contatos.grupo_id = grupos.id
10 | ORDER BY grupo, nome
11 | """
12 |
13 | with nova_conexao() as conexao:
14 | try:
15 | cursor = conexao.cursor(dictionary=True)
16 | cursor.execute(sql)
17 | contatos = cursor.fetchall()
18 | except ProgrammingError as e:
19 | print(f'Erro: {e.msg}')
20 | else:
21 | for contato in contatos:
22 | print(f'{contato["grupo"]}: {contato["nome"]}')
--------------------------------------------------------------------------------
/banco_dados/contatos_com_grupo_v2.py:
--------------------------------------------------------------------------------
1 | from collections import defaultdict
2 | from bd import nova_conexao
3 | from mysql.connector.errors import ProgrammingError
4 |
5 | sql = """
6 | SELECT
7 | grupos.descricao AS grupo,
8 | contatos.nome AS nome
9 | FROM contatos
10 | INNER JOIN grupos ON contatos.grupo_id = grupos.id
11 | ORDER BY grupo, nome
12 | """
13 |
14 | with nova_conexao() as conexao:
15 | try:
16 | cursor = conexao.cursor(dictionary=True)
17 | try:
18 | cursor.execute(sql)
19 | contatos = cursor.fetchall()
20 | finally:
21 | cursor.close()
22 | except ProgrammingError as e:
23 | print(f'Erro: {e.msg}')
24 | else:
25 | agrupados = defaultdict(list)
26 | for contato in contatos:
27 | agrupados[contato['grupo']].append(contato['nome'])
28 |
29 | print(agrupados)
--------------------------------------------------------------------------------
/banco_dados/criar_banco.py:
--------------------------------------------------------------------------------
1 | from mysql.connector import connect
2 |
3 | conexao = connect(
4 | host='localhost',
5 | port=3306,
6 | user='root',
7 | passwd='12345678'
8 | )
9 |
10 | cursor = conexao.cursor()
11 | # CREATE DATABASE IF NOT EXISTS agenda
12 | cursor.execute('CREATE DATABASE agenda')
--------------------------------------------------------------------------------
/banco_dados/criar_grupo.py:
--------------------------------------------------------------------------------
1 | from bd import nova_conexao
2 | from mysql.connector import ProgrammingError
3 |
4 | criar_tabela_grupo = """
5 | CREATE TABLE IF NOT EXISTS grupos (
6 | id INT AUTO_INCREMENT PRIMARY KEY,
7 | descricao VARCHAR(30)
8 | )
9 | """
10 |
11 | alterar_tabela_contato_1 = """
12 | ALTER TABLE contatos ADD grupo_id INT
13 | """
14 |
15 | alterar_tabela_contato_2 = """
16 | ALTER TABLE contatos ADD FOREIGN KEY (grupo_id)
17 | REFERENCES grupos(id)
18 | """
19 |
20 | try:
21 | with nova_conexao() as conexao:
22 | try:
23 | cursor = conexao.cursor()
24 | cursor.execute(criar_tabela_grupo)
25 | cursor.execute(alterar_tabela_contato_1)
26 | cursor.execute(alterar_tabela_contato_2)
27 | except ProgrammingError as e:
28 | print(f'Erro: {e.msg}')
29 | except ProgrammingError as e:
30 | print(f'Erro CONEXÃO: {e.msg}')
--------------------------------------------------------------------------------
/banco_dados/criar_tabela.py:
--------------------------------------------------------------------------------
1 | from bd import nova_conexao
2 | from mysql.connector import ProgrammingError
3 |
4 |
5 | tabela_contatos = """
6 | CREATE TABLE IF NOT EXISTS contatos(
7 | nome VARCHAR(50), tel VARCHAR(40)
8 | )
9 | """
10 |
11 | tabela_emails = """
12 | CREATE TABLE emails(
13 | id INT AUTO_INCREMENT PRIMARY KEY,
14 | dono VARCHAR(50)
15 | )
16 | """
17 | try:
18 | with nova_conexao() as conexao:
19 | try:
20 | cursor = conexao.cursor()
21 | cursor.execute(tabela_contatos)
22 | cursor.execute(tabela_emails)
23 | except ProgrammingError as e:
24 | print(f'Erro: {e.msg}')
25 | except ProgrammingError as e:
26 | print(f'Erro CONEXÃO: {e.msg}')
--------------------------------------------------------------------------------
/banco_dados/excluir_contato.py:
--------------------------------------------------------------------------------
1 | from mysql.connector.errors import ProgrammingError
2 | from bd import nova_conexao
3 |
4 | sql = 'DELETE FROM contatos WHERE nome = %s'
5 | args = ('Lucas',)
6 |
7 | with nova_conexao() as conexao:
8 | try:
9 | cursor = conexao.cursor()
10 | cursor.execute(sql, args)
11 | conexao.commit()
12 | except ProgrammingError as e:
13 | print(f'Erro: {e.msg}')
14 | else:
15 | print(f'{cursor.rowcount} registro(s) deletado(s).')
--------------------------------------------------------------------------------
/banco_dados/excluir_tabela.py:
--------------------------------------------------------------------------------
1 | from mysql.connector.errors import ProgrammingError
2 | from bd import nova_conexao
3 |
4 | with nova_conexao() as conexao:
5 | try:
6 | cursor = conexao.cursor()
7 | cursor.execute('DROP TABLE IF EXISTS emails')
8 | except ProgrammingError as e:
9 | print(f'Erro: {e.msg}')
--------------------------------------------------------------------------------
/banco_dados/incluir_contato.py:
--------------------------------------------------------------------------------
1 | from mysql.connector.errors import ProgrammingError
2 | from bd import nova_conexao
3 |
4 | sql = 'INSERT INTO contatos (nome, tel) VALUES (%s, %s)'
5 | args = ('Lucas', '98765-4321')
6 |
7 | with nova_conexao() as conexao:
8 | try:
9 | cursor = conexao.cursor()
10 | cursor.execute(sql, args)
11 | conexao.commit()
12 | except ProgrammingError as e:
13 | print(f'Erro: {e.msg}')
14 | else:
15 | print('1 registro incluído, ID:', cursor.lastrowid)
--------------------------------------------------------------------------------
/banco_dados/incluir_varios_contatos.py:
--------------------------------------------------------------------------------
1 | from mysql.connector.errors import ProgrammingError
2 | from bd import nova_conexao
3 |
4 | sql = 'INSERT INTO contatos (nome, tel) VALUES (%s, %s)'
5 | args = (
6 | ('Ana', '96765-4321'),
7 | ('Bia', '97765-4321'),
8 | ('Luca', '89765-4321'),
9 | ('Lu', '98765-4321'),
10 | ('Gui', '98735-4321'),
11 | ('Beca', '98765-2221'),
12 | ('Pedro', '98765-6721'),
13 | )
14 |
15 | with nova_conexao() as conexao:
16 | try:
17 | cursor = conexao.cursor()
18 | cursor.executemany(sql, args)
19 | conexao.commit()
20 | except ProgrammingError as e:
21 | print(f'Erro: {e.msg}')
22 | else:
23 | print(f'Foram incluídos {cursor.rowcount} registros!')
--------------------------------------------------------------------------------
/banco_dados/listar_bancos.py:
--------------------------------------------------------------------------------
1 | from mysql.connector import connect
2 |
3 | conexao = connect(
4 | host='localhost',
5 | port=3306,
6 | user='root',
7 | passwd='12345678'
8 | )
9 |
10 | cursor = conexao.cursor()
11 | cursor.execute('SHOW DATABASES')
12 |
13 | for i, database in enumerate(cursor, start=1):
14 | print(f'Banco de Dados {i}: {database[0]}')
--------------------------------------------------------------------------------
/banco_dados/listar_tabelas.py:
--------------------------------------------------------------------------------
1 | from bd import nova_conexao
2 |
3 | with nova_conexao() as conexao:
4 | cursor = conexao.cursor()
5 | cursor.execute('SHOW TABLES')
6 |
7 | for i, table in enumerate(cursor, start=1):
8 | print(f'Tabela {i}: {table[0]}')
--------------------------------------------------------------------------------
/banco_dados/ordenar_contatos.py:
--------------------------------------------------------------------------------
1 | from bd import nova_conexao
2 |
3 | sql = 'SELECT nome, id FROM contatos ORDER BY nome DESC'
4 |
5 | with nova_conexao() as conexao:
6 | cursor = conexao.cursor()
7 | cursor.execute(sql)
8 |
9 | print('\n'.join(str(registro) for registro in cursor))
--------------------------------------------------------------------------------
/banco_dados/povoar_grupo.py:
--------------------------------------------------------------------------------
1 | from mysql.connector.errors import ProgrammingError
2 | from bd import nova_conexao
3 |
4 | sql = 'INSERT INTO grupos (descricao) VALUES (%s)'
5 | args = (
6 | ('Casa',),
7 | ('Trabalho',),
8 | )
9 |
10 | with nova_conexao() as conexao:
11 | try:
12 | cursor = conexao.cursor()
13 | cursor.executemany(sql, args)
14 | conexao.commit()
15 | except ProgrammingError as e:
16 | print(f'Erro: {e.msg}')
17 | else:
18 | print(f'Foram incluídos {cursor.rowcount} registros!')
--------------------------------------------------------------------------------
/banco_dados/requerimentos.py:
--------------------------------------------------------------------------------
1 | #!python3
2 | try:
3 | from mysql import connector
4 | except ModuleNotFoundError:
5 | print('MySQL Connector não instalado!')
6 | else:
7 | print('MySQL Connector instalado e pronto!')
--------------------------------------------------------------------------------
/banco_dados/requirements.txt:
--------------------------------------------------------------------------------
1 | mysql-connector==2.2.9
2 |
--------------------------------------------------------------------------------
/banco_dados/selecionar_campos.py:
--------------------------------------------------------------------------------
1 | from bd import nova_conexao
2 |
3 | sql = 'SELECT tel, nome FROM contatos'
4 |
5 | with nova_conexao() as conexao:
6 | cursor = conexao.cursor()
7 | cursor.execute(sql)
8 |
9 | for contato in cursor.fetchall():
10 | print('\t'.join(str(campo) for campo in contato))
--------------------------------------------------------------------------------
/banco_dados/selecionar_com_filtro.py:
--------------------------------------------------------------------------------
1 | from bd import nova_conexao
2 |
3 | sql = "SELECT * FROM contatos WHERE tel = '98765-4321'"
4 |
5 | with nova_conexao() as conexao:
6 | cursor = conexao.cursor()
7 | cursor.execute(sql)
8 |
9 | for x in cursor:
10 | print(x)
--------------------------------------------------------------------------------
/banco_dados/selecionar_contatos.py:
--------------------------------------------------------------------------------
1 | from mysql.connector.errors import ProgrammingError
2 | from bd import nova_conexao
3 |
4 | sql = 'SELECT * FROM contatos'
5 |
6 | with nova_conexao() as conexao:
7 | try:
8 | cursor = conexao.cursor()
9 | cursor.execute(sql)
10 | contatos = cursor.fetchall()
11 | except ProgrammingError as e:
12 | print(f'Erro: {e.msg}')
13 | else:
14 | for contato in contatos:
15 | print(f'{contato[2]:2d} - {contato[0]:10s} Telefone: {contato[1]}')
--------------------------------------------------------------------------------
/banco_dados/selecionar_contatos_limit.py:
--------------------------------------------------------------------------------
1 | from mysql.connector.errors import ProgrammingError
2 | from bd import nova_conexao
3 |
4 | sql = 'SELECT * FROM contatos LIMIT 5'
5 |
6 | with nova_conexao() as conexao:
7 | try:
8 | cursor = conexao.cursor()
9 | cursor.execute(sql)
10 | contatos = cursor.fetchall()
11 | except ProgrammingError as e:
12 | print(f'Erro: {e.msg}')
13 | else:
14 | for contato in contatos:
15 | print(f'{contato[2]:2d} - {contato[0]:10s} Telefone: {contato[1]}')
--------------------------------------------------------------------------------
/banco_dados/selecionar_contatos_limit_offset.py:
--------------------------------------------------------------------------------
1 | from mysql.connector.errors import ProgrammingError
2 | from bd import nova_conexao
3 |
4 | sql = 'SELECT * FROM contatos LIMIT %s OFFSET %s'
5 | args = (3, 8)
6 |
7 | with nova_conexao() as conexao:
8 | try:
9 | cursor = conexao.cursor()
10 | cursor.execute(sql, args)
11 | contatos = cursor.fetchall()
12 | except ProgrammingError as e:
13 | print(f'Erro: {e.msg}')
14 | else:
15 | for contato in contatos:
16 | print(f'{contato[2]:2d} - {contato[0]:10s} Telefone: {contato[1]}')
--------------------------------------------------------------------------------
/banco_dados/selecionar_filtro_parcial.py:
--------------------------------------------------------------------------------
1 | from bd import nova_conexao
2 |
3 | sql = "SELECT * FROM contatos WHERE nome like 'Lu%'"
4 |
5 | with nova_conexao() as conexao:
6 | cursor = conexao.cursor()
7 | cursor.execute(sql)
8 |
9 | for x in cursor:
10 | print(x)
--------------------------------------------------------------------------------
/banco_dados/selecionar_sem_sql_injection.py:
--------------------------------------------------------------------------------
1 | from bd import nova_conexao
2 |
3 | sql = "SELECT * FROM contatos WHERE nome like %s"
4 |
5 | with nova_conexao() as conexao:
6 | nome = input('Contato a localizar: ')
7 | args = (f'%{nome}%', )
8 |
9 | cursor = conexao.cursor()
10 | cursor.execute(sql, args)
11 |
12 | for x in cursor:
13 | print(x)
--------------------------------------------------------------------------------
/banco_dados/selecionar_um_registro.py:
--------------------------------------------------------------------------------
1 | from bd import nova_conexao
2 |
3 | sql = 'SELECT tel, nome FROM contatos LIMIT 3 OFFSET 10'
4 |
5 | with nova_conexao() as conexao:
6 | cursor = conexao.cursor()
7 | cursor.execute(sql)
8 |
9 | print(cursor.fetchone())
10 | print(cursor.fetchone())
11 | print(cursor.fetchone())
12 | print(cursor.fetchone())
13 | print(cursor.fetchone())
14 | print(cursor.fetchone())
15 | print(cursor.fetchone())
16 | print(cursor.fetchone())
17 |
--------------------------------------------------------------------------------
/banco_dados/sqllite.py:
--------------------------------------------------------------------------------
1 | from sqlite3 import connect, ProgrammingError, Row
2 |
3 | tabela_grupo = """
4 | CREATE TABLE IF NOT EXISTS grupos (
5 | id INTEGER PRIMARY KEY AUTOINCREMENT,
6 | descricao VARCHAR(30)
7 | )
8 | """
9 |
10 | tabela_contatos = """
11 | CREATE TABLE IF NOT EXISTS contatos (
12 | id INTEGER PRIMARY KEY AUTOINCREMENT,
13 | nome VARCHAR(50),
14 | tel VARCHAR(40),
15 | grupo_id INTEGER,
16 | FOREIGN KEY (grupo_id) REFERENCES grupos(id)
17 | )
18 | """
19 |
20 | insert_grupos = 'INSERT INTO grupos (descricao) VALUES (?)'
21 | select_grupos = 'SELECT id, descricao FROM grupos'
22 | insert_contatos = 'INSERT INTO contatos (nome, tel, grupo_id) VALUES (?, ?, ?)'
23 | select = """
24 | SELECT
25 | grupos.descricao AS grupo,
26 | contatos.nome AS contato
27 | FROM contatos
28 | INNER JOIN grupos ON contatos.grupo_id = grupos.id
29 | ORDER BY grupo, contato
30 | """
31 |
32 | try:
33 | conexao = connect(':memory:')
34 | conexao.row_factory = Row
35 |
36 | cursor = conexao.cursor()
37 | cursor.execute(tabela_grupo)
38 | cursor.execute(tabela_contatos)
39 |
40 | cursor.executemany(insert_grupos, (('Casa',), ('Trabalho',)))
41 | cursor.execute(select_grupos)
42 | grupos = {row['descricao']: row['id'] for row in cursor.fetchall()}
43 |
44 | contatos = (
45 | ('Arthur', '456', grupos['Casa']),
46 | ('Paulo', '789', grupos['Casa']),
47 | ('Ângelo', '000', grupos['Trabalho']),
48 | ('Eduardo', '987', None),
49 | ('Yuri', '654', grupos['Casa']),
50 | ('Leonardo', '321', grupos['Casa']),
51 | )
52 | cursor.executemany(insert_contatos, contatos)
53 |
54 | cursor.execute(select)
55 | for contato in cursor:
56 | print(contato['contato'], contato['grupo'])
57 | except ProgrammingError as e:
58 | print(f'Erro: {e.msg}')
--------------------------------------------------------------------------------
/estruturas_controle/break_continue.py:
--------------------------------------------------------------------------------
1 | for x in range(1, 11):
2 | if x % 2 == 0:
3 | continue
4 | print(x)
5 |
6 | for x in range(1, 11):
7 | if x == 5:
8 | break
9 | print(x)
10 |
11 | print('Fim!')
12 |
--------------------------------------------------------------------------------
/estruturas_controle/desafio_set.py:
--------------------------------------------------------------------------------
1 | PALAVRAS_PROIBIDAS = {'futebol', 'religião', 'política'}
2 | textos = [
3 | 'João gosta de futebol e política',
4 | 'A praia foi divertida',
5 | ]
6 |
7 | for texto in textos:
8 | intersecao = PALAVRAS_PROIBIDAS.intersection(set(texto.lower().split()))
9 | if intersecao:
10 | print('Texto possui palavras proibidas:', intersecao)
11 | else:
12 | print('Texto autorizado:', texto)
13 |
--------------------------------------------------------------------------------
/estruturas_controle/for_1.py:
--------------------------------------------------------------------------------
1 | for i in range(1, 11):
2 | print('i = {}'.format(i))
3 |
4 | for j in range(10):
5 | print(f'j = {j}')
6 |
7 | for x in range(1, 11):
8 | for y in range(1, 11):
9 | print(f'{x} * {y} = {x * y}')
10 |
--------------------------------------------------------------------------------
/estruturas_controle/for_2.py:
--------------------------------------------------------------------------------
1 | palavra = 'paralelepípedo'
2 | for letra in palavra:
3 | print(letra, end=',')
4 | print('Fim')
5 |
6 | aprovados = ['Rafaela', 'Pedro', 'Renato', 'Maria']
7 | for nome in aprovados:
8 | print(nome)
9 |
10 | for posicao, nome in enumerate(aprovados):
11 | print(f'{posicao + 1})', nome)
12 |
13 | dias_semana = ('Domingo', 'Segunda', 'Terça',
14 | 'Quarta', 'Quinta', 'Sexta', 'Sábado')
15 | for dia in dias_semana:
16 | print(f'Hoje é {dia}')
17 |
18 | for numero in {1, 2, 3, 4, 5, 6}:
19 | print(numero)
20 |
--------------------------------------------------------------------------------
/estruturas_controle/for_3.py:
--------------------------------------------------------------------------------
1 | produto = {'nome': 'Caneta Chic', 'preco': 14.99,
2 | 'importada': True, 'estoque': 793}
3 |
4 | for chave in produto:
5 | print(chave)
6 |
7 | for valor in produto.values():
8 | print(valor)
9 |
10 | for chave, valor in produto.items():
11 | print(chave, '=', valor)
12 |
13 | print(chave, valor)
14 |
--------------------------------------------------------------------------------
/estruturas_controle/for_4.py:
--------------------------------------------------------------------------------
1 | # for i in range(1, 11):
2 | # if i == 6:
3 | # break
4 | # print(i)
5 | # else:
6 | # print('Fim!')
7 |
8 | from random import randint
9 |
10 |
11 | def sortear_dado():
12 | return randint(1, 6)
13 |
14 |
15 | for i in range(1, 7):
16 | if i % 2 == 1:
17 | continue
18 |
19 | if sortear_dado() == i:
20 | print('ACERTOU', i)
21 | break
22 | else:
23 | print('Não acertou o número!')
24 |
--------------------------------------------------------------------------------
/estruturas_controle/for_com_else.py:
--------------------------------------------------------------------------------
1 | PALAVRAS_PROIBIDAS = ('futebol', 'religião', 'política')
2 | textos = [
3 | 'João gosta de futebol e política',
4 | 'A praia foi divertida',
5 | ]
6 |
7 | for texto in textos:
8 | for palavra in texto.lower().split():
9 | if palavra in PALAVRAS_PROIBIDAS:
10 | print('Texto possui pelo menos uma palavra proibida:', palavra)
11 | break
12 | else:
13 | print('Texto autorizado:', texto)
14 |
--------------------------------------------------------------------------------
/estruturas_controle/for_sem_else.py:
--------------------------------------------------------------------------------
1 | PALAVRAS_PROIBIDAS = ('futebol', 'religião', 'política')
2 | textos = [
3 | 'João gosta de futebol e política',
4 | 'A praia foi divertida',
5 | ]
6 |
7 | for texto in textos:
8 | found = False
9 | for palavra in texto.lower().split():
10 | if palavra in PALAVRAS_PROIBIDAS:
11 | print('Texto possui pelo menos uma palavra proibida:', palavra)
12 | found = True
13 | break
14 |
15 | if not found:
16 | print('Texto autorizado:', texto)
17 |
--------------------------------------------------------------------------------
/estruturas_controle/if_else_1.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 |
3 |
4 | def nota_conceito(valor):
5 | nota = float(valor)
6 |
7 | if nota > 10:
8 | return 'Nota inválida'
9 | elif nota >= 9.1:
10 | return 'A'
11 | elif nota >= 8.1:
12 | return 'A-'
13 | elif nota >= 7.1:
14 | return 'B'
15 | elif nota >= 6.1:
16 | return 'B-'
17 | elif nota >= 5.1:
18 | return 'C'
19 | elif nota >= 4.1:
20 | return 'C-'
21 | elif nota >= 3.1:
22 | return 'D'
23 | elif nota >= 2.1:
24 | return 'D-'
25 | elif nota >= 1.1:
26 | return 'E'
27 | elif nota >= 0:
28 | return 'E-'
29 | else:
30 | return 'Nota inválida'
31 |
32 |
33 | if __name__ == '__main__':
34 | valor_informado = input('Nota do aluno: ')
35 | conceito = nota_conceito(valor_informado)
36 | print(conceito)
37 |
--------------------------------------------------------------------------------
/estruturas_controle/if_else_2.py:
--------------------------------------------------------------------------------
1 | def faixa_etaria(idade):
2 | if 0 <= idade < 18:
3 | return 'Menor de idade'
4 | elif idade in range(18, 65):
5 | return 'Adulto'
6 | elif idade in range(65, 100):
7 | return 'Melhor idade'
8 | elif idade >= 100:
9 | return 'Centenário'
10 | else:
11 | return 'idade inválida'
12 |
13 |
14 | if __name__ == '__main__':
15 | for idade in (17, 0, 35, 87, 113, -2):
16 | print(f'{idade}: {faixa_etaria(idade)}')
17 |
--------------------------------------------------------------------------------
/estruturas_controle/switch_1.py:
--------------------------------------------------------------------------------
1 | def get_dia_semana(dia):
2 | dias = {
3 | 1: 'Domingo',
4 | 2: 'Segunda',
5 | 3: 'Terça',
6 | 4: 'Quarta',
7 | 5: 'Quinta',
8 | 6: 'Sexta',
9 | 7: 'Sábado',
10 | }
11 | return dias.get(dia, '** inválido **')
12 |
13 |
14 | if __name__ == '__main__':
15 | for dia in range(0, 9):
16 | print(f'{dia}: {get_dia_semana(dia)}')
17 |
--------------------------------------------------------------------------------
/estruturas_controle/switch_2.py:
--------------------------------------------------------------------------------
1 | def get_tipo_dia(dia):
2 | dias = {
3 | 1: 'Fim de semana',
4 | 2: 'Dia de semana',
5 | 3: 'Dia de semana',
6 | 4: 'Dia de semana',
7 | 5: 'Dia de semana',
8 | 6: 'Dia de semana',
9 | 7: 'Fim de semana',
10 | }
11 | return dias.get(dia, '** inválido **')
12 |
13 |
14 | if __name__ == '__main__':
15 | for dia in range(8):
16 | print(f'{dia}: {get_tipo_dia(dia)}')
17 |
--------------------------------------------------------------------------------
/estruturas_controle/while_1.py:
--------------------------------------------------------------------------------
1 | # while True:
2 | # print('Vai demorar muitooooo')
3 |
4 | from random import randint
5 |
6 | numero_informado = -1
7 | numero_secreto = randint(0, 9)
8 |
9 | while numero_informado != numero_secreto:
10 | numero_informado = int(input('Informe o número: '))
11 |
12 | print('Número secreto {} foi encontrado!'.format(numero_secreto))
13 |
--------------------------------------------------------------------------------
/estruturas_controle_projetos/exemplo_recursao.py:
--------------------------------------------------------------------------------
1 | def imprimir(maximo, atual):
2 | # condição de parada!
3 | if atual < maximo:
4 | print(atual)
5 | imprimir(maximo, atual + 1)
6 |
7 |
8 | imprimir(990, 1)
9 |
--------------------------------------------------------------------------------
/estruturas_controle_projetos/fibonacci_recursive_v1.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | def fibonacci(quantidade, sequencia=(0, 1)):
3 | # Importante: Condição de parada
4 | if len(sequencia) == quantidade:
5 | return sequencia
6 | return fibonacci(quantidade, sequencia + (sum(sequencia[-2:]),))
7 |
8 |
9 | if __name__ == '__main__':
10 | # Listar os 20 primeiros números da sequência
11 | for fib in fibonacci(20):
12 | print(fib)
13 |
--------------------------------------------------------------------------------
/estruturas_controle_projetos/fibonacci_recursive_v2.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | def fibonacci(quantidade, sequencia=(0, 1)):
3 | # Importante: Condição de parada
4 | return sequencia if len(sequencia) == quantidade else \
5 | fibonacci(quantidade, sequencia + (sum(sequencia[-2:]),))
6 |
7 |
8 | if __name__ == '__main__':
9 | # Listar os 20 primeiros números da sequência
10 | for fib in fibonacci(20):
11 | print(fib)
12 |
--------------------------------------------------------------------------------
/estruturas_controle_projetos/fibonacci_v1.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 |
3 |
4 | # 0, 1, 1, 2, 3, 5, 8, 13, 21...
5 | def fibonacci():
6 | penultimo = 0
7 | ultimo = 1
8 | print(f'{penultimo},{ultimo}', end=',')
9 | while True:
10 | proximo = penultimo + ultimo
11 | print(proximo, end=',')
12 | penultimo = ultimo
13 | ultimo = proximo
14 |
15 |
16 | if __name__ == '__main__':
17 | fibonacci()
18 |
--------------------------------------------------------------------------------
/estruturas_controle_projetos/fibonacci_v2.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 |
3 |
4 | # 0, 1, 1, 2, 3, 5, 8, 13, 21...
5 | def fibonacci(limite):
6 | penultimo = 0
7 | ultimo = 1
8 | print(f'{penultimo},{ultimo}', end=',')
9 | while ultimo < limite:
10 | proximo = penultimo + ultimo
11 | print(proximo, end=',')
12 | penultimo = ultimo
13 | ultimo = proximo
14 |
15 |
16 | if __name__ == '__main__':
17 | fibonacci(20000)
18 |
--------------------------------------------------------------------------------
/estruturas_controle_projetos/fibonacci_v3.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 |
3 |
4 | # 0, 1, 1, 2, 3, 5, 8, 13, 21...
5 | def fibonacci(limite):
6 | penultimo = 0
7 | ultimo = 1
8 | print(f'{penultimo},{ultimo}', end=',')
9 | while ultimo < limite:
10 | penultimo, ultimo = ultimo, penultimo + ultimo
11 | print(ultimo, end=',')
12 |
13 |
14 | if __name__ == '__main__':
15 | fibonacci(20000)
16 |
--------------------------------------------------------------------------------
/estruturas_controle_projetos/fibonacci_v4.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 |
3 |
4 | # 0, 1, 1, 2, 3, 5, 8, 13, 21...
5 | def fibonacci(limite):
6 | resultado = [0, 1]
7 | while resultado[-1] < limite:
8 | resultado.append(resultado[-2] + resultado[-1])
9 | return resultado
10 |
11 |
12 | if __name__ == '__main__':
13 | for fib in fibonacci(10000):
14 | print(fib)
15 |
--------------------------------------------------------------------------------
/estruturas_controle_projetos/fibonacci_v5.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 |
3 |
4 | # 0, 1, 1, 2, 3, 5, 8, 13, 21...
5 | def fibonacci(limite):
6 | resultado = [0, 1]
7 | while resultado[-1] < limite:
8 | resultado.append(sum(resultado[-2:]))
9 | return resultado
10 |
11 |
12 | if __name__ == '__main__':
13 | for fib in fibonacci(10000):
14 | print(fib)
15 |
--------------------------------------------------------------------------------
/estruturas_controle_projetos/fibonacci_v6.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 |
3 |
4 | # 0, 1, 1, 2, 3, 5, 8, 13, 21...
5 | def fibonacci(quantidade):
6 | resultado = [0, 1]
7 | for _ in range(2, quantidade):
8 | resultado.append(sum(resultado[-2:]))
9 | return resultado
10 |
11 |
12 | if __name__ == '__main__':
13 | # Listar os 20 primeiros números da sequência
14 | for fib in fibonacci(20):
15 | print(fib)
16 |
--------------------------------------------------------------------------------
/funcoes/Untitled-1.py:
--------------------------------------------------------------------------------
1 | def soma(a, b):
2 | def soma_c(c):
3 | return a + b + c
4 | return soma_c
5 |
6 |
7 | print(soma(2, 3)(5))
8 |
--------------------------------------------------------------------------------
/funcoes/callable_object.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | class Potencia:
3 | # Calcula uma potência específica
4 | def __init__(self, expoente):
5 | self.expoente = expoente
6 |
7 | def __call__(self, base):
8 | return base ** self.expoente
9 |
10 |
11 | if __name__ == '__main__':
12 | quadrado = Potencia(2)
13 | cubo = Potencia(3)
14 |
15 | if callable(quadrado) and callable(cubo):
16 | print(f'3² => {quadrado(3)}')
17 | print(f'5³ => {cubo(5)}')
18 | print(Potencia(4)(2))
19 |
--------------------------------------------------------------------------------
/funcoes/callable_packing.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | def calc_preco_final(preco_bruto, calc_imposto, *params):
3 | return preco_bruto + preco_bruto * calc_imposto(*params)
4 |
5 |
6 | def imposto_x(importado):
7 | return 0.22 if importado else 0.13
8 |
9 |
10 | def imposto_y(explosivo, fator_mult=1):
11 | return 0.11 * fator_mult if explosivo else 0
12 |
13 |
14 | if __name__ == '__main__':
15 | preco_bruto = 134.98
16 | preco_final = calc_preco_final(preco_bruto, imposto_x, True)
17 | preco_final = calc_preco_final(preco_final, imposto_y, True, 1.5)
18 | print(f'Preço final R$ {preco_final}')
19 |
--------------------------------------------------------------------------------
/funcoes/callable_packing_nomeado.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | def calc_preco_final(preco_bruto, calc_imposto, **params):
3 | return preco_bruto + preco_bruto * calc_imposto(**params)
4 |
5 |
6 | def imposto_x(importado):
7 | return 0.22 if importado else 0.13
8 |
9 |
10 | def imposto_y(explosivo, fator_mult=1):
11 | return 0.11 * fator_mult if explosivo else 0
12 |
13 |
14 | if __name__ == '__main__':
15 | preco_bruto = 134.98
16 | preco_final = calc_preco_final(preco_bruto, imposto_x, importado=True)
17 | preco_final = calc_preco_final(preco_final, imposto_y,
18 | explosivo=True, fator_mult=1.5)
19 | print(f'Preço final R$ {preco_final}')
20 |
--------------------------------------------------------------------------------
/funcoes/correcao_arg_padrao_mutavel.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | def fibonacci(sequencia=None):
3 | sequencia = sequencia or [0, 1]
4 | sequencia.append(sequencia[-1] + sequencia[-2])
5 | return sequencia
6 |
7 |
8 | if __name__ == '__main__':
9 | inicio = fibonacci()
10 | print(inicio, id(inicio))
11 | print(fibonacci(inicio))
12 | restart = fibonacci()
13 | print(restart, id(restart))
14 | assert restart == [0, 1, 1]
15 |
--------------------------------------------------------------------------------
/funcoes/decorator.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | def log(function):
3 | def decorator(*args, **kwargs):
4 | print(f'Inicio da chamada da função: {function.__name__}')
5 | print(f'args: {args}')
6 | print(f'kwargs: {kwargs}')
7 | resultado = function(*args, **kwargs)
8 | print(f'Resultado da chamada: {resultado}')
9 | return resultado
10 | return decorator
11 |
12 |
13 | @log
14 | def soma(x, y):
15 | return x + y
16 |
17 |
18 | @log
19 | def sub(x, y):
20 | return x - y
21 |
22 |
23 | if __name__ == '__main__':
24 | print(soma(5, 7))
25 | print(sub(5, y=7))
26 |
--------------------------------------------------------------------------------
/funcoes/desafio_html.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | def tag(tag, *args, **kwargs):
3 | if 'html_class' in kwargs:
4 | kwargs['class'] = kwargs.pop('html_class')
5 | attrs = ''.join(f'{k}="{v}" ' for k, v in kwargs.items())
6 | inner = ''.join(args)
7 | return f'<{tag} {attrs}>{inner}{tag}>'
8 |
9 |
10 | if __name__ == '__main__':
11 | print(
12 | tag('p',
13 | tag('span', 'Curso de Python 3, por '),
14 | tag('strong', 'Juracy Filho', id='jf'),
15 | tag('span', ' e '),
16 | tag('strong', 'Leonardo Leitão', id='ll'),
17 | tag('span', '.'),
18 | html_class='alert')
19 | )
20 |
--------------------------------------------------------------------------------
/funcoes/gerador_html_v1.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | def tag_bloco(texto, classe='success'):
3 | return f'
{texto}
'
4 |
5 |
6 | if __name__ == '__main__':
7 | # Testes (assertions)
8 | assert tag_bloco('Incluído com sucesso!') == \
9 | 'Incluído com sucesso!
'
10 | assert tag_bloco('Impossível excluir!', 'error') == \
11 | 'Impossível excluir!
'
12 | print(tag_bloco('bloco'))
13 |
--------------------------------------------------------------------------------
/funcoes/gerador_html_v2.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | def tag_bloco(texto, classe='success', inline=False):
3 | tag = 'span' if inline else 'div'
4 | return f'<{tag} class="{classe}">{texto}{tag}>'
5 |
6 |
7 | if __name__ == '__main__':
8 | print(tag_bloco('bloco'))
9 | print(tag_bloco('inline e classe', 'info', True))
10 | print(tag_bloco('inline', inline=True))
11 | print(tag_bloco(inline=True, texto='inline'))
12 | print(tag_bloco('falhou', classe='error'))
13 |
--------------------------------------------------------------------------------
/funcoes/gerador_html_v3.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | def tag_bloco(conteudo, classe='success', inline=False):
3 | tag = 'span' if inline else 'div'
4 | return f'<{tag} class="{classe}">{conteudo}{tag}>'
5 |
6 |
7 | def tag_lista(*itens):
8 | lista = ''.join(f'{item}' for item in itens)
9 | return f''
10 |
11 |
12 | if __name__ == '__main__':
13 | print(tag_bloco('bloco'))
14 | print(tag_bloco('inline e classe', 'info', True))
15 | print(tag_bloco('inline', inline=True))
16 | print(tag_bloco(inline=True, conteudo='inline'))
17 | print(tag_bloco('falhou', classe='error'))
18 | print(tag_bloco(tag_lista('Item 1', 'Item 2'), classe='info'))
19 |
--------------------------------------------------------------------------------
/funcoes/gerador_html_v4.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | def tag_bloco(conteudo, *args, classe='success', inline=False):
3 | tag = 'span' if inline else 'div'
4 | html = conteudo if not callable(conteudo) else conteudo(*args)
5 | return f'<{tag} class="{classe}">{html}{tag}>'
6 |
7 |
8 | def tag_lista(*itens):
9 | lista = ''.join(f'{item}' for item in itens)
10 | return f''
11 |
12 |
13 | if __name__ == '__main__':
14 | print(tag_bloco('bloco'))
15 | print(tag_bloco('inline e classe', classe='info', inline=True))
16 | print(tag_bloco('inline', inline=True))
17 | print(tag_bloco(inline=True, conteudo='inline'))
18 | print(tag_bloco('falhou', classe='error'))
19 | print(tag_bloco(tag_lista('Item 1', 'Item 2'), classe='info'))
20 | print(tag_bloco(tag_lista, 'Sábado', 'Domingo',
21 | classe='info', inline=True))
22 |
--------------------------------------------------------------------------------
/funcoes/gerador_html_v5.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | bloco_atrs = ('bloco_accesskey', 'bloco_id')
3 | ul_atrs = ('ul_id', 'ul_style')
4 |
5 |
6 | def filtrar_atrs(informados, suportados):
7 | return ' '.join(f'{k.split("_")[-1]}="{v}"'
8 | for k, v in informados.items() if k in suportados)
9 |
10 |
11 | def tag_bloco(conteudo, *args, classe='success', inline=False, **novos_atrs):
12 | tag = 'span' if inline else 'div'
13 | html = conteudo if not callable(conteudo) \
14 | else conteudo(*args, **novos_atrs)
15 | atributos = filtrar_atrs(novos_atrs, bloco_atrs)
16 | return f'<{tag} {atributos} class="{classe}">{html}{tag}>'
17 |
18 |
19 | def tag_lista(*itens, **novos_atrs):
20 | lista = ''.join(f'{item}' for item in itens)
21 | return f''
22 |
23 |
24 | if __name__ == '__main__':
25 | print(tag_bloco('bloco'))
26 | print(tag_bloco('inline e classe', classe='info', inline=True))
27 | print(tag_bloco('inline', inline=True))
28 | print(tag_bloco(inline=True, conteudo='inline'))
29 | print(tag_bloco('falhou', classe='error'))
30 | print(tag_bloco(tag_lista('Item 1', 'Item 2'), classe='info'))
31 | print(tag_bloco(tag_lista, 'Sábado', 'Domingo',
32 | classe='info', inline=True))
33 | print(tag_bloco(tag_lista, 'Item 1', 'Item 2', classe='info',
34 | bloco_accesskey='m', bloco_id='conteudo', ul_id='lista',
35 | ul_style='color:red'))
36 |
--------------------------------------------------------------------------------
/funcoes/packing.py:
--------------------------------------------------------------------------------
1 | def soma_2(a, b):
2 | return a + b
3 |
4 |
5 | def soma_3(a, b, c):
6 | return a + b + c
7 |
8 |
9 | def soma_n(*numeros):
10 | soma = 0
11 | for n in numeros:
12 | soma += n
13 | return soma
14 |
15 |
16 | if __name__ == '__main__':
17 | print(soma_2(2, 3))
18 | print(soma_3(2, 4, 6))
19 |
20 | # packing
21 | print(soma_n(1))
22 | print(soma_n(1, 1))
23 | print(soma_n(1, 1, 1, 1, 1, 1, 1))
24 |
25 | # unpacking
26 | tupla_nums = (1, 2, 3)
27 | print(soma_3(*tupla_nums))
28 | lista_nums = [1, 2, 3]
29 | print(soma_3(*lista_nums))
30 |
--------------------------------------------------------------------------------
/funcoes/packing_nomeado.py:
--------------------------------------------------------------------------------
1 | # **kwargs
2 | def resultado_f1(**podium):
3 | for posicao, piloto in podium.items():
4 | print(f'{posicao} -> {piloto}')
5 |
6 |
7 | if __name__ == '__main__':
8 | resultado_f1(primeiro='L. Hamilton',
9 | segundo='M. Verstappen',
10 | terceiro='S. Vettel')
11 |
--------------------------------------------------------------------------------
/funcoes/problema_arg_padrao_mutavel.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | def fibonacci(sequencia=[0, 1]):
3 | # Uso de mutáveis como valor default (armadilha)
4 | sequencia.append(sequencia[-1] + sequencia[-2])
5 | return sequencia
6 |
7 |
8 | if __name__ == '__main__':
9 | inicio = fibonacci()
10 | print(inicio, id(inicio))
11 | print(fibonacci(inicio))
12 | restart = fibonacci()
13 | print(restart, id(restart))
14 | assert restart == [0, 1, 1]
15 |
--------------------------------------------------------------------------------
/funcoes/prog_funcional_spoiler.py:
--------------------------------------------------------------------------------
1 | def executar(funcao):
2 | if callable(funcao):
3 | funcao()
4 |
5 |
6 | def bom_dia():
7 | print('Bom dia!')
8 |
9 |
10 | def boa_tarde():
11 | print('Boa tarde!')
12 |
13 |
14 | if __name__ == '__main__':
15 | executar(bom_dia)
16 | executar(boa_tarde)
17 | executar(1)
18 |
--------------------------------------------------------------------------------
/funcoes/todos_parametros.py:
--------------------------------------------------------------------------------
1 | def todos_params(*args, **kwargs):
2 | print(f'args: {args}')
3 | print(f'kwargs: {kwargs}')
4 |
5 |
6 | if __name__ == '__main__':
7 | todos_params('a', 'b', 'c')
8 | todos_params(1, 2, 3, legal=True, valor=12.99)
9 | todos_params('Ana', False, [1, 2, 3], tamanho='M', fragil=False)
10 | todos_params(primeiro='João', segundo='Maria')
11 | todos_params('Maria', primeiro='João')
12 |
--------------------------------------------------------------------------------
/funcoes/unpacking_nomeado.py:
--------------------------------------------------------------------------------
1 | # **kwargs
2 | def resultado_f1(primeiro, segundo, terceiro):
3 | print(f'1) {primeiro}')
4 | print(f'2) {segundo}')
5 | print(f'3) {terceiro}')
6 |
7 |
8 | if __name__ == '__main__':
9 | podium = {'segundo': 'M. Verstappen',
10 | 'primeiro': 'L. Hamilton',
11 | 'terceiro': 'S. Vettel'}
12 | resultado_f1(**podium)
13 |
--------------------------------------------------------------------------------
/fundamentos/builtins.py:
--------------------------------------------------------------------------------
1 | # type()
2 | type(1)
3 | __builtins__.type('Fala Galera!')
4 | __builtins__.print(10 / 3)
5 |
6 | # __builtins__.help(__builtins__.dir)
7 |
8 | # a = 7
9 | # import math
10 | # dir()
11 | # dir(__builtins__)
12 |
13 |
14 | nome = 'João da Silva'
15 | type(nome)
16 | # __builtin__.len(nome)
17 |
18 | dir()
19 |
--------------------------------------------------------------------------------
/fundamentos/coercao_automatica.py:
--------------------------------------------------------------------------------
1 | # %%
2 | 10 / 2
3 | type(10 / 2)
4 | 10 / 3
5 | 10 // 3
6 | type(10 // 3)
7 | 10 // 3.3
8 | type(10 // 3.3)
9 | 10 / 2.5
10 | 2 + True
11 | 2 + False
12 | type(1 + 2)
13 | type(1 + 2.5)
14 |
--------------------------------------------------------------------------------
/fundamentos/comentarios.py:
--------------------------------------------------------------------------------
1 | # %%
2 | # Minhas variáveis
3 | salario = 3450.45
4 | despesas = 2456.2
5 |
6 | """
7 | A ideia é calcular o
8 | quando vai sobrar no
9 | final do mes!
10 | """
11 | print(salario - despesas)
12 |
13 | # print('Fim')
14 | print('Fim de verdade') # comentário aqui tb vale!
15 |
16 | '''
17 | A ideia é calcular o
18 | quando vai sobrar no
19 | final do mes!
20 | '''
21 | print('Agora sim o fim de verdade')
22 |
--------------------------------------------------------------------------------
/fundamentos/conjunto.py:
--------------------------------------------------------------------------------
1 | # %%
2 | a = {1, 2, 3}
3 | type(a)
4 | # a[0]
5 | a = set('coddddd3r')
6 | print(a)
7 | print('3' in a, 4 not in a)
8 | {1, 2, 3} == {3, 2, 1, 3}
9 |
10 | # operacoes
11 | c1 = {1, 2}
12 | c2 = {2, 3}
13 | c1.union(c2)
14 | c1.intersection(c2)
15 | c1.update(c2)
16 | c1
17 | c2 <= c1
18 | c1 >= c2
19 |
20 | {1, 2, 3} - {2}
21 | c1 - c2
22 | c1 -= {2}
23 | c1
24 |
--------------------------------------------------------------------------------
/fundamentos/conversao_tipos.py:
--------------------------------------------------------------------------------
1 | # %%
2 | 2 + 3
3 | '2' + '3'
4 | # 2 + '3'
5 | # print(2 + '3')
6 |
7 | a = 2
8 | b = '3'
9 |
10 | print(type(a))
11 | print(type(b))
12 |
13 | print(a + int(b))
14 | print(str(a) + b)
15 |
16 | type(str(a))
17 |
18 | # print(2 + int('3.4'))
19 |
--------------------------------------------------------------------------------
/fundamentos/dicionario.py:
--------------------------------------------------------------------------------
1 | # %%
2 | pessoa = {'nome': 'Prof(a). Ana', 'idade': 38,
3 | 'cursos': ['Inglês', 'Português']}
4 | type(pessoa)
5 | dir(dict)
6 | len(pessoa)
7 |
8 | pessoa
9 | pessoa['nome']
10 | pessoa['idade']
11 | pessoa['cursos']
12 | pessoa['cursos'][1]
13 | # pessoa['tags']
14 | pessoa.keys()
15 | pessoa.values()
16 | pessoa.items()
17 | pessoa.get('idade')
18 | pessoa.get('tags')
19 | pessoa.get('tags', [])
20 |
21 | # %%
22 | pessoa = {'nome': 'Prof. Alberto', 'idade': 43, 'cursos': ['React', 'Python']}
23 | pessoa['idade'] = 44
24 | pessoa['cursos'].append('Angular')
25 | pessoa
26 | pessoa.pop('idade')
27 | pessoa
28 | pessoa.update({'idade': 40, 'Sexo': 'M'})
29 | pessoa
30 | del pessoa['cursos']
31 | pessoa
32 | pessoa.clear()
33 | pessoa
34 |
--------------------------------------------------------------------------------
/fundamentos/interpolacao.py:
--------------------------------------------------------------------------------
1 | # %%
2 | from string import Template
3 |
4 | nome, idade = 'Ana', 30
5 |
6 | print('Nome: %s Idade: %d' % (nome, idade)) # mais antiga
7 | print('Nome: {0} Idade: {1}'.format(nome, idade)) # python < 3.6
8 | print(f'Nome: {nome} Idade: {idade}') # python >= 3.6
9 |
10 |
11 | s = Template('Nome: $nome Idade: $idade')
12 | print(s.substitute(nome=nome, idade=idade))
13 |
--------------------------------------------------------------------------------
/fundamentos/lista.py:
--------------------------------------------------------------------------------
1 | # %%
2 | lista = []
3 | type(lista)
4 | dir(lista)
5 | # help(list)
6 | len(lista)
7 | lista.append(1)
8 | lista.append(5)
9 | lista
10 | len(lista)
11 |
12 | nova_lista = [1, 5, 'Ana', 'Bia']
13 | nova_lista
14 | nova_lista.remove(5)
15 | nova_lista
16 | nova_lista.reverse()
17 | nova_lista
18 |
19 | # %%
20 | lista = [1, 5, 'Rebeca', 'Guilherme', 3.1415]
21 | lista.index('Guilherme')
22 | # lista.index(42)
23 | lista[2]
24 | 1 in lista
25 | 'Rebeca' in lista
26 | 'Pedro' not in lista
27 | lista[0]
28 | lista[4]
29 | # lista[5]
30 | lista[-1]
31 | lista[-5]
32 |
33 | # %%
34 | lista = ['Ana', 'Lia', 'Rui', 'Paulo', 'Dani']
35 | lista[1:3]
36 | lista[1:-1]
37 | lista[1:]
38 | lista[:-1]
39 | lista[:]
40 | lista[::2]
41 | lista[::-1]
42 | del lista[2]
43 | lista
44 | del lista[1:]
45 | lista
46 |
--------------------------------------------------------------------------------
/fundamentos/mais_operadores.py:
--------------------------------------------------------------------------------
1 | # %%
2 | # Operador de Membro
3 | lista = [1, 2, 3, 'Ana', 'Carla']
4 | 2 in lista
5 | 'Ana' not in lista
6 |
7 | # Operador de Identidade
8 | x = 3
9 | y = x
10 | z = 3
11 | x is y
12 | y is z
13 | x is not z
14 |
15 | lista_a = [1, 2, 3]
16 | lista_b = lista_a
17 | lista_c = [1, 2, 3]
18 |
19 | lista_a is lista_b
20 | lista_b is lista_c
21 | lista_a is not lista_c
22 |
--------------------------------------------------------------------------------
/fundamentos/operadores_aritmeticos.py:
--------------------------------------------------------------------------------
1 | # %%
2 | print(2 + 3)
3 | print(4 - 7)
4 | print(2 * 5.3)
5 | print(9.4 / 3)
6 | print(9.4 // 3)
7 | print(2 ** 8)
8 | print(10 % 3)
9 |
10 | a = 12
11 | b = a
12 | print(a + b)
13 |
14 | # %%
15 | # Minhas variáveis
16 | salario = 3450.45
17 | despesas = 2456.2
18 |
19 | # Resposta do desafio
20 | percentual_comprometido = despesas / salario * 100
21 | percentual_comprometido
22 |
--------------------------------------------------------------------------------
/fundamentos/operadores_atribuicao.py:
--------------------------------------------------------------------------------
1 | # %%
2 | a = 3
3 | a = a + 7
4 | print(a)
5 |
6 | # a = 5
7 | a += 5 # a = a + 5
8 | print(a)
9 |
10 | a -= 3
11 | print(a)
12 |
13 | a *= 2
14 | print(a)
15 |
16 | a /= 4
17 | print(a)
18 |
19 | a %= 4
20 | print(a)
21 |
22 | a **= 8
23 | print(a)
24 |
25 | a //= 256
26 | print(a)
27 |
--------------------------------------------------------------------------------
/fundamentos/operadores_logicos.py:
--------------------------------------------------------------------------------
1 | # %%
2 | True or False
3 | 7 != 3 and 2 > 3
4 |
5 | # Tabela verdade do AND
6 | True and True
7 | True and False
8 | False and True
9 | False and False
10 | True and True and False and True and True and True
11 |
12 | # Tabela verdade do OR
13 | True or True
14 | True or False
15 | False or True
16 | False or False
17 | False or False or True or False or False or False
18 |
19 | # Tabela verdade do XOR
20 | # True != True
21 | # True != False
22 | # False != True
23 | # False != False
24 |
25 | # Operador de Negação (unário)
26 | not True
27 | not False
28 |
29 | not 0
30 | not 1
31 | not not -1
32 | not not True
33 |
34 | # Cuidado!
35 | True & False
36 | False | True
37 | True ^ False
38 |
39 | # AND Bit-a-bit
40 | # 3 = 11
41 | # 2 = 10
42 | # _ = 10
43 | 3 & 2
44 |
45 | # OR Bit-a-bit
46 | # 3 = 11
47 | # 2 = 10
48 | # _ = 11
49 | 3 | 2
50 |
51 | # XOR Bit-a-bit
52 | # 3 = 11
53 | # 2 = 10
54 | # _ = 01
55 | 3 ^ 2
56 |
57 | # Um pouco de realidade
58 | saldo = 1000
59 | salario = 4000
60 | despesas = 3900
61 |
62 | saldo_positivo = saldo > 0
63 | despesas_controladas = salario - despesas >= 0.2 * salario
64 |
65 | meta = saldo_positivo and despesas_controladas
66 | meta
67 |
68 | # %%
69 | # Desafio Operadores Lógicos
70 |
71 | # Os Trabalhos
72 | trabalho_terca = False
73 | trabalho_quinta = False
74 |
75 | """
76 | - Confirmando os 2: TV 50' + Sorvete
77 | - Confirmando apenas 1: TV 32' + Sorvete
78 | - Nenhum confirmado: Fica em casa
79 | """
80 | tv_50 = trabalho_terca and trabalho_quinta
81 | sorvete = trabalho_terca or trabalho_quinta
82 | tv_32 = trabalho_terca != trabalho_quinta # xor
83 | mais_saudavel = not sorvete
84 |
85 | print("Tv50={} Tv32={} Sorvete={} Saudável={}"
86 | .format(tv_50, tv_32, sorvete, mais_saudavel))
87 |
88 | # "{}, {} = {}".format(1, False, 'resultado')
89 |
--------------------------------------------------------------------------------
/fundamentos/operadores_relacionais.py:
--------------------------------------------------------------------------------
1 | # %%
2 | 3 > 4
3 | 4 >= 3
4 | 1 < 2
5 | 3 <= 1
6 | 3 != 2
7 | 3 == 3
8 | 2 == '2'
9 |
--------------------------------------------------------------------------------
/fundamentos/operadores_ternarios.py:
--------------------------------------------------------------------------------
1 | # %%
2 | esta_chuvendo = False
3 |
4 | print('Hoje estou com as roupas ' + ('secas.', 'molhadas.')[esta_chuvendo])
5 | print('Hoje estou com as roupas ' +
6 | ('molhadas.' if esta_chuvendo else 'secas.'))
7 |
--------------------------------------------------------------------------------
/fundamentos/operadores_unarios.py:
--------------------------------------------------------------------------------
1 | # %%
2 | a = 3
3 | # a++
4 | # a += 1
5 | # a
6 | # a--
7 | # ++a
8 | # ++a
9 | -a
10 | +a
11 |
12 | not 0
13 | not 1
14 | not -2
15 | not False
16 | not not True
--------------------------------------------------------------------------------
/fundamentos/primeiros_exemplos.py:
--------------------------------------------------------------------------------
1 | # %%
2 | print('primeiro programa')
3 | 1 \
4 | + 2
5 |
6 | help(print)
7 |
8 | # %%
9 | 1 + 2 + 3
10 | 4 + 5 + 6
11 |
12 | # %%
13 | print(1 + 2 + 3)
14 | print(4 + 5 + 6)
15 |
--------------------------------------------------------------------------------
/fundamentos/tipo_string.py:
--------------------------------------------------------------------------------
1 | # %%
2 | dir(str)
3 | nome = 'Saulo Pedro'
4 | nome
5 | nome[0]
6 | # nome[0] = 'P'
7 |
8 | # 'marca d'água'
9 | "Dias D'Avila" == 'Dias D\'Avila'
10 | "Teste \" funciona!"
11 | texto = 'Texto entre apostrófos pode ter "aspas"'
12 | texto
13 |
14 | doc = """Texto com múltiplas
15 | ... linhas"""
16 | doc
17 | print('Texto com múltiplas\n\t... linhas')
18 | print(doc)
19 |
20 | doc2 = '''Também é possível
21 | ... com 3 aspas simples'''
22 | doc2
23 |
24 | # %%
25 | nome = 'Ana Paula'
26 | nome[0]
27 | nome[6]
28 | nome[-3]
29 | nome[4:]
30 | nome[-5:]
31 | nome[:3]
32 | nome[2:5]
33 |
34 | numeros = '1234567890'
35 | numeros
36 | numeros[::]
37 | numeros[::2]
38 | numeros[1::2]
39 | numeros[::-1]
40 | numeros[::-2]
41 |
42 | nome[::-1]
43 |
44 | # %%
45 | frase = 'Python é uma linguagem excelente'
46 | 'py' not in frase
47 | 'ing' in frase
48 | len(frase)
49 | frase.lower()
50 | frase
51 | frase = frase.upper()
52 | frase
53 |
54 | frase.split()
55 | frase.split('E')
56 |
57 | # dir(str)
58 | # help(str.center)
59 |
60 | # %%
61 | a = '123'
62 | b = ' de Oliveira 4'
63 | a + b
64 | a.__add__(b)
65 | str.__add__(a, b)
66 |
67 | len(a)
68 | a.__len__()
69 | '1' in a
70 | a.__contains__('1')
71 |
72 | dir(str)
73 |
--------------------------------------------------------------------------------
/fundamentos/tipos_basicos.py:
--------------------------------------------------------------------------------
1 | # %%
2 | print(True)
3 | print(False)
4 | print(1.2 + 1)
5 | print('Aqui eu falo na minha lingua!')
6 | print("Tb funciona.")
7 | print('Você é ' + 3 * 'muito ' + 'legal!')
8 | # print(3 + '3') -> ambiguidade
9 | print([1, 2, 3])
10 | print({'nome': 'Pedro', 'idade': 22})
11 | print(None)
--------------------------------------------------------------------------------
/fundamentos/tipos_numericos_1.py:
--------------------------------------------------------------------------------
1 | # %%
2 | dir(int)
3 | dir(float)
4 |
5 | a = 5
6 | b = 2.5
7 | a / b
8 | a + b
9 | a * b
10 |
11 | type(a)
12 | type(b)
13 | type(a - b)
14 |
15 | b.is_integer()
16 | 5.0.is_integer()
17 |
18 | dir(int)
19 | int.__add__(2, 3)
20 | 2 + 3
21 |
22 | (-2).__abs__()
23 | abs(-2)
24 |
25 | (-3.6).__abs__()
26 | dir(float)
27 | abs(-3.6)
28 |
--------------------------------------------------------------------------------
/fundamentos/tipos_numericos_2.py:
--------------------------------------------------------------------------------
1 | # %%
2 | import decimal
3 | from decimal import Decimal, getcontext
4 |
5 | # 1.1 + 2.2
6 | Decimal(1) / Decimal(7)
7 |
8 | getcontext().prec = 4
9 | Decimal(1) / Decimal(7)
10 | Decimal.max(Decimal(1), Decimal(7))
11 | dir(Decimal)
12 |
13 | 1.1 + 2.2
14 | getcontext().prec = 10
15 | Decimal(1.1) + Decimal(2.2)
16 |
17 | dir(decimal)
18 | dir()
19 |
--------------------------------------------------------------------------------
/fundamentos/tupla.py:
--------------------------------------------------------------------------------
1 | # %%
2 | tupla = tuple()
3 | tupla = ()
4 | type(tupla)
5 | dir(tupla)
6 | # help(tuple)
7 | type(tupla)
8 | tupla = ('um')
9 | type(tupla)
10 | tupla = ('um',)
11 | type(tupla)
12 | tupla[0]
13 | # tupla[0] = 'novo'
14 | cores = ('verde', 'amarelo', 'azul', 'branco')
15 | cores[0]
16 | cores[-1]
17 | cores[1:]
18 |
19 | cores.index('amarelo')
20 | cores.count('Azul')
21 | len(cores)
22 |
--------------------------------------------------------------------------------
/fundamentos/variaveis.py:
--------------------------------------------------------------------------------
1 | # %%
2 | a = 10
3 | b = 5.2
4 |
5 | print(a + b)
6 |
7 | a = 'Agora sou uma string!'
8 | print(a)
9 | a
10 | b
11 |
12 | # print(a + b)
--------------------------------------------------------------------------------
/fundamentos_projetos/__pycache__/area_circulo_v6.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cod3rcursos/curso-python/a572d15cb1c1816064095d82bc3e1a46176ee379/fundamentos_projetos/__pycache__/area_circulo_v6.cpython-37.pyc
--------------------------------------------------------------------------------
/fundamentos_projetos/__pycache__/area_circulo_v7.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cod3rcursos/curso-python/a572d15cb1c1816064095d82bc3e1a46176ee379/fundamentos_projetos/__pycache__/area_circulo_v7.cpython-37.pyc
--------------------------------------------------------------------------------
/fundamentos_projetos/__pycache__/area_circulo_v8.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cod3rcursos/curso-python/a572d15cb1c1816064095d82bc3e1a46176ee379/fundamentos_projetos/__pycache__/area_circulo_v8.cpython-37.pyc
--------------------------------------------------------------------------------
/fundamentos_projetos/__pycache__/area_circulo_v9.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cod3rcursos/curso-python/a572d15cb1c1816064095d82bc3e1a46176ee379/fundamentos_projetos/__pycache__/area_circulo_v9.cpython-37.pyc
--------------------------------------------------------------------------------
/fundamentos_projetos/area_circulo:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | pi = 3.14159
3 | raio = 15.3
4 | print('Área do círculo', pi * raio ** 2)
5 |
--------------------------------------------------------------------------------
/fundamentos_projetos/area_circulo_v1.py:
--------------------------------------------------------------------------------
1 | pi = 3.14159
2 | raio = 15.3
3 | print('Área do círculo', pi * raio ** 2)
4 |
--------------------------------------------------------------------------------
/fundamentos_projetos/area_circulo_v10.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | from math import pi
3 | import sys
4 |
5 |
6 | def circulo(raio):
7 | return pi * float(raio) ** 2
8 |
9 |
10 | if __name__ == '__main__':
11 | raio = sys.argv[1]
12 | area = circulo(raio)
13 | print('Área do círculo', area)
14 |
--------------------------------------------------------------------------------
/fundamentos_projetos/area_circulo_v11.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | from math import pi
3 | import sys
4 |
5 |
6 | def circulo(raio):
7 | return pi * float(raio) ** 2
8 |
9 |
10 | if __name__ == '__main__':
11 | if len(sys.argv) < 2:
12 | print("É necessário informar o raio do círculo.")
13 | print("Sintaxe: {} ".format(sys.argv[0][2:]))
14 | else:
15 | raio = sys.argv[1]
16 | area = circulo(raio)
17 | print('Área do círculo', area)
18 |
--------------------------------------------------------------------------------
/fundamentos_projetos/area_circulo_v12.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | from math import pi
3 | import sys
4 |
5 |
6 | def help():
7 | print("É necessário informar o raio do círculo.")
8 | print("Sintaxe: {} ".format(sys.argv[0][2:]))
9 |
10 |
11 | def circulo(raio):
12 | return pi * float(raio) ** 2
13 |
14 |
15 | if __name__ == '__main__':
16 | if len(sys.argv) < 2:
17 | help()
18 | else:
19 | raio = sys.argv[1]
20 | area = circulo(raio)
21 | print('Área do círculo', area)
22 |
--------------------------------------------------------------------------------
/fundamentos_projetos/area_circulo_v13.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | from math import pi
3 | import sys
4 | # import errno
5 |
6 |
7 | def help():
8 | print("É necessário informar o raio do círculo.")
9 | print("Sintaxe: {} ".format(sys.argv[0][2:]))
10 |
11 |
12 | def circulo(raio):
13 | return pi * float(raio) ** 2
14 |
15 |
16 | if __name__ == '__main__':
17 | if len(sys.argv) < 2:
18 | help()
19 | # sys.exit(errno.EPERM)
20 | else:
21 | raio = sys.argv[1]
22 | area = circulo(raio)
23 | print('Área do círculo', area)
24 |
--------------------------------------------------------------------------------
/fundamentos_projetos/area_circulo_v14.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | from math import pi
3 | import sys
4 | import errno
5 |
6 |
7 | def help():
8 | print("É necessário informar o raio do círculo.")
9 | print("Sintaxe: {} ".format(sys.argv[0][2:]))
10 |
11 |
12 | def circulo(raio):
13 | return pi * float(raio) ** 2
14 |
15 |
16 | if __name__ == '__main__':
17 | if len(sys.argv) < 2:
18 | help()
19 | sys.exit(errno.EPERM)
20 |
21 | if not sys.argv[1].isnumeric():
22 | help()
23 | print('O raio deve ser um valor númerico')
24 | sys.exit(errno.EINVAL)
25 |
26 | raio = sys.argv[1]
27 | area = circulo(raio)
28 | print('Área do círculo', area)
29 |
--------------------------------------------------------------------------------
/fundamentos_projetos/area_circulo_v15.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | from math import pi
3 | import sys
4 | import errno
5 |
6 |
7 | class TerminalColor:
8 | ERRO = '\033[91m'
9 | NORMAL = '\033[0m'
10 |
11 |
12 | def help():
13 | print("É necessário informar o raio do círculo.")
14 | print("Sintaxe: {} ".format(sys.argv[0][2:]))
15 |
16 |
17 | def circulo(raio):
18 | return pi * float(raio) ** 2
19 |
20 |
21 | if __name__ == '__main__':
22 | if len(sys.argv) < 2:
23 | help()
24 | sys.exit(errno.EPERM)
25 |
26 | if not sys.argv[1].isnumeric():
27 | help()
28 | print(TerminalColor.ERRO + 'O raio deve ser um valor númerico' +
29 | TerminalColor.NORMAL)
30 | sys.exit(errno.EINVAL)
31 |
32 | raio = sys.argv[1]
33 | area = circulo(raio)
34 | print('Área do círculo', area)
35 |
--------------------------------------------------------------------------------
/fundamentos_projetos/area_circulo_v2.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | pi = 3.14159
3 | raio = 15.3
4 | print('Área do círculo', pi * raio ** 2)
5 |
--------------------------------------------------------------------------------
/fundamentos_projetos/area_circulo_v3.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | pi = 3.14159
3 | raio = 15.3
4 | print('Área do círculo', pi * raio ** 2)
5 |
--------------------------------------------------------------------------------
/fundamentos_projetos/area_circulo_v4.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | # import math
3 | from math import pi
4 |
5 | # print(dir())
6 |
7 | raio = 15.3
8 | print('Área do círculo', pi * raio ** 2)
9 |
--------------------------------------------------------------------------------
/fundamentos_projetos/area_circulo_v5.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | from math import pi
3 |
4 | raio = input('Informe o raio: ')
5 | print('Área do círculo', pi * float(raio) ** 2)
6 |
--------------------------------------------------------------------------------
/fundamentos_projetos/area_circulo_v6.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | from math import pi
3 |
4 | raio = input('Informe o raio: ')
5 | print('Área do círculo', pi * float(raio) ** 2)
6 |
7 | print('Nome do módulo', __name__)
8 |
--------------------------------------------------------------------------------
/fundamentos_projetos/area_circulo_v7.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | from math import pi
3 |
4 | if __name__ == '__main__':
5 | raio = input('Informe o raio: ')
6 | print('Área do círculo', pi * float(raio) ** 2)
7 |
--------------------------------------------------------------------------------
/fundamentos_projetos/area_circulo_v8.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | from math import pi
3 |
4 |
5 | def circulo(raio):
6 | print('Área do círculo', pi * float(raio) ** 2)
7 |
8 |
9 | if __name__ == '__main__':
10 | raio = input('Informe o raio: ')
11 | circulo(raio)
12 |
--------------------------------------------------------------------------------
/fundamentos_projetos/area_circulo_v9.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | from math import pi
3 |
4 |
5 | def circulo(raio):
6 | return pi * float(raio) ** 2
7 |
8 |
9 | if __name__ == '__main__':
10 | raio = input('Informe o raio: ')
11 | area = circulo(raio)
12 | print('Área do círculo', area)
13 |
--------------------------------------------------------------------------------
/fundamentos_projetos/encoding_teste.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | print "你好,世界"
3 | print "Olá Mundo!"
--------------------------------------------------------------------------------
/fundamentos_projetos/nota_aluno.py:
--------------------------------------------------------------------------------
1 | nota = 2.8
2 |
3 | if nota >= 9:
4 | print("Quadro de Honra")
5 | elif nota >= 7:
6 | print("Aprovado")
7 | elif nota >= 5:
8 | print("Recuperação")
9 | elif nota >= 3:
10 | print("Recuperação + Trabalho")
11 | else:
12 | print("Reprovado")
13 |
--------------------------------------------------------------------------------
/list_comprehension/comprehension_v1.py:
--------------------------------------------------------------------------------
1 | # [ expressão for item in list ]
2 | dobros = [i * 2 for i in range(10)]
3 | print(dobros)
4 |
5 | # Versão "normal"
6 | dobros = []
7 | for i in range(10):
8 | dobros.append(i * 2)
9 | print(dobros)
10 |
--------------------------------------------------------------------------------
/list_comprehension/comprehension_v2.py:
--------------------------------------------------------------------------------
1 | # [ expressão for item in list if condicional ]
2 | dobros_dos_pares = [i * 2 for i in range(10) if i % 2 == 0]
3 | print(dobros_dos_pares)
4 |
5 | # Versão "normal"
6 | dobros_dos_pares = []
7 | for i in range(10):
8 | if i % 2 == 0:
9 | dobros_dos_pares.append(i * 2)
10 | print(dobros_dos_pares)
11 |
--------------------------------------------------------------------------------
/list_comprehension/comprehension_v3.py:
--------------------------------------------------------------------------------
1 | generator = (i ** 2 for i in range(10) if i % 2 == 0)
2 | print(next(generator)) # Saída 0
3 | print(next(generator)) # Saída 4
4 | print(next(generator)) # Saída 16
5 | print(next(generator)) # Saída 36
6 | print(next(generator)) # Saída 64
7 | # print(next(generator)) # Erro!
8 |
--------------------------------------------------------------------------------
/list_comprehension/comprehension_v4.py:
--------------------------------------------------------------------------------
1 | generator = (i ** 2 for i in range(10) if i % 2 == 0)
2 |
3 | for numero in generator:
4 | print(numero)
5 |
--------------------------------------------------------------------------------
/list_comprehension/comprehension_v5.py:
--------------------------------------------------------------------------------
1 | dicionario = {i: i * 2 for i in range(10) if i % 2 == 0}
2 | print(dicionario)
3 |
4 | for numero, dobro in dicionario.items():
5 | print(f'{numero} x 2 = {dobro}')
6 |
--------------------------------------------------------------------------------
/list_comprehension/switch_3.py:
--------------------------------------------------------------------------------
1 | def get_tipo_dia(dia):
2 | dias = {
3 | (1, 7): 'Fim de semana',
4 | tuple(range(2, 7)): 'Dia de semana',
5 | }
6 | dia_escolhido = (tipo for numeros, tipo in dias.items() if dia in numeros)
7 | return next(dia_escolhido, '** dia inválido **')
8 |
9 |
10 | if __name__ == '__main__':
11 | for dia in range(0, 9):
12 | print(f'{dia}: {get_tipo_dia(dia)}')
13 |
--------------------------------------------------------------------------------
/manipulacao_arquivos/__pycache__/io_desafio_csv.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cod3rcursos/curso-python/a572d15cb1c1816064095d82bc3e1a46176ee379/manipulacao_arquivos/__pycache__/io_desafio_csv.cpython-37.pyc
--------------------------------------------------------------------------------
/manipulacao_arquivos/desafio-ibge.csv:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cod3rcursos/curso-python/a572d15cb1c1816064095d82bc3e1a46176ee379/manipulacao_arquivos/desafio-ibge.csv
--------------------------------------------------------------------------------
/manipulacao_arquivos/io_csv.py:
--------------------------------------------------------------------------------
1 | import csv
2 |
3 | with open('pessoas.csv') as entrada:
4 | for pessoa in csv.reader(entrada):
5 | print('Nome: {}, Idade: {}'.format(*pessoa))
6 |
--------------------------------------------------------------------------------
/manipulacao_arquivos/io_desafio_csv.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | import csv
3 | from urllib import request
4 |
5 |
6 | def read(url):
7 | with request.urlopen(url) as entrada:
8 | print('Baixando o CSV...')
9 | dados = entrada.read().decode('latin1')
10 | print('Download completo!')
11 | for cidade in csv.reader(dados.splitlines()):
12 | print(f'{cidade[8]}: {cidade[3]}')
13 |
14 |
15 | if __name__ == '__main__':
16 | read(r'http://files.cod3r.com.br/curso-python/desafio-ibge.csv')
17 |
--------------------------------------------------------------------------------
/manipulacao_arquivos/io_v1.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | arquivo = open('pessoas.csv')
3 | dados = arquivo.read()
4 | arquivo.close()
5 |
6 | for registro in dados.splitlines():
7 | print('Nome: {}, Idade: {}'.format(*registro.split(',')))
8 |
--------------------------------------------------------------------------------
/manipulacao_arquivos/io_v2.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | arquivo = open('pessoas.csv')
3 | for registro in arquivo:
4 | print('Nome: {} Idade: {}'.format(*registro.split(',')))
5 | arquivo.close()
6 |
--------------------------------------------------------------------------------
/manipulacao_arquivos/io_v3.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | arquivo = open('pessoas.csv')
3 |
4 | for registro in arquivo:
5 | print('Nome: {}, Idade: {}'.format(*registro.strip().split(',')))
6 |
7 | arquivo.close()
8 |
--------------------------------------------------------------------------------
/manipulacao_arquivos/io_v4.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 |
3 | try:
4 | arquivo = open('pessoas.csv')
5 |
6 | for registro in arquivo:
7 | print('Nome: {}, Idade: {}'.format(*registro.strip().split(',')))
8 | finally:
9 | arquivo.close()
10 |
11 | if arquivo.closed:
12 | print('Arquivo já foi fechado!')
13 |
--------------------------------------------------------------------------------
/manipulacao_arquivos/io_v5.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 |
3 | with open('pessoas.csv') as arquivo:
4 | for registro in arquivo:
5 | print('Nome: {}, Idade: {}'.format(*registro.strip().split(',')))
6 |
7 | if arquivo.closed:
8 | print('Arquivo já foi fechado!')
9 |
--------------------------------------------------------------------------------
/manipulacao_arquivos/io_v6.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 |
3 | with open('pessoas.csv') as arquivo:
4 | with open('pessoas.txt', 'w') as saida:
5 | for registro in arquivo:
6 | pessoa = registro.strip().split(',')
7 | print('Nome: {}, Idade: {}'.format(*pessoa), file=saida)
8 |
9 | if arquivo.closed:
10 | print('Arquivo já foi fechado!')
11 |
12 | if saida.closed:
13 | print('Arquivo de saída já foi fechado!')
14 |
--------------------------------------------------------------------------------
/manipulacao_arquivos/pessoas.csv:
--------------------------------------------------------------------------------
1 | Maria,45
2 | João,33
3 | Pedro,63
4 | Ana,21
5 | Bia,40
6 | Carlos,14
--------------------------------------------------------------------------------
/manipulacao_arquivos/pessoas.txt:
--------------------------------------------------------------------------------
1 | Nome: Maria, Idade: 45
2 | Nome: João, Idade: 33
3 | Nome: Pedro, Idade: 63
4 | Nome: Ana, Idade: 21
5 | Nome: Bia, Idade: 40
6 | Nome: Carlos, Idade: 14
7 |
--------------------------------------------------------------------------------
/notas/.ipynb_checkpoints/Fundamentos-checkpoint.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Primeiros Exemplos "
8 | ]
9 | },
10 | {
11 | "cell_type": "code",
12 | "execution_count": null,
13 | "metadata": {},
14 | "outputs": [],
15 | "source": [
16 | "print('primeiro programa')\n",
17 | "1 \\\n",
18 | " + 2\n",
19 | "\n",
20 | "help(print)"
21 | ]
22 | },
23 | {
24 | "cell_type": "code",
25 | "execution_count": null,
26 | "metadata": {},
27 | "outputs": [],
28 | "source": [
29 | "1 + 2 + 3\n",
30 | "4 + 5 + 6"
31 | ]
32 | },
33 | {
34 | "cell_type": "code",
35 | "execution_count": null,
36 | "metadata": {},
37 | "outputs": [],
38 | "source": [
39 | "print(1 + 2 + 3)\n",
40 | "print(4 + 5 + 6)"
41 | ]
42 | },
43 | {
44 | "cell_type": "markdown",
45 | "metadata": {},
46 | "source": [
47 | "# Tipos Básicos "
48 | ]
49 | },
50 | {
51 | "cell_type": "code",
52 | "execution_count": null,
53 | "metadata": {},
54 | "outputs": [],
55 | "source": [
56 | "print(True)\n",
57 | "print(False)\n",
58 | "print(1.2 + 1)\n",
59 | "print('Aqui eu falo na minha lingua!')\n",
60 | "print(\"Tb funciona.\")\n",
61 | "print('Você é ' + 3 * 'muito ' + 'legal!')\n",
62 | "# print(3 + '3') -> ambiguidade\n",
63 | "print([1, 2, 3])\n",
64 | "print({'nome': 'Pedro', 'idade': 22})\n",
65 | "print(None)"
66 | ]
67 | },
68 | {
69 | "cell_type": "markdown",
70 | "metadata": {},
71 | "source": [
72 | "# Variáveis "
73 | ]
74 | },
75 | {
76 | "cell_type": "code",
77 | "execution_count": null,
78 | "metadata": {},
79 | "outputs": [],
80 | "source": [
81 | "a = 10\n",
82 | "b = 5.2\n",
83 | "\n",
84 | "print(a + b)\n",
85 | "\n",
86 | "a = 'Agora sou uma string!'\n",
87 | "print(a)\n",
88 | "a\n",
89 | "b\n",
90 | "\n",
91 | "# print(a + b)"
92 | ]
93 | },
94 | {
95 | "cell_type": "markdown",
96 | "metadata": {},
97 | "source": [
98 | "# Comentários "
99 | ]
100 | },
101 | {
102 | "cell_type": "code",
103 | "execution_count": null,
104 | "metadata": {},
105 | "outputs": [],
106 | "source": [
107 | "# Minhas variáveis\n",
108 | "salario = 3450.45\n",
109 | "despesas = 2456.2\n",
110 | "\n",
111 | "\"\"\"\n",
112 | "A ideia é calcular o\n",
113 | "quando vai sobrar no\n",
114 | "final do mes!\n",
115 | "\"\"\"\n",
116 | "print(salario - despesas)\n",
117 | "\n",
118 | "# print('Fim')\n",
119 | "print('Fim de verdade') # comentário aqui tb vale!\n",
120 | "\n",
121 | "'''\n",
122 | "A ideia é calcular o\n",
123 | "quando vai sobrar no\n",
124 | "final do mes!\n",
125 | "'''\n",
126 | "print('Agora sim o fim de verdade')"
127 | ]
128 | },
129 | {
130 | "cell_type": "markdown",
131 | "metadata": {},
132 | "source": [
133 | "# Operadores Aritméticos "
134 | ]
135 | },
136 | {
137 | "cell_type": "code",
138 | "execution_count": null,
139 | "metadata": {},
140 | "outputs": [],
141 | "source": [
142 | "print(2 + 3)\n",
143 | "print(4 - 7)\n",
144 | "print(2 * 5.3)\n",
145 | "print(9.4 / 3)\n",
146 | "print(9.4 // 3)\n",
147 | "print(2 ** 8)\n",
148 | "print(10 % 3)\n",
149 | "\n",
150 | "a = 12\n",
151 | "b = a\n",
152 | "print(a + b)"
153 | ]
154 | },
155 | {
156 | "cell_type": "code",
157 | "execution_count": null,
158 | "metadata": {},
159 | "outputs": [],
160 | "source": [
161 | "# Minhas variáveis\n",
162 | "salario = 3450.45\n",
163 | "despesas = 2456.2\n",
164 | "\n",
165 | "# Resposta do desafio\n",
166 | "percentual_comprometido = despesas / salario * 100\n",
167 | "percentual_comprometido"
168 | ]
169 | },
170 | {
171 | "cell_type": "markdown",
172 | "metadata": {},
173 | "source": [
174 | "# Operadores Relacionais "
175 | ]
176 | },
177 | {
178 | "cell_type": "code",
179 | "execution_count": null,
180 | "metadata": {},
181 | "outputs": [],
182 | "source": [
183 | "3 > 4\n",
184 | "4 >= 3\n",
185 | "1 < 2\n",
186 | "3 <= 1\n",
187 | "3 != 2\n",
188 | "3 == 3\n",
189 | "2 == '2'"
190 | ]
191 | },
192 | {
193 | "cell_type": "markdown",
194 | "metadata": {},
195 | "source": [
196 | "# Operadores de Atribuição "
197 | ]
198 | },
199 | {
200 | "cell_type": "code",
201 | "execution_count": null,
202 | "metadata": {},
203 | "outputs": [],
204 | "source": [
205 | "a = 3\n",
206 | "a = a + 7\n",
207 | "print(a)\n",
208 | "\n",
209 | "# a = 5\n",
210 | "a += 5 # a = a + 5\n",
211 | "print(a)\n",
212 | "\n",
213 | "a -= 3\n",
214 | "print(a)\n",
215 | "\n",
216 | "a *= 2\n",
217 | "print(a)\n",
218 | "\n",
219 | "a /= 4\n",
220 | "print(a)\n",
221 | "\n",
222 | "a %= 4\n",
223 | "print(a)\n",
224 | "\n",
225 | "a **= 8\n",
226 | "print(a)\n",
227 | "\n",
228 | "a //= 256\n",
229 | "print(a)"
230 | ]
231 | },
232 | {
233 | "cell_type": "markdown",
234 | "metadata": {},
235 | "source": [
236 | "# Operadores Lógicos "
237 | ]
238 | },
239 | {
240 | "cell_type": "code",
241 | "execution_count": null,
242 | "metadata": {},
243 | "outputs": [],
244 | "source": [
245 | "True or False\n",
246 | "7 != 3 and 2 > 3\n",
247 | "\n",
248 | "# Tabela verdade do AND\n",
249 | "True and True\n",
250 | "True and False\n",
251 | "False and True\n",
252 | "False and False\n",
253 | "True and True and False and True and True and True\n",
254 | "\n",
255 | "# Tabela verdade do OR\n",
256 | "True or True\n",
257 | "True or False\n",
258 | "False or True\n",
259 | "False or False\n",
260 | "False or False or True or False or False or False\n",
261 | "\n",
262 | "# Tabela verdade do XOR\n",
263 | "True != True\n",
264 | "True != False\n",
265 | "False != True\n",
266 | "False != False\n",
267 | "\n",
268 | "# Operador de Negação (unário)\n",
269 | "not True\n",
270 | "not False\n",
271 | "\n",
272 | "not 0\n",
273 | "not 1\n",
274 | "not not -1\n",
275 | "not not True\n",
276 | "\n",
277 | "# Cuidado!\n",
278 | "True & False\n",
279 | "False | True\n",
280 | "True ^ False\n",
281 | "\n",
282 | "# AND Bit-a-bit\n",
283 | "# 3 = 11\n",
284 | "# 2 = 10\n",
285 | "# _ = 10\n",
286 | "3 & 2\n",
287 | "\n",
288 | "# OR Bit-a-bit\n",
289 | "# 3 = 11\n",
290 | "# 2 = 10\n",
291 | "# _ = 11\n",
292 | "3 | 2\n",
293 | "\n",
294 | "# XOR Bit-a-bit\n",
295 | "# 3 = 11\n",
296 | "# 2 = 10\n",
297 | "# _ = 01\n",
298 | "3 ^ 2\n",
299 | "\n",
300 | "# Um pouco de realidade\n",
301 | "saldo = 1000\n",
302 | "salario = 4000\n",
303 | "despesas = 3900\n",
304 | "\n",
305 | "saldo_positivo = saldo > 0\n",
306 | "despesas_controladas = salario - despesas >= 0.2 * salario\n",
307 | "\n",
308 | "meta = saldo_positivo and despesas_controladas\n",
309 | "meta"
310 | ]
311 | },
312 | {
313 | "cell_type": "code",
314 | "execution_count": null,
315 | "metadata": {},
316 | "outputs": [],
317 | "source": [
318 | "# Desafio Operadores Lógicos\n",
319 | "\n",
320 | "# Os Trabalhos\n",
321 | "trabalho_terca = False\n",
322 | "trabalho_quinta = False\n",
323 | "\n",
324 | "\"\"\"\n",
325 | "- Confirmando os 2: TV 50' + Sorvete\n",
326 | "- Confirmando apenas 1: TV 32' + Sorvete\n",
327 | "- Nenhum confirmado: Fica em casa\n",
328 | "\"\"\"\n",
329 | "tv_50 = trabalho_terca and trabalho_quinta\n",
330 | "sorvete = trabalho_terca or trabalho_quinta\n",
331 | "tv_32 = trabalho_terca != trabalho_quinta #xor\n",
332 | "mais_saudavel = not sorvete\n",
333 | "\n",
334 | "print(\"Tv50={} Tv32={} Sorvete={} Saudável={}\"\n",
335 | " .format(tv_50, tv_32, sorvete, mais_saudavel))\n",
336 | "\n",
337 | "# \"{}, {} = {}\".format(1, False, 'resultado')"
338 | ]
339 | },
340 | {
341 | "cell_type": "markdown",
342 | "metadata": {},
343 | "source": [
344 | "# Operadores Unários "
345 | ]
346 | },
347 | {
348 | "cell_type": "code",
349 | "execution_count": null,
350 | "metadata": {},
351 | "outputs": [],
352 | "source": [
353 | "a = 3\n",
354 | "# a++\n",
355 | "# a += 1\n",
356 | "# a\n",
357 | "# a--\n",
358 | "++a\n",
359 | "++a\n",
360 | "-a\n",
361 | "+a\n",
362 | "\n",
363 | "not 0\n",
364 | "not 1\n",
365 | "not -2\n",
366 | "not False\n",
367 | "not not True"
368 | ]
369 | },
370 | {
371 | "cell_type": "markdown",
372 | "metadata": {},
373 | "source": [
374 | "# Operadores Ternários "
375 | ]
376 | },
377 | {
378 | "cell_type": "code",
379 | "execution_count": null,
380 | "metadata": {},
381 | "outputs": [],
382 | "source": [
383 | "esta_chuvendo = False\n",
384 | "\n",
385 | "print('Hoje estou com as roupas ' + ('secas.', 'molhadas.')[esta_chuvendo])\n",
386 | "print('Hoje estou com as roupas ' + ('molhadas.' if esta_chuvendo else 'secas.'))"
387 | ]
388 | },
389 | {
390 | "cell_type": "markdown",
391 | "metadata": {},
392 | "source": [
393 | "# Mais Operadores "
394 | ]
395 | },
396 | {
397 | "cell_type": "code",
398 | "execution_count": null,
399 | "metadata": {},
400 | "outputs": [],
401 | "source": [
402 | "# Operador de Membro\n",
403 | "lista = [1, 2, 3, 'Ana', 'Carla']\n",
404 | "2 in lista\n",
405 | "'Ana' not in lista\n",
406 | "\n",
407 | "# Operador de Identidade\n",
408 | "x = 3\n",
409 | "y = x\n",
410 | "z = 3\n",
411 | "x is y\n",
412 | "y is z\n",
413 | "x is not z\n",
414 | "\n",
415 | "lista_a = [1, 2, 3]\n",
416 | "lista_b = lista_a\n",
417 | "lista_c = [1, 2, 3]\n",
418 | "\n",
419 | "lista_a is lista_b\n",
420 | "lista_b is lista_c\n",
421 | "lista_a is not lista_c"
422 | ]
423 | },
424 | {
425 | "cell_type": "markdown",
426 | "metadata": {},
427 | "source": [
428 | "# Builtins "
429 | ]
430 | },
431 | {
432 | "cell_type": "code",
433 | "execution_count": 4,
434 | "metadata": {},
435 | "outputs": [
436 | {
437 | "name": "stdout",
438 | "output_type": "stream",
439 | "text": [
440 | "3.3333333333333335\n"
441 | ]
442 | },
443 | {
444 | "data": {
445 | "text/plain": [
446 | "['In',\n",
447 | " 'Out',\n",
448 | " '_',\n",
449 | " '_1',\n",
450 | " '_2',\n",
451 | " '_3',\n",
452 | " '__',\n",
453 | " '___',\n",
454 | " '__builtin__',\n",
455 | " '__builtins__',\n",
456 | " '__doc__',\n",
457 | " '__loader__',\n",
458 | " '__name__',\n",
459 | " '__package__',\n",
460 | " '__spec__',\n",
461 | " '_dh',\n",
462 | " '_i',\n",
463 | " '_i1',\n",
464 | " '_i2',\n",
465 | " '_i3',\n",
466 | " '_i4',\n",
467 | " '_ih',\n",
468 | " '_ii',\n",
469 | " '_iii',\n",
470 | " '_oh',\n",
471 | " 'exit',\n",
472 | " 'get_ipython',\n",
473 | " 'nome',\n",
474 | " 'quit']"
475 | ]
476 | },
477 | "execution_count": 4,
478 | "metadata": {},
479 | "output_type": "execute_result"
480 | }
481 | ],
482 | "source": [
483 | "# type()\n",
484 | "type(1)\n",
485 | "__builtins__.type('Fala Galera!')\n",
486 | "__builtins__.print(10 / 3)\n",
487 | "\n",
488 | "# __builtins__.help(__builtins__.dir)\n",
489 | "\n",
490 | "# a = 7\n",
491 | "# import math\n",
492 | "# dir()\n",
493 | "# dir(__builtins__)\n",
494 | "\n",
495 | "\n",
496 | "nome = 'João da Silva'\n",
497 | "type(nome)\n",
498 | "__builtin__.len(nome)\n",
499 | "\n",
500 | "dir()"
501 | ]
502 | },
503 | {
504 | "cell_type": "markdown",
505 | "metadata": {},
506 | "source": [
507 | "# Conversão de Tipos "
508 | ]
509 | },
510 | {
511 | "cell_type": "code",
512 | "execution_count": 19,
513 | "metadata": {},
514 | "outputs": [
515 | {
516 | "name": "stdout",
517 | "output_type": "stream",
518 | "text": [
519 | "\n",
520 | "\n",
521 | "5\n",
522 | "23\n"
523 | ]
524 | },
525 | {
526 | "data": {
527 | "text/plain": [
528 | "str"
529 | ]
530 | },
531 | "execution_count": 19,
532 | "metadata": {},
533 | "output_type": "execute_result"
534 | }
535 | ],
536 | "source": [
537 | "2 + 3\n",
538 | "'2' + '3'\n",
539 | "# 2 + '3'\n",
540 | "# print(2 + '3')\n",
541 | "\n",
542 | "a = 2\n",
543 | "b = '3'\n",
544 | "\n",
545 | "print(type(a))\n",
546 | "print(type(b))\n",
547 | "\n",
548 | "print(a + int(b))\n",
549 | "print(str(a) + b)\n",
550 | "\n",
551 | "type(str(a))\n",
552 | "\n",
553 | "# print(2 + int('3.4'))"
554 | ]
555 | },
556 | {
557 | "cell_type": "markdown",
558 | "metadata": {},
559 | "source": [
560 | "# Coerção Automática "
561 | ]
562 | },
563 | {
564 | "cell_type": "code",
565 | "execution_count": 45,
566 | "metadata": {},
567 | "outputs": [
568 | {
569 | "data": {
570 | "text/plain": [
571 | "float"
572 | ]
573 | },
574 | "execution_count": 45,
575 | "metadata": {},
576 | "output_type": "execute_result"
577 | }
578 | ],
579 | "source": [
580 | "10 / 2\n",
581 | "type(10 / 2)\n",
582 | "10 / 3\n",
583 | "10 // 3\n",
584 | "type(10 // 3)\n",
585 | "10 // 3.3\n",
586 | "type(10 // 3.3)\n",
587 | "10 / 2.5\n",
588 | "2 + True\n",
589 | "2 + False\n",
590 | "type(1 + 2)\n",
591 | "type(1 + 2.5)"
592 | ]
593 | },
594 | {
595 | "cell_type": "markdown",
596 | "metadata": {},
597 | "source": [
598 | "# Tipos Numéricos "
599 | ]
600 | },
601 | {
602 | "cell_type": "code",
603 | "execution_count": 77,
604 | "metadata": {},
605 | "outputs": [
606 | {
607 | "data": {
608 | "text/plain": [
609 | "3.6"
610 | ]
611 | },
612 | "execution_count": 77,
613 | "metadata": {},
614 | "output_type": "execute_result"
615 | }
616 | ],
617 | "source": [
618 | "dir(int)\n",
619 | "dir(float)\n",
620 | "\n",
621 | "a = 5\n",
622 | "b = 2.5\n",
623 | "a / b\n",
624 | "a + b\n",
625 | "a * b\n",
626 | "\n",
627 | "type(a)\n",
628 | "type(b)\n",
629 | "type(a - b)\n",
630 | "\n",
631 | "b.is_integer()\n",
632 | "5.0.is_integer()\n",
633 | "\n",
634 | "dir(int)\n",
635 | "int.__add__(2, 3)\n",
636 | "2 + 3\n",
637 | "\n",
638 | "(-2).__abs__()\n",
639 | "abs(-2)\n",
640 | "\n",
641 | "(-3.6).__abs__()\n",
642 | "dir(float)\n",
643 | "abs(-3.6)"
644 | ]
645 | },
646 | {
647 | "cell_type": "code",
648 | "execution_count": 93,
649 | "metadata": {},
650 | "outputs": [
651 | {
652 | "data": {
653 | "text/plain": [
654 | "['Decimal',\n",
655 | " 'In',\n",
656 | " 'Out',\n",
657 | " '_',\n",
658 | " '_1',\n",
659 | " '_14',\n",
660 | " '_19',\n",
661 | " '_2',\n",
662 | " '_20',\n",
663 | " '_21',\n",
664 | " '_22',\n",
665 | " '_23',\n",
666 | " '_24',\n",
667 | " '_25',\n",
668 | " '_26',\n",
669 | " '_27',\n",
670 | " '_28',\n",
671 | " '_29',\n",
672 | " '_3',\n",
673 | " '_30',\n",
674 | " '_31',\n",
675 | " '_32',\n",
676 | " '_33',\n",
677 | " '_34',\n",
678 | " '_35',\n",
679 | " '_36',\n",
680 | " '_37',\n",
681 | " '_38',\n",
682 | " '_39',\n",
683 | " '_4',\n",
684 | " '_40',\n",
685 | " '_41',\n",
686 | " '_42',\n",
687 | " '_43',\n",
688 | " '_44',\n",
689 | " '_45',\n",
690 | " '_46',\n",
691 | " '_47',\n",
692 | " '_48',\n",
693 | " '_49',\n",
694 | " '_5',\n",
695 | " '_50',\n",
696 | " '_51',\n",
697 | " '_52',\n",
698 | " '_53',\n",
699 | " '_54',\n",
700 | " '_55',\n",
701 | " '_57',\n",
702 | " '_58',\n",
703 | " '_59',\n",
704 | " '_6',\n",
705 | " '_60',\n",
706 | " '_61',\n",
707 | " '_63',\n",
708 | " '_64',\n",
709 | " '_65',\n",
710 | " '_66',\n",
711 | " '_67',\n",
712 | " '_68',\n",
713 | " '_70',\n",
714 | " '_71',\n",
715 | " '_72',\n",
716 | " '_73',\n",
717 | " '_74',\n",
718 | " '_75',\n",
719 | " '_76',\n",
720 | " '_77',\n",
721 | " '_78',\n",
722 | " '_79',\n",
723 | " '_80',\n",
724 | " '_81',\n",
725 | " '_83',\n",
726 | " '_84',\n",
727 | " '_85',\n",
728 | " '_86',\n",
729 | " '_87',\n",
730 | " '_88',\n",
731 | " '_89',\n",
732 | " '_90',\n",
733 | " '_92',\n",
734 | " '__',\n",
735 | " '___',\n",
736 | " '__builtin__',\n",
737 | " '__builtins__',\n",
738 | " '__doc__',\n",
739 | " '__loader__',\n",
740 | " '__name__',\n",
741 | " '__package__',\n",
742 | " '__spec__',\n",
743 | " '_dh',\n",
744 | " '_i',\n",
745 | " '_i1',\n",
746 | " '_i10',\n",
747 | " '_i11',\n",
748 | " '_i12',\n",
749 | " '_i13',\n",
750 | " '_i14',\n",
751 | " '_i15',\n",
752 | " '_i16',\n",
753 | " '_i17',\n",
754 | " '_i18',\n",
755 | " '_i19',\n",
756 | " '_i2',\n",
757 | " '_i20',\n",
758 | " '_i21',\n",
759 | " '_i22',\n",
760 | " '_i23',\n",
761 | " '_i24',\n",
762 | " '_i25',\n",
763 | " '_i26',\n",
764 | " '_i27',\n",
765 | " '_i28',\n",
766 | " '_i29',\n",
767 | " '_i3',\n",
768 | " '_i30',\n",
769 | " '_i31',\n",
770 | " '_i32',\n",
771 | " '_i33',\n",
772 | " '_i34',\n",
773 | " '_i35',\n",
774 | " '_i36',\n",
775 | " '_i37',\n",
776 | " '_i38',\n",
777 | " '_i39',\n",
778 | " '_i4',\n",
779 | " '_i40',\n",
780 | " '_i41',\n",
781 | " '_i42',\n",
782 | " '_i43',\n",
783 | " '_i44',\n",
784 | " '_i45',\n",
785 | " '_i46',\n",
786 | " '_i47',\n",
787 | " '_i48',\n",
788 | " '_i49',\n",
789 | " '_i5',\n",
790 | " '_i50',\n",
791 | " '_i51',\n",
792 | " '_i52',\n",
793 | " '_i53',\n",
794 | " '_i54',\n",
795 | " '_i55',\n",
796 | " '_i56',\n",
797 | " '_i57',\n",
798 | " '_i58',\n",
799 | " '_i59',\n",
800 | " '_i6',\n",
801 | " '_i60',\n",
802 | " '_i61',\n",
803 | " '_i62',\n",
804 | " '_i63',\n",
805 | " '_i64',\n",
806 | " '_i65',\n",
807 | " '_i66',\n",
808 | " '_i67',\n",
809 | " '_i68',\n",
810 | " '_i69',\n",
811 | " '_i7',\n",
812 | " '_i70',\n",
813 | " '_i71',\n",
814 | " '_i72',\n",
815 | " '_i73',\n",
816 | " '_i74',\n",
817 | " '_i75',\n",
818 | " '_i76',\n",
819 | " '_i77',\n",
820 | " '_i78',\n",
821 | " '_i79',\n",
822 | " '_i8',\n",
823 | " '_i80',\n",
824 | " '_i81',\n",
825 | " '_i82',\n",
826 | " '_i83',\n",
827 | " '_i84',\n",
828 | " '_i85',\n",
829 | " '_i86',\n",
830 | " '_i87',\n",
831 | " '_i88',\n",
832 | " '_i89',\n",
833 | " '_i9',\n",
834 | " '_i90',\n",
835 | " '_i91',\n",
836 | " '_i92',\n",
837 | " '_i93',\n",
838 | " '_ih',\n",
839 | " '_ii',\n",
840 | " '_iii',\n",
841 | " '_oh',\n",
842 | " 'a',\n",
843 | " 'b',\n",
844 | " 'decimal',\n",
845 | " 'exit',\n",
846 | " 'get_ipython',\n",
847 | " 'getcontext',\n",
848 | " 'nome',\n",
849 | " 'quit']"
850 | ]
851 | },
852 | "execution_count": 93,
853 | "metadata": {},
854 | "output_type": "execute_result"
855 | }
856 | ],
857 | "source": [
858 | "# 1.1 + 2.2\n",
859 | "from decimal import Decimal, getcontext\n",
860 | "Decimal(1) / Decimal(7)\n",
861 | "\n",
862 | "getcontext().prec = 4\n",
863 | "Decimal(1) / Decimal(7)\n",
864 | "Decimal.max(Decimal(1), Decimal(7))\n",
865 | "dir(Decimal)\n",
866 | "\n",
867 | "1.1 + 2.2\n",
868 | "getcontext().prec = 10\n",
869 | "Decimal(1.1) + Decimal(2.2)\n",
870 | "\n",
871 | "import decimal\n",
872 | "dir(decimal)\n",
873 | "dir()"
874 | ]
875 | },
876 | {
877 | "cell_type": "markdown",
878 | "metadata": {},
879 | "source": [
880 | "# Tipo String "
881 | ]
882 | },
883 | {
884 | "cell_type": "code",
885 | "execution_count": 115,
886 | "metadata": {},
887 | "outputs": [
888 | {
889 | "name": "stdout",
890 | "output_type": "stream",
891 | "text": [
892 | "Texto com múltiplas\n",
893 | "\t... linhas\n",
894 | "Texto com múltiplas\n",
895 | " ... linhas\n"
896 | ]
897 | },
898 | {
899 | "data": {
900 | "text/plain": [
901 | "'Também é possível\\n... com 3 aspas simples'"
902 | ]
903 | },
904 | "execution_count": 115,
905 | "metadata": {},
906 | "output_type": "execute_result"
907 | }
908 | ],
909 | "source": [
910 | "dir(str)\n",
911 | "nome = 'Saulo Pedro'\n",
912 | "nome\n",
913 | "nome[0]\n",
914 | "# nome[0] = 'P'\n",
915 | "\n",
916 | "# 'marca d'água'\n",
917 | "\"Dias D'Avila\" == 'Dias D\\'Avila'\n",
918 | "\"Teste \\\" funciona!\"\n",
919 | "texto = 'Texto entre apostrófos pode ter \"aspas\"'\n",
920 | "texto\n",
921 | "\n",
922 | "doc = \"\"\"Texto com múltiplas\n",
923 | " ... linhas\"\"\"\n",
924 | "doc\n",
925 | "print('Texto com múltiplas\\n\\t... linhas')\n",
926 | "print(doc)\n",
927 | "\n",
928 | "doc2 = '''Também é possível\n",
929 | "... com 3 aspas simples'''\n",
930 | "doc2"
931 | ]
932 | },
933 | {
934 | "cell_type": "code",
935 | "execution_count": 131,
936 | "metadata": {},
937 | "outputs": [
938 | {
939 | "data": {
940 | "text/plain": [
941 | "'aluaP anA'"
942 | ]
943 | },
944 | "execution_count": 131,
945 | "metadata": {},
946 | "output_type": "execute_result"
947 | }
948 | ],
949 | "source": [
950 | "nome = 'Ana Paula'\n",
951 | "nome[0]\n",
952 | "nome[6]\n",
953 | "nome[-3]\n",
954 | "nome[4:]\n",
955 | "nome[-5:]\n",
956 | "nome[:3]\n",
957 | "nome[2:5]\n",
958 | "\n",
959 | "numeros = '1234567890'\n",
960 | "numeros\n",
961 | "numeros[::]\n",
962 | "numeros[::2]\n",
963 | "numeros[1::2]\n",
964 | "numeros[::-1]\n",
965 | "numeros[::-2]\n",
966 | "\n",
967 | "nome[::-1]"
968 | ]
969 | },
970 | {
971 | "cell_type": "code",
972 | "execution_count": 156,
973 | "metadata": {},
974 | "outputs": [
975 | {
976 | "name": "stdout",
977 | "output_type": "stream",
978 | "text": [
979 | "Help on method_descriptor:\n",
980 | "\n",
981 | "center(self, width, fillchar=' ', /)\n",
982 | " Return a centered string of length width.\n",
983 | " \n",
984 | " Padding is done using the specified fill character (default is a space).\n",
985 | "\n"
986 | ]
987 | }
988 | ],
989 | "source": [
990 | "frase = 'Python é uma linguagem excelente'\n",
991 | "'py' not in frase\n",
992 | "'ing' in frase\n",
993 | "len(frase)\n",
994 | "frase.lower()\n",
995 | "frase\n",
996 | "frase = frase.upper()\n",
997 | "frase\n",
998 | "\n",
999 | "frase.split()\n",
1000 | "frase.split('E')\n",
1001 | "\n",
1002 | "# dir(str)\n",
1003 | "# help(str.center)"
1004 | ]
1005 | },
1006 | {
1007 | "cell_type": "code",
1008 | "execution_count": 165,
1009 | "metadata": {},
1010 | "outputs": [
1011 | {
1012 | "data": {
1013 | "text/plain": [
1014 | "['__add__',\n",
1015 | " '__class__',\n",
1016 | " '__contains__',\n",
1017 | " '__delattr__',\n",
1018 | " '__dir__',\n",
1019 | " '__doc__',\n",
1020 | " '__eq__',\n",
1021 | " '__format__',\n",
1022 | " '__ge__',\n",
1023 | " '__getattribute__',\n",
1024 | " '__getitem__',\n",
1025 | " '__getnewargs__',\n",
1026 | " '__gt__',\n",
1027 | " '__hash__',\n",
1028 | " '__init__',\n",
1029 | " '__init_subclass__',\n",
1030 | " '__iter__',\n",
1031 | " '__le__',\n",
1032 | " '__len__',\n",
1033 | " '__lt__',\n",
1034 | " '__mod__',\n",
1035 | " '__mul__',\n",
1036 | " '__ne__',\n",
1037 | " '__new__',\n",
1038 | " '__reduce__',\n",
1039 | " '__reduce_ex__',\n",
1040 | " '__repr__',\n",
1041 | " '__rmod__',\n",
1042 | " '__rmul__',\n",
1043 | " '__setattr__',\n",
1044 | " '__sizeof__',\n",
1045 | " '__str__',\n",
1046 | " '__subclasshook__',\n",
1047 | " 'capitalize',\n",
1048 | " 'casefold',\n",
1049 | " 'center',\n",
1050 | " 'count',\n",
1051 | " 'encode',\n",
1052 | " 'endswith',\n",
1053 | " 'expandtabs',\n",
1054 | " 'find',\n",
1055 | " 'format',\n",
1056 | " 'format_map',\n",
1057 | " 'index',\n",
1058 | " 'isalnum',\n",
1059 | " 'isalpha',\n",
1060 | " 'isascii',\n",
1061 | " 'isdecimal',\n",
1062 | " 'isdigit',\n",
1063 | " 'isidentifier',\n",
1064 | " 'islower',\n",
1065 | " 'isnumeric',\n",
1066 | " 'isprintable',\n",
1067 | " 'isspace',\n",
1068 | " 'istitle',\n",
1069 | " 'isupper',\n",
1070 | " 'join',\n",
1071 | " 'ljust',\n",
1072 | " 'lower',\n",
1073 | " 'lstrip',\n",
1074 | " 'maketrans',\n",
1075 | " 'partition',\n",
1076 | " 'replace',\n",
1077 | " 'rfind',\n",
1078 | " 'rindex',\n",
1079 | " 'rjust',\n",
1080 | " 'rpartition',\n",
1081 | " 'rsplit',\n",
1082 | " 'rstrip',\n",
1083 | " 'split',\n",
1084 | " 'splitlines',\n",
1085 | " 'startswith',\n",
1086 | " 'strip',\n",
1087 | " 'swapcase',\n",
1088 | " 'title',\n",
1089 | " 'translate',\n",
1090 | " 'upper',\n",
1091 | " 'zfill']"
1092 | ]
1093 | },
1094 | "execution_count": 165,
1095 | "metadata": {},
1096 | "output_type": "execute_result"
1097 | }
1098 | ],
1099 | "source": [
1100 | "a = '123'\n",
1101 | "b = ' de Oliveira 4'\n",
1102 | "a + b\n",
1103 | "a.__add__(b)\n",
1104 | "str.__add__(a, b)\n",
1105 | "\n",
1106 | "len(a)\n",
1107 | "a.__len__()\n",
1108 | "'1' in a\n",
1109 | "a.__contains__('1')\n",
1110 | "\n",
1111 | "dir(str)"
1112 | ]
1113 | },
1114 | {
1115 | "cell_type": "markdown",
1116 | "metadata": {},
1117 | "source": [
1118 | "# Lista "
1119 | ]
1120 | },
1121 | {
1122 | "cell_type": "code",
1123 | "execution_count": 199,
1124 | "metadata": {},
1125 | "outputs": [
1126 | {
1127 | "data": {
1128 | "text/plain": [
1129 | "['Bia', 'Ana', 1]"
1130 | ]
1131 | },
1132 | "execution_count": 199,
1133 | "metadata": {},
1134 | "output_type": "execute_result"
1135 | }
1136 | ],
1137 | "source": [
1138 | "lista = []\n",
1139 | "type(lista)\n",
1140 | "dir(lista)\n",
1141 | "# help(list)\n",
1142 | "len(lista)\n",
1143 | "lista.append(1)\n",
1144 | "lista.append(5)\n",
1145 | "lista\n",
1146 | "len(lista)\n",
1147 | "\n",
1148 | "nova_lista = [1, 5, 'Ana', 'Bia']\n",
1149 | "nova_lista\n",
1150 | "nova_lista.remove(5)\n",
1151 | "nova_lista\n",
1152 | "nova_lista.reverse()\n",
1153 | "nova_lista"
1154 | ]
1155 | },
1156 | {
1157 | "cell_type": "code",
1158 | "execution_count": 210,
1159 | "metadata": {},
1160 | "outputs": [
1161 | {
1162 | "data": {
1163 | "text/plain": [
1164 | "1"
1165 | ]
1166 | },
1167 | "execution_count": 210,
1168 | "metadata": {},
1169 | "output_type": "execute_result"
1170 | }
1171 | ],
1172 | "source": [
1173 | "lista = [1, 5, 'Rebeca', 'Guilherme', 3.1415]\n",
1174 | "lista.index('Guilherme')\n",
1175 | "# lista.index(42)\n",
1176 | "lista[2]\n",
1177 | "1 in lista\n",
1178 | "'Rebeca' in lista\n",
1179 | "'Pedro' not in lista\n",
1180 | "lista[0]\n",
1181 | "lista[4]\n",
1182 | "# lista[5]\n",
1183 | "lista[-1]\n",
1184 | "lista[-5]"
1185 | ]
1186 | },
1187 | {
1188 | "cell_type": "code",
1189 | "execution_count": 220,
1190 | "metadata": {},
1191 | "outputs": [
1192 | {
1193 | "data": {
1194 | "text/plain": [
1195 | "['Ana']"
1196 | ]
1197 | },
1198 | "execution_count": 220,
1199 | "metadata": {},
1200 | "output_type": "execute_result"
1201 | }
1202 | ],
1203 | "source": [
1204 | "lista = ['Ana', 'Lia', 'Rui', 'Paulo', 'Dani']\n",
1205 | "lista[1:3]\n",
1206 | "lista[1:-1]\n",
1207 | "lista[1:]\n",
1208 | "lista[:-1]\n",
1209 | "lista[:]\n",
1210 | "lista[::2]\n",
1211 | "lista[::-1]\n",
1212 | "del lista[2]\n",
1213 | "lista\n",
1214 | "del lista[1:]\n",
1215 | "lista"
1216 | ]
1217 | },
1218 | {
1219 | "cell_type": "markdown",
1220 | "metadata": {},
1221 | "source": [
1222 | "# Tupla "
1223 | ]
1224 | },
1225 | {
1226 | "cell_type": "code",
1227 | "execution_count": 301,
1228 | "metadata": {},
1229 | "outputs": [
1230 | {
1231 | "data": {
1232 | "text/plain": [
1233 | "4"
1234 | ]
1235 | },
1236 | "execution_count": 301,
1237 | "metadata": {},
1238 | "output_type": "execute_result"
1239 | }
1240 | ],
1241 | "source": [
1242 | "tupla = tuple()\n",
1243 | "tupla = ()\n",
1244 | "type(tupla)\n",
1245 | "dir(tupla)\n",
1246 | "# help(tuple)\n",
1247 | "type(tupla)\n",
1248 | "tupla = ('um')\n",
1249 | "type(tupla)\n",
1250 | "tupla = ('um',)\n",
1251 | "type(tupla)\n",
1252 | "tupla[0]\n",
1253 | "# tupla[0] = 'novo'\n",
1254 | "cores = ('verde', 'amarelo', 'azul', 'branco')\n",
1255 | "cores[0]\n",
1256 | "cores[-1]\n",
1257 | "cores[1:]\n",
1258 | "\n",
1259 | "cores.index('amarelo')\n",
1260 | "cores.count('Azul')\n",
1261 | "len(cores)"
1262 | ]
1263 | },
1264 | {
1265 | "cell_type": "markdown",
1266 | "metadata": {},
1267 | "source": [
1268 | "# Dicionário "
1269 | ]
1270 | },
1271 | {
1272 | "cell_type": "code",
1273 | "execution_count": 321,
1274 | "metadata": {},
1275 | "outputs": [
1276 | {
1277 | "data": {
1278 | "text/plain": [
1279 | "[]"
1280 | ]
1281 | },
1282 | "execution_count": 321,
1283 | "metadata": {},
1284 | "output_type": "execute_result"
1285 | }
1286 | ],
1287 | "source": [
1288 | "pessoa = {'nome': 'Prof(a). Ana', 'idade': 38, 'cursos': ['Inglês', 'Português']}\n",
1289 | "type(pessoa)\n",
1290 | "dir(dict)\n",
1291 | "len(pessoa)\n",
1292 | "\n",
1293 | "pessoa\n",
1294 | "pessoa['nome']\n",
1295 | "pessoa['idade']\n",
1296 | "pessoa['cursos']\n",
1297 | "pessoa['cursos'][1]\n",
1298 | "# pessoa['tags']\n",
1299 | "pessoa.keys()\n",
1300 | "pessoa.values()\n",
1301 | "pessoa.items()\n",
1302 | "pessoa.get('idade')\n",
1303 | "pessoa.get('tags')\n",
1304 | "pessoa.get('tags', [])"
1305 | ]
1306 | },
1307 | {
1308 | "cell_type": "code",
1309 | "execution_count": 1,
1310 | "metadata": {},
1311 | "outputs": [
1312 | {
1313 | "data": {
1314 | "text/plain": [
1315 | "{}"
1316 | ]
1317 | },
1318 | "execution_count": 1,
1319 | "metadata": {},
1320 | "output_type": "execute_result"
1321 | }
1322 | ],
1323 | "source": [
1324 | "pessoa = {'nome': 'Prof. Alberto', 'idade': 43, 'cursos': ['React', 'Python']}\n",
1325 | "pessoa['idade'] = 44\n",
1326 | "pessoa['cursos'].append('Angular')\n",
1327 | "pessoa\n",
1328 | "pessoa.pop('idade')\n",
1329 | "pessoa\n",
1330 | "pessoa.update({'idade': 40, 'Sexo': 'M'})\n",
1331 | "pessoa\n",
1332 | "del pessoa['cursos']\n",
1333 | "pessoa\n",
1334 | "pessoa.clear()\n",
1335 | "pessoa"
1336 | ]
1337 | },
1338 | {
1339 | "cell_type": "markdown",
1340 | "metadata": {},
1341 | "source": [
1342 | "# Conjunto "
1343 | ]
1344 | },
1345 | {
1346 | "cell_type": "code",
1347 | "execution_count": 53,
1348 | "metadata": {},
1349 | "outputs": [
1350 | {
1351 | "name": "stdout",
1352 | "output_type": "stream",
1353 | "text": [
1354 | "{'c', 'r', 'o', 'd', '3'}\n",
1355 | "True True\n"
1356 | ]
1357 | },
1358 | {
1359 | "data": {
1360 | "text/plain": [
1361 | "{1, 3}"
1362 | ]
1363 | },
1364 | "execution_count": 53,
1365 | "metadata": {},
1366 | "output_type": "execute_result"
1367 | }
1368 | ],
1369 | "source": [
1370 | "a = {1, 2, 3}\n",
1371 | "type(a)\n",
1372 | "# a[0]\n",
1373 | "a = set('coddddd3r')\n",
1374 | "print(a)\n",
1375 | "print('3' in a, 4 not in a)\n",
1376 | "{1, 2, 3} == {3, 2, 1, 3}\n",
1377 | "\n",
1378 | "# operacoes\n",
1379 | "c1 = {1, 2}\n",
1380 | "c2 = {2, 3}\n",
1381 | "c1.union(c2)\n",
1382 | "c1.intersection(c2)\n",
1383 | "c1.update(c2)\n",
1384 | "c1\n",
1385 | "c2 <= c1\n",
1386 | "c1 >= c2\n",
1387 | "\n",
1388 | "{1, 2, 3} - {2}\n",
1389 | "c1 - c2\n",
1390 | "c1 -= {2}\n",
1391 | "c1"
1392 | ]
1393 | },
1394 | {
1395 | "cell_type": "markdown",
1396 | "metadata": {},
1397 | "source": [
1398 | "# Interpolação "
1399 | ]
1400 | },
1401 | {
1402 | "cell_type": "code",
1403 | "execution_count": 84,
1404 | "metadata": {},
1405 | "outputs": [
1406 | {
1407 | "name": "stdout",
1408 | "output_type": "stream",
1409 | "text": [
1410 | "Nome: Ana Idade: 30\n",
1411 | "Nome: Ana Idade: 30\n",
1412 | "Nome: {nome} Idade: {idade}\n",
1413 | "Nome: Ana Idade: 30\n"
1414 | ]
1415 | }
1416 | ],
1417 | "source": [
1418 | "from string import Template\n",
1419 | "\n",
1420 | "nome, idade = 'Ana', 30\n",
1421 | "\n",
1422 | "print('Nome: %s Idade: %d' % (nome, idade)) # mais antiga\n",
1423 | "print('Nome: {0} Idade: {1}'.format(nome, idade)) # python < 3.6\n",
1424 | "print(f'Nome: {nome} Idade: {idade}') # python >= 3.6\n",
1425 | "\n",
1426 | "s = Template('Nome: $nome Idade: $idade')\n",
1427 | "print(s.substitute(nome=nome, idade=idade))"
1428 | ]
1429 | }
1430 | ],
1431 | "metadata": {
1432 | "kernelspec": {
1433 | "display_name": "Python 3",
1434 | "language": "python",
1435 | "name": "python3"
1436 | },
1437 | "language_info": {
1438 | "codemirror_mode": {
1439 | "name": "ipython",
1440 | "version": 3
1441 | },
1442 | "file_extension": ".py",
1443 | "mimetype": "text/x-python",
1444 | "name": "python",
1445 | "nbconvert_exporter": "python",
1446 | "pygments_lexer": "ipython3",
1447 | "version": "3.7.0"
1448 | }
1449 | },
1450 | "nbformat": 4,
1451 | "nbformat_minor": 2
1452 | }
1453 |
--------------------------------------------------------------------------------
/notas/.ipynb_checkpoints/Testando Jupyter-checkpoint.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 10,
6 | "metadata": {},
7 | "outputs": [
8 | {
9 | "data": {
10 | "text/plain": [
11 | "1"
12 | ]
13 | },
14 | "execution_count": 10,
15 | "metadata": {},
16 | "output_type": "execute_result"
17 | }
18 | ],
19 | "source": [
20 | "1 + 2 + 3\n",
21 | "3 // 2"
22 | ]
23 | },
24 | {
25 | "cell_type": "code",
26 | "execution_count": 8,
27 | "metadata": {},
28 | "outputs": [
29 | {
30 | "name": "stdout",
31 | "output_type": "stream",
32 | "text": [
33 | "256\n",
34 | "8\n"
35 | ]
36 | }
37 | ],
38 | "source": [
39 | "print(2 ** 8)\n",
40 | "print(3 + 5)"
41 | ]
42 | },
43 | {
44 | "cell_type": "code",
45 | "execution_count": 11,
46 | "metadata": {},
47 | "outputs": [
48 | {
49 | "name": "stdout",
50 | "output_type": "stream",
51 | "text": [
52 | "teste jupyter!\n"
53 | ]
54 | }
55 | ],
56 | "source": [
57 | "print('teste jupyter!')"
58 | ]
59 | },
60 | {
61 | "cell_type": "markdown",
62 | "metadata": {},
63 | "source": [
64 | "# Operadores"
65 | ]
66 | },
67 | {
68 | "cell_type": "code",
69 | "execution_count": 13,
70 | "metadata": {},
71 | "outputs": [
72 | {
73 | "data": {
74 | "text/plain": [
75 | "3"
76 | ]
77 | },
78 | "execution_count": 13,
79 | "metadata": {},
80 | "output_type": "execute_result"
81 | }
82 | ],
83 | "source": [
84 | "1 + 2"
85 | ]
86 | },
87 | {
88 | "cell_type": "code",
89 | "execution_count": 15,
90 | "metadata": {},
91 | "outputs": [
92 | {
93 | "data": {
94 | "text/plain": [
95 | "8"
96 | ]
97 | },
98 | "execution_count": 15,
99 | "metadata": {},
100 | "output_type": "execute_result"
101 | }
102 | ],
103 | "source": [
104 | "2 * 4"
105 | ]
106 | },
107 | {
108 | "cell_type": "code",
109 | "execution_count": 16,
110 | "metadata": {},
111 | "outputs": [
112 | {
113 | "data": {
114 | "text/plain": [
115 | "0.6"
116 | ]
117 | },
118 | "execution_count": 16,
119 | "metadata": {},
120 | "output_type": "execute_result"
121 | }
122 | ],
123 | "source": [
124 | "3 / 5"
125 | ]
126 | },
127 | {
128 | "cell_type": "markdown",
129 | "metadata": {},
130 | "source": [
131 | "# Estruturas de Controle "
132 | ]
133 | },
134 | {
135 | "cell_type": "code",
136 | "execution_count": 20,
137 | "metadata": {},
138 | "outputs": [],
139 | "source": [
140 | "a = 2"
141 | ]
142 | },
143 | {
144 | "cell_type": "code",
145 | "execution_count": 21,
146 | "metadata": {},
147 | "outputs": [],
148 | "source": [
149 | "b = 3"
150 | ]
151 | },
152 | {
153 | "cell_type": "code",
154 | "execution_count": 22,
155 | "metadata": {},
156 | "outputs": [
157 | {
158 | "data": {
159 | "text/plain": [
160 | "5"
161 | ]
162 | },
163 | "execution_count": 22,
164 | "metadata": {},
165 | "output_type": "execute_result"
166 | }
167 | ],
168 | "source": [
169 | "a + b"
170 | ]
171 | },
172 | {
173 | "cell_type": "code",
174 | "execution_count": 23,
175 | "metadata": {},
176 | "outputs": [
177 | {
178 | "data": {
179 | "text/plain": [
180 | "125"
181 | ]
182 | },
183 | "execution_count": 23,
184 | "metadata": {},
185 | "output_type": "execute_result"
186 | }
187 | ],
188 | "source": [
189 | "_ ** 3"
190 | ]
191 | },
192 | {
193 | "cell_type": "code",
194 | "execution_count": 24,
195 | "metadata": {},
196 | "outputs": [
197 | {
198 | "data": {
199 | "text/plain": [
200 | "25.0"
201 | ]
202 | },
203 | "execution_count": 24,
204 | "metadata": {},
205 | "output_type": "execute_result"
206 | }
207 | ],
208 | "source": [
209 | "_ / 5"
210 | ]
211 | },
212 | {
213 | "cell_type": "code",
214 | "execution_count": null,
215 | "metadata": {},
216 | "outputs": [],
217 | "source": []
218 | }
219 | ],
220 | "metadata": {
221 | "kernelspec": {
222 | "display_name": "Python 3",
223 | "language": "python",
224 | "name": "python3"
225 | },
226 | "language_info": {
227 | "codemirror_mode": {
228 | "name": "ipython",
229 | "version": 3
230 | },
231 | "file_extension": ".py",
232 | "mimetype": "text/x-python",
233 | "name": "python",
234 | "nbconvert_exporter": "python",
235 | "pygments_lexer": "ipython3",
236 | "version": "3.7.0"
237 | }
238 | },
239 | "nbformat": 4,
240 | "nbformat_minor": 2
241 | }
242 |
--------------------------------------------------------------------------------
/notas/Fundamentos.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Primeiros Exemplos "
8 | ]
9 | },
10 | {
11 | "cell_type": "code",
12 | "execution_count": null,
13 | "metadata": {},
14 | "outputs": [],
15 | "source": [
16 | "print('primeiro programa')\n",
17 | "1 \\\n",
18 | " + 2\n",
19 | "\n",
20 | "help(print)"
21 | ]
22 | },
23 | {
24 | "cell_type": "code",
25 | "execution_count": null,
26 | "metadata": {},
27 | "outputs": [],
28 | "source": [
29 | "1 + 2 + 3\n",
30 | "4 + 5 + 6"
31 | ]
32 | },
33 | {
34 | "cell_type": "code",
35 | "execution_count": null,
36 | "metadata": {},
37 | "outputs": [],
38 | "source": [
39 | "print(1 + 2 + 3)\n",
40 | "print(4 + 5 + 6)"
41 | ]
42 | },
43 | {
44 | "cell_type": "markdown",
45 | "metadata": {},
46 | "source": [
47 | "# Tipos Básicos "
48 | ]
49 | },
50 | {
51 | "cell_type": "code",
52 | "execution_count": null,
53 | "metadata": {},
54 | "outputs": [],
55 | "source": [
56 | "print(True)\n",
57 | "print(False)\n",
58 | "print(1.2 + 1)\n",
59 | "print('Aqui eu falo na minha lingua!')\n",
60 | "print(\"Tb funciona.\")\n",
61 | "print('Você é ' + 3 * 'muito ' + 'legal!')\n",
62 | "# print(3 + '3') -> ambiguidade\n",
63 | "print([1, 2, 3])\n",
64 | "print({'nome': 'Pedro', 'idade': 22})\n",
65 | "print(None)"
66 | ]
67 | },
68 | {
69 | "cell_type": "markdown",
70 | "metadata": {},
71 | "source": [
72 | "# Variáveis "
73 | ]
74 | },
75 | {
76 | "cell_type": "code",
77 | "execution_count": null,
78 | "metadata": {},
79 | "outputs": [],
80 | "source": [
81 | "a = 10\n",
82 | "b = 5.2\n",
83 | "\n",
84 | "print(a + b)\n",
85 | "\n",
86 | "a = 'Agora sou uma string!'\n",
87 | "print(a)\n",
88 | "a\n",
89 | "b\n",
90 | "\n",
91 | "# print(a + b)"
92 | ]
93 | },
94 | {
95 | "cell_type": "markdown",
96 | "metadata": {},
97 | "source": [
98 | "# Comentários "
99 | ]
100 | },
101 | {
102 | "cell_type": "code",
103 | "execution_count": null,
104 | "metadata": {},
105 | "outputs": [],
106 | "source": [
107 | "# Minhas variáveis\n",
108 | "salario = 3450.45\n",
109 | "despesas = 2456.2\n",
110 | "\n",
111 | "\"\"\"\n",
112 | "A ideia é calcular o\n",
113 | "quando vai sobrar no\n",
114 | "final do mes!\n",
115 | "\"\"\"\n",
116 | "print(salario - despesas)\n",
117 | "\n",
118 | "# print('Fim')\n",
119 | "print('Fim de verdade') # comentário aqui tb vale!\n",
120 | "\n",
121 | "'''\n",
122 | "A ideia é calcular o\n",
123 | "quando vai sobrar no\n",
124 | "final do mes!\n",
125 | "'''\n",
126 | "print('Agora sim o fim de verdade')"
127 | ]
128 | },
129 | {
130 | "cell_type": "markdown",
131 | "metadata": {},
132 | "source": [
133 | "# Operadores Aritméticos "
134 | ]
135 | },
136 | {
137 | "cell_type": "code",
138 | "execution_count": null,
139 | "metadata": {},
140 | "outputs": [],
141 | "source": [
142 | "print(2 + 3)\n",
143 | "print(4 - 7)\n",
144 | "print(2 * 5.3)\n",
145 | "print(9.4 / 3)\n",
146 | "print(9.4 // 3)\n",
147 | "print(2 ** 8)\n",
148 | "print(10 % 3)\n",
149 | "\n",
150 | "a = 12\n",
151 | "b = a\n",
152 | "print(a + b)"
153 | ]
154 | },
155 | {
156 | "cell_type": "code",
157 | "execution_count": null,
158 | "metadata": {},
159 | "outputs": [],
160 | "source": [
161 | "# Minhas variáveis\n",
162 | "salario = 3450.45\n",
163 | "despesas = 2456.2\n",
164 | "\n",
165 | "# Resposta do desafio\n",
166 | "percentual_comprometido = despesas / salario * 100\n",
167 | "percentual_comprometido"
168 | ]
169 | },
170 | {
171 | "cell_type": "markdown",
172 | "metadata": {},
173 | "source": [
174 | "# Operadores Relacionais "
175 | ]
176 | },
177 | {
178 | "cell_type": "code",
179 | "execution_count": null,
180 | "metadata": {},
181 | "outputs": [],
182 | "source": [
183 | "3 > 4\n",
184 | "4 >= 3\n",
185 | "1 < 2\n",
186 | "3 <= 1\n",
187 | "3 != 2\n",
188 | "3 == 3\n",
189 | "2 == '2'"
190 | ]
191 | },
192 | {
193 | "cell_type": "markdown",
194 | "metadata": {},
195 | "source": [
196 | "# Operadores de Atribuição "
197 | ]
198 | },
199 | {
200 | "cell_type": "code",
201 | "execution_count": null,
202 | "metadata": {},
203 | "outputs": [],
204 | "source": [
205 | "a = 3\n",
206 | "a = a + 7\n",
207 | "print(a)\n",
208 | "\n",
209 | "# a = 5\n",
210 | "a += 5 # a = a + 5\n",
211 | "print(a)\n",
212 | "\n",
213 | "a -= 3\n",
214 | "print(a)\n",
215 | "\n",
216 | "a *= 2\n",
217 | "print(a)\n",
218 | "\n",
219 | "a /= 4\n",
220 | "print(a)\n",
221 | "\n",
222 | "a %= 4\n",
223 | "print(a)\n",
224 | "\n",
225 | "a **= 8\n",
226 | "print(a)\n",
227 | "\n",
228 | "a //= 256\n",
229 | "print(a)"
230 | ]
231 | },
232 | {
233 | "cell_type": "markdown",
234 | "metadata": {},
235 | "source": [
236 | "# Operadores Lógicos "
237 | ]
238 | },
239 | {
240 | "cell_type": "code",
241 | "execution_count": null,
242 | "metadata": {},
243 | "outputs": [],
244 | "source": [
245 | "True or False\n",
246 | "7 != 3 and 2 > 3\n",
247 | "\n",
248 | "# Tabela verdade do AND\n",
249 | "True and True\n",
250 | "True and False\n",
251 | "False and True\n",
252 | "False and False\n",
253 | "True and True and False and True and True and True\n",
254 | "\n",
255 | "# Tabela verdade do OR\n",
256 | "True or True\n",
257 | "True or False\n",
258 | "False or True\n",
259 | "False or False\n",
260 | "False or False or True or False or False or False\n",
261 | "\n",
262 | "# Tabela verdade do XOR\n",
263 | "True != True\n",
264 | "True != False\n",
265 | "False != True\n",
266 | "False != False\n",
267 | "\n",
268 | "# Operador de Negação (unário)\n",
269 | "not True\n",
270 | "not False\n",
271 | "\n",
272 | "not 0\n",
273 | "not 1\n",
274 | "not not -1\n",
275 | "not not True\n",
276 | "\n",
277 | "# Cuidado!\n",
278 | "True & False\n",
279 | "False | True\n",
280 | "True ^ False\n",
281 | "\n",
282 | "# AND Bit-a-bit\n",
283 | "# 3 = 11\n",
284 | "# 2 = 10\n",
285 | "# _ = 10\n",
286 | "3 & 2\n",
287 | "\n",
288 | "# OR Bit-a-bit\n",
289 | "# 3 = 11\n",
290 | "# 2 = 10\n",
291 | "# _ = 11\n",
292 | "3 | 2\n",
293 | "\n",
294 | "# XOR Bit-a-bit\n",
295 | "# 3 = 11\n",
296 | "# 2 = 10\n",
297 | "# _ = 01\n",
298 | "3 ^ 2\n",
299 | "\n",
300 | "# Um pouco de realidade\n",
301 | "saldo = 1000\n",
302 | "salario = 4000\n",
303 | "despesas = 3900\n",
304 | "\n",
305 | "saldo_positivo = saldo > 0\n",
306 | "despesas_controladas = salario - despesas >= 0.2 * salario\n",
307 | "\n",
308 | "meta = saldo_positivo and despesas_controladas\n",
309 | "meta"
310 | ]
311 | },
312 | {
313 | "cell_type": "code",
314 | "execution_count": null,
315 | "metadata": {},
316 | "outputs": [],
317 | "source": [
318 | "# Desafio Operadores Lógicos\n",
319 | "\n",
320 | "# Os Trabalhos\n",
321 | "trabalho_terca = False\n",
322 | "trabalho_quinta = False\n",
323 | "\n",
324 | "\"\"\"\n",
325 | "- Confirmando os 2: TV 50' + Sorvete\n",
326 | "- Confirmando apenas 1: TV 32' + Sorvete\n",
327 | "- Nenhum confirmado: Fica em casa\n",
328 | "\"\"\"\n",
329 | "tv_50 = trabalho_terca and trabalho_quinta\n",
330 | "sorvete = trabalho_terca or trabalho_quinta\n",
331 | "tv_32 = trabalho_terca != trabalho_quinta #xor\n",
332 | "mais_saudavel = not sorvete\n",
333 | "\n",
334 | "print(\"Tv50={} Tv32={} Sorvete={} Saudável={}\"\n",
335 | " .format(tv_50, tv_32, sorvete, mais_saudavel))\n",
336 | "\n",
337 | "# \"{}, {} = {}\".format(1, False, 'resultado')"
338 | ]
339 | },
340 | {
341 | "cell_type": "markdown",
342 | "metadata": {},
343 | "source": [
344 | "# Operadores Unários "
345 | ]
346 | },
347 | {
348 | "cell_type": "code",
349 | "execution_count": null,
350 | "metadata": {},
351 | "outputs": [],
352 | "source": [
353 | "a = 3\n",
354 | "# a++\n",
355 | "# a += 1\n",
356 | "# a\n",
357 | "# a--\n",
358 | "++a\n",
359 | "++a\n",
360 | "-a\n",
361 | "+a\n",
362 | "\n",
363 | "not 0\n",
364 | "not 1\n",
365 | "not -2\n",
366 | "not False\n",
367 | "not not True"
368 | ]
369 | },
370 | {
371 | "cell_type": "markdown",
372 | "metadata": {},
373 | "source": [
374 | "# Operadores Ternários "
375 | ]
376 | },
377 | {
378 | "cell_type": "code",
379 | "execution_count": null,
380 | "metadata": {},
381 | "outputs": [],
382 | "source": [
383 | "esta_chuvendo = False\n",
384 | "\n",
385 | "print('Hoje estou com as roupas ' + ('secas.', 'molhadas.')[esta_chuvendo])\n",
386 | "print('Hoje estou com as roupas ' + ('molhadas.' if esta_chuvendo else 'secas.'))"
387 | ]
388 | },
389 | {
390 | "cell_type": "markdown",
391 | "metadata": {},
392 | "source": [
393 | "# Mais Operadores "
394 | ]
395 | },
396 | {
397 | "cell_type": "code",
398 | "execution_count": null,
399 | "metadata": {},
400 | "outputs": [],
401 | "source": [
402 | "# Operador de Membro\n",
403 | "lista = [1, 2, 3, 'Ana', 'Carla']\n",
404 | "2 in lista\n",
405 | "'Ana' not in lista\n",
406 | "\n",
407 | "# Operador de Identidade\n",
408 | "x = 3\n",
409 | "y = x\n",
410 | "z = 3\n",
411 | "x is y\n",
412 | "y is z\n",
413 | "x is not z\n",
414 | "\n",
415 | "lista_a = [1, 2, 3]\n",
416 | "lista_b = lista_a\n",
417 | "lista_c = [1, 2, 3]\n",
418 | "\n",
419 | "lista_a is lista_b\n",
420 | "lista_b is lista_c\n",
421 | "lista_a is not lista_c"
422 | ]
423 | },
424 | {
425 | "cell_type": "markdown",
426 | "metadata": {},
427 | "source": [
428 | "# Builtins "
429 | ]
430 | },
431 | {
432 | "cell_type": "code",
433 | "execution_count": 4,
434 | "metadata": {},
435 | "outputs": [
436 | {
437 | "name": "stdout",
438 | "output_type": "stream",
439 | "text": [
440 | "3.3333333333333335\n"
441 | ]
442 | },
443 | {
444 | "data": {
445 | "text/plain": [
446 | "['In',\n",
447 | " 'Out',\n",
448 | " '_',\n",
449 | " '_1',\n",
450 | " '_2',\n",
451 | " '_3',\n",
452 | " '__',\n",
453 | " '___',\n",
454 | " '__builtin__',\n",
455 | " '__builtins__',\n",
456 | " '__doc__',\n",
457 | " '__loader__',\n",
458 | " '__name__',\n",
459 | " '__package__',\n",
460 | " '__spec__',\n",
461 | " '_dh',\n",
462 | " '_i',\n",
463 | " '_i1',\n",
464 | " '_i2',\n",
465 | " '_i3',\n",
466 | " '_i4',\n",
467 | " '_ih',\n",
468 | " '_ii',\n",
469 | " '_iii',\n",
470 | " '_oh',\n",
471 | " 'exit',\n",
472 | " 'get_ipython',\n",
473 | " 'nome',\n",
474 | " 'quit']"
475 | ]
476 | },
477 | "execution_count": 4,
478 | "metadata": {},
479 | "output_type": "execute_result"
480 | }
481 | ],
482 | "source": [
483 | "# type()\n",
484 | "type(1)\n",
485 | "__builtins__.type('Fala Galera!')\n",
486 | "__builtins__.print(10 / 3)\n",
487 | "\n",
488 | "# __builtins__.help(__builtins__.dir)\n",
489 | "\n",
490 | "# a = 7\n",
491 | "# import math\n",
492 | "# dir()\n",
493 | "# dir(__builtins__)\n",
494 | "\n",
495 | "\n",
496 | "nome = 'João da Silva'\n",
497 | "type(nome)\n",
498 | "__builtin__.len(nome)\n",
499 | "\n",
500 | "dir()"
501 | ]
502 | },
503 | {
504 | "cell_type": "markdown",
505 | "metadata": {},
506 | "source": [
507 | "# Conversão de Tipos "
508 | ]
509 | },
510 | {
511 | "cell_type": "code",
512 | "execution_count": 19,
513 | "metadata": {},
514 | "outputs": [
515 | {
516 | "name": "stdout",
517 | "output_type": "stream",
518 | "text": [
519 | "\n",
520 | "\n",
521 | "5\n",
522 | "23\n"
523 | ]
524 | },
525 | {
526 | "data": {
527 | "text/plain": [
528 | "str"
529 | ]
530 | },
531 | "execution_count": 19,
532 | "metadata": {},
533 | "output_type": "execute_result"
534 | }
535 | ],
536 | "source": [
537 | "2 + 3\n",
538 | "'2' + '3'\n",
539 | "# 2 + '3'\n",
540 | "# print(2 + '3')\n",
541 | "\n",
542 | "a = 2\n",
543 | "b = '3'\n",
544 | "\n",
545 | "print(type(a))\n",
546 | "print(type(b))\n",
547 | "\n",
548 | "print(a + int(b))\n",
549 | "print(str(a) + b)\n",
550 | "\n",
551 | "type(str(a))\n",
552 | "\n",
553 | "# print(2 + int('3.4'))"
554 | ]
555 | },
556 | {
557 | "cell_type": "markdown",
558 | "metadata": {},
559 | "source": [
560 | "# Coerção Automática "
561 | ]
562 | },
563 | {
564 | "cell_type": "code",
565 | "execution_count": 45,
566 | "metadata": {},
567 | "outputs": [
568 | {
569 | "data": {
570 | "text/plain": [
571 | "float"
572 | ]
573 | },
574 | "execution_count": 45,
575 | "metadata": {},
576 | "output_type": "execute_result"
577 | }
578 | ],
579 | "source": [
580 | "10 / 2\n",
581 | "type(10 / 2)\n",
582 | "10 / 3\n",
583 | "10 // 3\n",
584 | "type(10 // 3)\n",
585 | "10 // 3.3\n",
586 | "type(10 // 3.3)\n",
587 | "10 / 2.5\n",
588 | "2 + True\n",
589 | "2 + False\n",
590 | "type(1 + 2)\n",
591 | "type(1 + 2.5)"
592 | ]
593 | },
594 | {
595 | "cell_type": "markdown",
596 | "metadata": {},
597 | "source": [
598 | "# Tipos Numéricos "
599 | ]
600 | },
601 | {
602 | "cell_type": "code",
603 | "execution_count": 77,
604 | "metadata": {},
605 | "outputs": [
606 | {
607 | "data": {
608 | "text/plain": [
609 | "3.6"
610 | ]
611 | },
612 | "execution_count": 77,
613 | "metadata": {},
614 | "output_type": "execute_result"
615 | }
616 | ],
617 | "source": [
618 | "dir(int)\n",
619 | "dir(float)\n",
620 | "\n",
621 | "a = 5\n",
622 | "b = 2.5\n",
623 | "a / b\n",
624 | "a + b\n",
625 | "a * b\n",
626 | "\n",
627 | "type(a)\n",
628 | "type(b)\n",
629 | "type(a - b)\n",
630 | "\n",
631 | "b.is_integer()\n",
632 | "5.0.is_integer()\n",
633 | "\n",
634 | "dir(int)\n",
635 | "int.__add__(2, 3)\n",
636 | "2 + 3\n",
637 | "\n",
638 | "(-2).__abs__()\n",
639 | "abs(-2)\n",
640 | "\n",
641 | "(-3.6).__abs__()\n",
642 | "dir(float)\n",
643 | "abs(-3.6)"
644 | ]
645 | },
646 | {
647 | "cell_type": "code",
648 | "execution_count": 93,
649 | "metadata": {},
650 | "outputs": [
651 | {
652 | "data": {
653 | "text/plain": [
654 | "['Decimal',\n",
655 | " 'In',\n",
656 | " 'Out',\n",
657 | " '_',\n",
658 | " '_1',\n",
659 | " '_14',\n",
660 | " '_19',\n",
661 | " '_2',\n",
662 | " '_20',\n",
663 | " '_21',\n",
664 | " '_22',\n",
665 | " '_23',\n",
666 | " '_24',\n",
667 | " '_25',\n",
668 | " '_26',\n",
669 | " '_27',\n",
670 | " '_28',\n",
671 | " '_29',\n",
672 | " '_3',\n",
673 | " '_30',\n",
674 | " '_31',\n",
675 | " '_32',\n",
676 | " '_33',\n",
677 | " '_34',\n",
678 | " '_35',\n",
679 | " '_36',\n",
680 | " '_37',\n",
681 | " '_38',\n",
682 | " '_39',\n",
683 | " '_4',\n",
684 | " '_40',\n",
685 | " '_41',\n",
686 | " '_42',\n",
687 | " '_43',\n",
688 | " '_44',\n",
689 | " '_45',\n",
690 | " '_46',\n",
691 | " '_47',\n",
692 | " '_48',\n",
693 | " '_49',\n",
694 | " '_5',\n",
695 | " '_50',\n",
696 | " '_51',\n",
697 | " '_52',\n",
698 | " '_53',\n",
699 | " '_54',\n",
700 | " '_55',\n",
701 | " '_57',\n",
702 | " '_58',\n",
703 | " '_59',\n",
704 | " '_6',\n",
705 | " '_60',\n",
706 | " '_61',\n",
707 | " '_63',\n",
708 | " '_64',\n",
709 | " '_65',\n",
710 | " '_66',\n",
711 | " '_67',\n",
712 | " '_68',\n",
713 | " '_70',\n",
714 | " '_71',\n",
715 | " '_72',\n",
716 | " '_73',\n",
717 | " '_74',\n",
718 | " '_75',\n",
719 | " '_76',\n",
720 | " '_77',\n",
721 | " '_78',\n",
722 | " '_79',\n",
723 | " '_80',\n",
724 | " '_81',\n",
725 | " '_83',\n",
726 | " '_84',\n",
727 | " '_85',\n",
728 | " '_86',\n",
729 | " '_87',\n",
730 | " '_88',\n",
731 | " '_89',\n",
732 | " '_90',\n",
733 | " '_92',\n",
734 | " '__',\n",
735 | " '___',\n",
736 | " '__builtin__',\n",
737 | " '__builtins__',\n",
738 | " '__doc__',\n",
739 | " '__loader__',\n",
740 | " '__name__',\n",
741 | " '__package__',\n",
742 | " '__spec__',\n",
743 | " '_dh',\n",
744 | " '_i',\n",
745 | " '_i1',\n",
746 | " '_i10',\n",
747 | " '_i11',\n",
748 | " '_i12',\n",
749 | " '_i13',\n",
750 | " '_i14',\n",
751 | " '_i15',\n",
752 | " '_i16',\n",
753 | " '_i17',\n",
754 | " '_i18',\n",
755 | " '_i19',\n",
756 | " '_i2',\n",
757 | " '_i20',\n",
758 | " '_i21',\n",
759 | " '_i22',\n",
760 | " '_i23',\n",
761 | " '_i24',\n",
762 | " '_i25',\n",
763 | " '_i26',\n",
764 | " '_i27',\n",
765 | " '_i28',\n",
766 | " '_i29',\n",
767 | " '_i3',\n",
768 | " '_i30',\n",
769 | " '_i31',\n",
770 | " '_i32',\n",
771 | " '_i33',\n",
772 | " '_i34',\n",
773 | " '_i35',\n",
774 | " '_i36',\n",
775 | " '_i37',\n",
776 | " '_i38',\n",
777 | " '_i39',\n",
778 | " '_i4',\n",
779 | " '_i40',\n",
780 | " '_i41',\n",
781 | " '_i42',\n",
782 | " '_i43',\n",
783 | " '_i44',\n",
784 | " '_i45',\n",
785 | " '_i46',\n",
786 | " '_i47',\n",
787 | " '_i48',\n",
788 | " '_i49',\n",
789 | " '_i5',\n",
790 | " '_i50',\n",
791 | " '_i51',\n",
792 | " '_i52',\n",
793 | " '_i53',\n",
794 | " '_i54',\n",
795 | " '_i55',\n",
796 | " '_i56',\n",
797 | " '_i57',\n",
798 | " '_i58',\n",
799 | " '_i59',\n",
800 | " '_i6',\n",
801 | " '_i60',\n",
802 | " '_i61',\n",
803 | " '_i62',\n",
804 | " '_i63',\n",
805 | " '_i64',\n",
806 | " '_i65',\n",
807 | " '_i66',\n",
808 | " '_i67',\n",
809 | " '_i68',\n",
810 | " '_i69',\n",
811 | " '_i7',\n",
812 | " '_i70',\n",
813 | " '_i71',\n",
814 | " '_i72',\n",
815 | " '_i73',\n",
816 | " '_i74',\n",
817 | " '_i75',\n",
818 | " '_i76',\n",
819 | " '_i77',\n",
820 | " '_i78',\n",
821 | " '_i79',\n",
822 | " '_i8',\n",
823 | " '_i80',\n",
824 | " '_i81',\n",
825 | " '_i82',\n",
826 | " '_i83',\n",
827 | " '_i84',\n",
828 | " '_i85',\n",
829 | " '_i86',\n",
830 | " '_i87',\n",
831 | " '_i88',\n",
832 | " '_i89',\n",
833 | " '_i9',\n",
834 | " '_i90',\n",
835 | " '_i91',\n",
836 | " '_i92',\n",
837 | " '_i93',\n",
838 | " '_ih',\n",
839 | " '_ii',\n",
840 | " '_iii',\n",
841 | " '_oh',\n",
842 | " 'a',\n",
843 | " 'b',\n",
844 | " 'decimal',\n",
845 | " 'exit',\n",
846 | " 'get_ipython',\n",
847 | " 'getcontext',\n",
848 | " 'nome',\n",
849 | " 'quit']"
850 | ]
851 | },
852 | "execution_count": 93,
853 | "metadata": {},
854 | "output_type": "execute_result"
855 | }
856 | ],
857 | "source": [
858 | "# 1.1 + 2.2\n",
859 | "from decimal import Decimal, getcontext\n",
860 | "Decimal(1) / Decimal(7)\n",
861 | "\n",
862 | "getcontext().prec = 4\n",
863 | "Decimal(1) / Decimal(7)\n",
864 | "Decimal.max(Decimal(1), Decimal(7))\n",
865 | "dir(Decimal)\n",
866 | "\n",
867 | "1.1 + 2.2\n",
868 | "getcontext().prec = 10\n",
869 | "Decimal(1.1) + Decimal(2.2)\n",
870 | "\n",
871 | "import decimal\n",
872 | "dir(decimal)\n",
873 | "dir()"
874 | ]
875 | },
876 | {
877 | "cell_type": "markdown",
878 | "metadata": {},
879 | "source": [
880 | "# Tipo String "
881 | ]
882 | },
883 | {
884 | "cell_type": "code",
885 | "execution_count": 115,
886 | "metadata": {},
887 | "outputs": [
888 | {
889 | "name": "stdout",
890 | "output_type": "stream",
891 | "text": [
892 | "Texto com múltiplas\n",
893 | "\t... linhas\n",
894 | "Texto com múltiplas\n",
895 | " ... linhas\n"
896 | ]
897 | },
898 | {
899 | "data": {
900 | "text/plain": [
901 | "'Também é possível\\n... com 3 aspas simples'"
902 | ]
903 | },
904 | "execution_count": 115,
905 | "metadata": {},
906 | "output_type": "execute_result"
907 | }
908 | ],
909 | "source": [
910 | "dir(str)\n",
911 | "nome = 'Saulo Pedro'\n",
912 | "nome\n",
913 | "nome[0]\n",
914 | "# nome[0] = 'P'\n",
915 | "\n",
916 | "# 'marca d'água'\n",
917 | "\"Dias D'Avila\" == 'Dias D\\'Avila'\n",
918 | "\"Teste \\\" funciona!\"\n",
919 | "texto = 'Texto entre apostrófos pode ter \"aspas\"'\n",
920 | "texto\n",
921 | "\n",
922 | "doc = \"\"\"Texto com múltiplas\n",
923 | " ... linhas\"\"\"\n",
924 | "doc\n",
925 | "print('Texto com múltiplas\\n\\t... linhas')\n",
926 | "print(doc)\n",
927 | "\n",
928 | "doc2 = '''Também é possível\n",
929 | "... com 3 aspas simples'''\n",
930 | "doc2"
931 | ]
932 | },
933 | {
934 | "cell_type": "code",
935 | "execution_count": 131,
936 | "metadata": {},
937 | "outputs": [
938 | {
939 | "data": {
940 | "text/plain": [
941 | "'aluaP anA'"
942 | ]
943 | },
944 | "execution_count": 131,
945 | "metadata": {},
946 | "output_type": "execute_result"
947 | }
948 | ],
949 | "source": [
950 | "nome = 'Ana Paula'\n",
951 | "nome[0]\n",
952 | "nome[6]\n",
953 | "nome[-3]\n",
954 | "nome[4:]\n",
955 | "nome[-5:]\n",
956 | "nome[:3]\n",
957 | "nome[2:5]\n",
958 | "\n",
959 | "numeros = '1234567890'\n",
960 | "numeros\n",
961 | "numeros[::]\n",
962 | "numeros[::2]\n",
963 | "numeros[1::2]\n",
964 | "numeros[::-1]\n",
965 | "numeros[::-2]\n",
966 | "\n",
967 | "nome[::-1]"
968 | ]
969 | },
970 | {
971 | "cell_type": "code",
972 | "execution_count": 156,
973 | "metadata": {},
974 | "outputs": [
975 | {
976 | "name": "stdout",
977 | "output_type": "stream",
978 | "text": [
979 | "Help on method_descriptor:\n",
980 | "\n",
981 | "center(self, width, fillchar=' ', /)\n",
982 | " Return a centered string of length width.\n",
983 | " \n",
984 | " Padding is done using the specified fill character (default is a space).\n",
985 | "\n"
986 | ]
987 | }
988 | ],
989 | "source": [
990 | "frase = 'Python é uma linguagem excelente'\n",
991 | "'py' not in frase\n",
992 | "'ing' in frase\n",
993 | "len(frase)\n",
994 | "frase.lower()\n",
995 | "frase\n",
996 | "frase = frase.upper()\n",
997 | "frase\n",
998 | "\n",
999 | "frase.split()\n",
1000 | "frase.split('E')\n",
1001 | "\n",
1002 | "# dir(str)\n",
1003 | "# help(str.center)"
1004 | ]
1005 | },
1006 | {
1007 | "cell_type": "code",
1008 | "execution_count": 165,
1009 | "metadata": {},
1010 | "outputs": [
1011 | {
1012 | "data": {
1013 | "text/plain": [
1014 | "['__add__',\n",
1015 | " '__class__',\n",
1016 | " '__contains__',\n",
1017 | " '__delattr__',\n",
1018 | " '__dir__',\n",
1019 | " '__doc__',\n",
1020 | " '__eq__',\n",
1021 | " '__format__',\n",
1022 | " '__ge__',\n",
1023 | " '__getattribute__',\n",
1024 | " '__getitem__',\n",
1025 | " '__getnewargs__',\n",
1026 | " '__gt__',\n",
1027 | " '__hash__',\n",
1028 | " '__init__',\n",
1029 | " '__init_subclass__',\n",
1030 | " '__iter__',\n",
1031 | " '__le__',\n",
1032 | " '__len__',\n",
1033 | " '__lt__',\n",
1034 | " '__mod__',\n",
1035 | " '__mul__',\n",
1036 | " '__ne__',\n",
1037 | " '__new__',\n",
1038 | " '__reduce__',\n",
1039 | " '__reduce_ex__',\n",
1040 | " '__repr__',\n",
1041 | " '__rmod__',\n",
1042 | " '__rmul__',\n",
1043 | " '__setattr__',\n",
1044 | " '__sizeof__',\n",
1045 | " '__str__',\n",
1046 | " '__subclasshook__',\n",
1047 | " 'capitalize',\n",
1048 | " 'casefold',\n",
1049 | " 'center',\n",
1050 | " 'count',\n",
1051 | " 'encode',\n",
1052 | " 'endswith',\n",
1053 | " 'expandtabs',\n",
1054 | " 'find',\n",
1055 | " 'format',\n",
1056 | " 'format_map',\n",
1057 | " 'index',\n",
1058 | " 'isalnum',\n",
1059 | " 'isalpha',\n",
1060 | " 'isascii',\n",
1061 | " 'isdecimal',\n",
1062 | " 'isdigit',\n",
1063 | " 'isidentifier',\n",
1064 | " 'islower',\n",
1065 | " 'isnumeric',\n",
1066 | " 'isprintable',\n",
1067 | " 'isspace',\n",
1068 | " 'istitle',\n",
1069 | " 'isupper',\n",
1070 | " 'join',\n",
1071 | " 'ljust',\n",
1072 | " 'lower',\n",
1073 | " 'lstrip',\n",
1074 | " 'maketrans',\n",
1075 | " 'partition',\n",
1076 | " 'replace',\n",
1077 | " 'rfind',\n",
1078 | " 'rindex',\n",
1079 | " 'rjust',\n",
1080 | " 'rpartition',\n",
1081 | " 'rsplit',\n",
1082 | " 'rstrip',\n",
1083 | " 'split',\n",
1084 | " 'splitlines',\n",
1085 | " 'startswith',\n",
1086 | " 'strip',\n",
1087 | " 'swapcase',\n",
1088 | " 'title',\n",
1089 | " 'translate',\n",
1090 | " 'upper',\n",
1091 | " 'zfill']"
1092 | ]
1093 | },
1094 | "execution_count": 165,
1095 | "metadata": {},
1096 | "output_type": "execute_result"
1097 | }
1098 | ],
1099 | "source": [
1100 | "a = '123'\n",
1101 | "b = ' de Oliveira 4'\n",
1102 | "a + b\n",
1103 | "a.__add__(b)\n",
1104 | "str.__add__(a, b)\n",
1105 | "\n",
1106 | "len(a)\n",
1107 | "a.__len__()\n",
1108 | "'1' in a\n",
1109 | "a.__contains__('1')\n",
1110 | "\n",
1111 | "dir(str)"
1112 | ]
1113 | },
1114 | {
1115 | "cell_type": "markdown",
1116 | "metadata": {},
1117 | "source": [
1118 | "# Lista "
1119 | ]
1120 | },
1121 | {
1122 | "cell_type": "code",
1123 | "execution_count": 199,
1124 | "metadata": {},
1125 | "outputs": [
1126 | {
1127 | "data": {
1128 | "text/plain": [
1129 | "['Bia', 'Ana', 1]"
1130 | ]
1131 | },
1132 | "execution_count": 199,
1133 | "metadata": {},
1134 | "output_type": "execute_result"
1135 | }
1136 | ],
1137 | "source": [
1138 | "lista = []\n",
1139 | "type(lista)\n",
1140 | "dir(lista)\n",
1141 | "# help(list)\n",
1142 | "len(lista)\n",
1143 | "lista.append(1)\n",
1144 | "lista.append(5)\n",
1145 | "lista\n",
1146 | "len(lista)\n",
1147 | "\n",
1148 | "nova_lista = [1, 5, 'Ana', 'Bia']\n",
1149 | "nova_lista\n",
1150 | "nova_lista.remove(5)\n",
1151 | "nova_lista\n",
1152 | "nova_lista.reverse()\n",
1153 | "nova_lista"
1154 | ]
1155 | },
1156 | {
1157 | "cell_type": "code",
1158 | "execution_count": 210,
1159 | "metadata": {},
1160 | "outputs": [
1161 | {
1162 | "data": {
1163 | "text/plain": [
1164 | "1"
1165 | ]
1166 | },
1167 | "execution_count": 210,
1168 | "metadata": {},
1169 | "output_type": "execute_result"
1170 | }
1171 | ],
1172 | "source": [
1173 | "lista = [1, 5, 'Rebeca', 'Guilherme', 3.1415]\n",
1174 | "lista.index('Guilherme')\n",
1175 | "# lista.index(42)\n",
1176 | "lista[2]\n",
1177 | "1 in lista\n",
1178 | "'Rebeca' in lista\n",
1179 | "'Pedro' not in lista\n",
1180 | "lista[0]\n",
1181 | "lista[4]\n",
1182 | "# lista[5]\n",
1183 | "lista[-1]\n",
1184 | "lista[-5]"
1185 | ]
1186 | },
1187 | {
1188 | "cell_type": "code",
1189 | "execution_count": 220,
1190 | "metadata": {},
1191 | "outputs": [
1192 | {
1193 | "data": {
1194 | "text/plain": [
1195 | "['Ana']"
1196 | ]
1197 | },
1198 | "execution_count": 220,
1199 | "metadata": {},
1200 | "output_type": "execute_result"
1201 | }
1202 | ],
1203 | "source": [
1204 | "lista = ['Ana', 'Lia', 'Rui', 'Paulo', 'Dani']\n",
1205 | "lista[1:3]\n",
1206 | "lista[1:-1]\n",
1207 | "lista[1:]\n",
1208 | "lista[:-1]\n",
1209 | "lista[:]\n",
1210 | "lista[::2]\n",
1211 | "lista[::-1]\n",
1212 | "del lista[2]\n",
1213 | "lista\n",
1214 | "del lista[1:]\n",
1215 | "lista"
1216 | ]
1217 | },
1218 | {
1219 | "cell_type": "markdown",
1220 | "metadata": {},
1221 | "source": [
1222 | "# Tupla "
1223 | ]
1224 | },
1225 | {
1226 | "cell_type": "code",
1227 | "execution_count": 301,
1228 | "metadata": {},
1229 | "outputs": [
1230 | {
1231 | "data": {
1232 | "text/plain": [
1233 | "4"
1234 | ]
1235 | },
1236 | "execution_count": 301,
1237 | "metadata": {},
1238 | "output_type": "execute_result"
1239 | }
1240 | ],
1241 | "source": [
1242 | "tupla = tuple()\n",
1243 | "tupla = ()\n",
1244 | "type(tupla)\n",
1245 | "dir(tupla)\n",
1246 | "# help(tuple)\n",
1247 | "type(tupla)\n",
1248 | "tupla = ('um')\n",
1249 | "type(tupla)\n",
1250 | "tupla = ('um',)\n",
1251 | "type(tupla)\n",
1252 | "tupla[0]\n",
1253 | "# tupla[0] = 'novo'\n",
1254 | "cores = ('verde', 'amarelo', 'azul', 'branco')\n",
1255 | "cores[0]\n",
1256 | "cores[-1]\n",
1257 | "cores[1:]\n",
1258 | "\n",
1259 | "cores.index('amarelo')\n",
1260 | "cores.count('Azul')\n",
1261 | "len(cores)"
1262 | ]
1263 | },
1264 | {
1265 | "cell_type": "markdown",
1266 | "metadata": {},
1267 | "source": [
1268 | "# Dicionário "
1269 | ]
1270 | },
1271 | {
1272 | "cell_type": "code",
1273 | "execution_count": 321,
1274 | "metadata": {},
1275 | "outputs": [
1276 | {
1277 | "data": {
1278 | "text/plain": [
1279 | "[]"
1280 | ]
1281 | },
1282 | "execution_count": 321,
1283 | "metadata": {},
1284 | "output_type": "execute_result"
1285 | }
1286 | ],
1287 | "source": [
1288 | "pessoa = {'nome': 'Prof(a). Ana', 'idade': 38, 'cursos': ['Inglês', 'Português']}\n",
1289 | "type(pessoa)\n",
1290 | "dir(dict)\n",
1291 | "len(pessoa)\n",
1292 | "\n",
1293 | "pessoa\n",
1294 | "pessoa['nome']\n",
1295 | "pessoa['idade']\n",
1296 | "pessoa['cursos']\n",
1297 | "pessoa['cursos'][1]\n",
1298 | "# pessoa['tags']\n",
1299 | "pessoa.keys()\n",
1300 | "pessoa.values()\n",
1301 | "pessoa.items()\n",
1302 | "pessoa.get('idade')\n",
1303 | "pessoa.get('tags')\n",
1304 | "pessoa.get('tags', [])"
1305 | ]
1306 | },
1307 | {
1308 | "cell_type": "code",
1309 | "execution_count": 1,
1310 | "metadata": {},
1311 | "outputs": [
1312 | {
1313 | "data": {
1314 | "text/plain": [
1315 | "{}"
1316 | ]
1317 | },
1318 | "execution_count": 1,
1319 | "metadata": {},
1320 | "output_type": "execute_result"
1321 | }
1322 | ],
1323 | "source": [
1324 | "pessoa = {'nome': 'Prof. Alberto', 'idade': 43, 'cursos': ['React', 'Python']}\n",
1325 | "pessoa['idade'] = 44\n",
1326 | "pessoa['cursos'].append('Angular')\n",
1327 | "pessoa\n",
1328 | "pessoa.pop('idade')\n",
1329 | "pessoa\n",
1330 | "pessoa.update({'idade': 40, 'Sexo': 'M'})\n",
1331 | "pessoa\n",
1332 | "del pessoa['cursos']\n",
1333 | "pessoa\n",
1334 | "pessoa.clear()\n",
1335 | "pessoa"
1336 | ]
1337 | },
1338 | {
1339 | "cell_type": "markdown",
1340 | "metadata": {},
1341 | "source": [
1342 | "# Conjunto "
1343 | ]
1344 | },
1345 | {
1346 | "cell_type": "code",
1347 | "execution_count": 53,
1348 | "metadata": {},
1349 | "outputs": [
1350 | {
1351 | "name": "stdout",
1352 | "output_type": "stream",
1353 | "text": [
1354 | "{'c', 'r', 'o', 'd', '3'}\n",
1355 | "True True\n"
1356 | ]
1357 | },
1358 | {
1359 | "data": {
1360 | "text/plain": [
1361 | "{1, 3}"
1362 | ]
1363 | },
1364 | "execution_count": 53,
1365 | "metadata": {},
1366 | "output_type": "execute_result"
1367 | }
1368 | ],
1369 | "source": [
1370 | "a = {1, 2, 3}\n",
1371 | "type(a)\n",
1372 | "# a[0]\n",
1373 | "a = set('coddddd3r')\n",
1374 | "print(a)\n",
1375 | "print('3' in a, 4 not in a)\n",
1376 | "{1, 2, 3} == {3, 2, 1, 3}\n",
1377 | "\n",
1378 | "# operacoes\n",
1379 | "c1 = {1, 2}\n",
1380 | "c2 = {2, 3}\n",
1381 | "c1.union(c2)\n",
1382 | "c1.intersection(c2)\n",
1383 | "c1.update(c2)\n",
1384 | "c1\n",
1385 | "c2 <= c1\n",
1386 | "c1 >= c2\n",
1387 | "\n",
1388 | "{1, 2, 3} - {2}\n",
1389 | "c1 - c2\n",
1390 | "c1 -= {2}\n",
1391 | "c1"
1392 | ]
1393 | },
1394 | {
1395 | "cell_type": "markdown",
1396 | "metadata": {},
1397 | "source": [
1398 | "# Interpolação "
1399 | ]
1400 | },
1401 | {
1402 | "cell_type": "code",
1403 | "execution_count": 84,
1404 | "metadata": {},
1405 | "outputs": [
1406 | {
1407 | "name": "stdout",
1408 | "output_type": "stream",
1409 | "text": [
1410 | "Nome: Ana Idade: 30\n",
1411 | "Nome: Ana Idade: 30\n",
1412 | "Nome: {nome} Idade: {idade}\n",
1413 | "Nome: Ana Idade: 30\n"
1414 | ]
1415 | }
1416 | ],
1417 | "source": [
1418 | "from string import Template\n",
1419 | "\n",
1420 | "nome, idade = 'Ana', 30\n",
1421 | "\n",
1422 | "print('Nome: %s Idade: %d' % (nome, idade)) # mais antiga\n",
1423 | "print('Nome: {0} Idade: {1}'.format(nome, idade)) # python < 3.6\n",
1424 | "print(f'Nome: {nome} Idade: {idade}') # python >= 3.6\n",
1425 | "\n",
1426 | "s = Template('Nome: $nome Idade: $idade')\n",
1427 | "print(s.substitute(nome=nome, idade=idade))"
1428 | ]
1429 | }
1430 | ],
1431 | "metadata": {
1432 | "kernelspec": {
1433 | "display_name": "Python 3",
1434 | "language": "python",
1435 | "name": "python3"
1436 | },
1437 | "language_info": {
1438 | "codemirror_mode": {
1439 | "name": "ipython",
1440 | "version": 3
1441 | },
1442 | "file_extension": ".py",
1443 | "mimetype": "text/x-python",
1444 | "name": "python",
1445 | "nbconvert_exporter": "python",
1446 | "pygments_lexer": "ipython3",
1447 | "version": "3.7.0"
1448 | }
1449 | },
1450 | "nbformat": 4,
1451 | "nbformat_minor": 2
1452 | }
1453 |
--------------------------------------------------------------------------------
/notas/Testando Jupyter.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 10,
6 | "metadata": {},
7 | "outputs": [
8 | {
9 | "data": {
10 | "text/plain": [
11 | "1"
12 | ]
13 | },
14 | "execution_count": 10,
15 | "metadata": {},
16 | "output_type": "execute_result"
17 | }
18 | ],
19 | "source": [
20 | "1 + 2 + 3\n",
21 | "3 // 2"
22 | ]
23 | },
24 | {
25 | "cell_type": "code",
26 | "execution_count": 8,
27 | "metadata": {},
28 | "outputs": [
29 | {
30 | "name": "stdout",
31 | "output_type": "stream",
32 | "text": [
33 | "256\n",
34 | "8\n"
35 | ]
36 | }
37 | ],
38 | "source": [
39 | "print(2 ** 8)\n",
40 | "print(3 + 5)"
41 | ]
42 | },
43 | {
44 | "cell_type": "code",
45 | "execution_count": 11,
46 | "metadata": {},
47 | "outputs": [
48 | {
49 | "name": "stdout",
50 | "output_type": "stream",
51 | "text": [
52 | "teste jupyter!\n"
53 | ]
54 | }
55 | ],
56 | "source": [
57 | "print('teste jupyter!')"
58 | ]
59 | },
60 | {
61 | "cell_type": "markdown",
62 | "metadata": {},
63 | "source": [
64 | "# Operadores"
65 | ]
66 | },
67 | {
68 | "cell_type": "code",
69 | "execution_count": 13,
70 | "metadata": {},
71 | "outputs": [
72 | {
73 | "data": {
74 | "text/plain": [
75 | "3"
76 | ]
77 | },
78 | "execution_count": 13,
79 | "metadata": {},
80 | "output_type": "execute_result"
81 | }
82 | ],
83 | "source": [
84 | "1 + 2"
85 | ]
86 | },
87 | {
88 | "cell_type": "code",
89 | "execution_count": 15,
90 | "metadata": {},
91 | "outputs": [
92 | {
93 | "data": {
94 | "text/plain": [
95 | "8"
96 | ]
97 | },
98 | "execution_count": 15,
99 | "metadata": {},
100 | "output_type": "execute_result"
101 | }
102 | ],
103 | "source": [
104 | "2 * 4"
105 | ]
106 | },
107 | {
108 | "cell_type": "code",
109 | "execution_count": 16,
110 | "metadata": {},
111 | "outputs": [
112 | {
113 | "data": {
114 | "text/plain": [
115 | "0.6"
116 | ]
117 | },
118 | "execution_count": 16,
119 | "metadata": {},
120 | "output_type": "execute_result"
121 | }
122 | ],
123 | "source": [
124 | "3 / 5"
125 | ]
126 | },
127 | {
128 | "cell_type": "markdown",
129 | "metadata": {},
130 | "source": [
131 | "# Estruturas de Controle "
132 | ]
133 | },
134 | {
135 | "cell_type": "code",
136 | "execution_count": 20,
137 | "metadata": {},
138 | "outputs": [],
139 | "source": [
140 | "a = 2"
141 | ]
142 | },
143 | {
144 | "cell_type": "code",
145 | "execution_count": 21,
146 | "metadata": {},
147 | "outputs": [],
148 | "source": [
149 | "b = 3"
150 | ]
151 | },
152 | {
153 | "cell_type": "code",
154 | "execution_count": 22,
155 | "metadata": {},
156 | "outputs": [
157 | {
158 | "data": {
159 | "text/plain": [
160 | "5"
161 | ]
162 | },
163 | "execution_count": 22,
164 | "metadata": {},
165 | "output_type": "execute_result"
166 | }
167 | ],
168 | "source": [
169 | "a + b"
170 | ]
171 | },
172 | {
173 | "cell_type": "code",
174 | "execution_count": 23,
175 | "metadata": {},
176 | "outputs": [
177 | {
178 | "data": {
179 | "text/plain": [
180 | "125"
181 | ]
182 | },
183 | "execution_count": 23,
184 | "metadata": {},
185 | "output_type": "execute_result"
186 | }
187 | ],
188 | "source": [
189 | "_ ** 3"
190 | ]
191 | },
192 | {
193 | "cell_type": "code",
194 | "execution_count": 24,
195 | "metadata": {},
196 | "outputs": [
197 | {
198 | "data": {
199 | "text/plain": [
200 | "25.0"
201 | ]
202 | },
203 | "execution_count": 24,
204 | "metadata": {},
205 | "output_type": "execute_result"
206 | }
207 | ],
208 | "source": [
209 | "_ / 5"
210 | ]
211 | },
212 | {
213 | "cell_type": "code",
214 | "execution_count": 25,
215 | "metadata": {},
216 | "outputs": [
217 | {
218 | "name": "stdout",
219 | "output_type": "stream",
220 | "text": [
221 | "7 3\n"
222 | ]
223 | }
224 | ],
225 | "source": [
226 | "a = 3\n",
227 | "b = 7\n",
228 | "\n",
229 | "a, b = b, a\n",
230 | "print(a, b)"
231 | ]
232 | }
233 | ],
234 | "metadata": {
235 | "kernelspec": {
236 | "display_name": "Python 3",
237 | "language": "python",
238 | "name": "python3"
239 | },
240 | "language_info": {
241 | "codemirror_mode": {
242 | "name": "ipython",
243 | "version": 3
244 | },
245 | "file_extension": ".py",
246 | "mimetype": "text/x-python",
247 | "name": "python",
248 | "nbconvert_exporter": "python",
249 | "pygments_lexer": "ipython3",
250 | "version": "3.7.0"
251 | }
252 | },
253 | "nbformat": 4,
254 | "nbformat_minor": 2
255 | }
256 |
--------------------------------------------------------------------------------
/pacotes/app/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cod3rcursos/curso-python/a572d15cb1c1816064095d82bc3e1a46176ee379/pacotes/app/__init__.py
--------------------------------------------------------------------------------
/pacotes/app/negocio/__init__.py:
--------------------------------------------------------------------------------
1 | def nome_existe(nome):
2 | return False
3 |
--------------------------------------------------------------------------------
/pacotes/app/negocio/backend.py:
--------------------------------------------------------------------------------
1 | def add_nome(nome):
2 | pass
3 |
--------------------------------------------------------------------------------
/pacotes/app/utils/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cod3rcursos/curso-python/a572d15cb1c1816064095d82bc3e1a46176ee379/pacotes/app/utils/__init__.py
--------------------------------------------------------------------------------
/pacotes/app/utils/gerador.py:
--------------------------------------------------------------------------------
1 | from random import choice
2 |
3 |
4 | def novo_nome():
5 | return choice(['Ana', 'Maria', 'Pedro', 'Rafael'])
6 |
--------------------------------------------------------------------------------
/pacotes/calc/__init__.py:
--------------------------------------------------------------------------------
1 | from pacote1.modulo1 import soma
2 | from pacote2.modulo1 import subtracao
3 |
4 | __all__ = ['soma', 'subtracao']
5 |
--------------------------------------------------------------------------------
/pacotes/desafio_package.py:
--------------------------------------------------------------------------------
1 | from app.utils.gerador import novo_nome
2 | from app.negocio import nome_existe
3 | from app.negocio.backend import add_nome
4 |
5 |
6 | def main():
7 | while True:
8 | nome = novo_nome()
9 | if not nome_existe(nome):
10 | add_nome(nome)
11 | break
12 |
13 | print(f'Criado novo nome de testes: "{nome}"')
14 |
15 |
16 | if __name__ == '__main__':
17 | main()
18 |
--------------------------------------------------------------------------------
/pacotes/pacote1/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cod3rcursos/curso-python/a572d15cb1c1816064095d82bc3e1a46176ee379/pacotes/pacote1/__init__.py
--------------------------------------------------------------------------------
/pacotes/pacote1/modulo1.py:
--------------------------------------------------------------------------------
1 | print(f'importado módulo {__name__} do pacote {__package__}!')
2 |
3 |
4 | def soma(x, y):
5 | return x + y
6 |
--------------------------------------------------------------------------------
/pacotes/pacote1/modulo2.py:
--------------------------------------------------------------------------------
1 | def main():
2 | print(f'Rodando o main() no módulo {__name__}')
3 |
4 |
5 | if __name__ == '__main__':
6 | main()
7 |
--------------------------------------------------------------------------------
/pacotes/pacote2/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cod3rcursos/curso-python/a572d15cb1c1816064095d82bc3e1a46176ee379/pacotes/pacote2/__init__.py
--------------------------------------------------------------------------------
/pacotes/pacote2/modulo1.py:
--------------------------------------------------------------------------------
1 | def subtracao(x, y):
2 | return x - y
3 |
--------------------------------------------------------------------------------
/pacotes/pacote_v1.py:
--------------------------------------------------------------------------------
1 | from pacote1 import modulo1
2 |
3 | print(type(modulo1))
4 | print(modulo1.soma(2, 3))
5 |
--------------------------------------------------------------------------------
/pacotes/pacote_v2.py:
--------------------------------------------------------------------------------
1 | from pacote1 import modulo2
2 |
3 | modulo2.main()
4 |
--------------------------------------------------------------------------------
/pacotes/pacote_v3.py:
--------------------------------------------------------------------------------
1 | from pacote1 import modulo1
2 | from pacote2 import modulo1 as modulo1_sub
3 |
4 | print('Soma', modulo1.soma(3, 2))
5 | print('Subtração', modulo1_sub.subtracao(3, 2))
6 |
--------------------------------------------------------------------------------
/pacotes/pacote_v4.py:
--------------------------------------------------------------------------------
1 | from pacote1.modulo1 import soma
2 | from pacote2.modulo1 import subtracao as sub
3 |
4 | print('Soma', soma(3, 2))
5 | print('Subtração', sub(3, 2))
6 |
--------------------------------------------------------------------------------
/pacotes/pacote_v5.py:
--------------------------------------------------------------------------------
1 | from calc import soma, subtracao
2 |
3 | print('Soma', soma(3, 2))
4 | print('Subtração', subtracao(3, 2))
5 |
--------------------------------------------------------------------------------
/pip/requirements.txt:
--------------------------------------------------------------------------------
1 | astroid==2.2.5
2 | isort==4.3.21
3 | lazy-object-proxy==1.4.1
4 | mccabe==0.6.1
5 | pylint==2.3.1
6 | pytz==2019.2
7 | six==1.12.0
8 | sqlparse==0.3.0
9 | typed-ast==1.4.0
10 | wrapt==1.11.2
11 | django==2.2.4
12 |
--------------------------------------------------------------------------------
/poo/data_v1.py:
--------------------------------------------------------------------------------
1 | class Data:
2 | def __str__(self):
3 | return f'{self.dia}/{self.mes}/{self.ano}'
4 |
5 |
6 | d1 = Data()
7 | d1.dia = 5
8 | d1.mes = 12
9 | d1.ano = 2019
10 | print(d1)
11 |
12 | d2 = Data()
13 | d2.dia = 7
14 | d2.mes = 11
15 | d2.ano = 2020
16 | print(d2)
17 |
--------------------------------------------------------------------------------
/poo/data_v2.py:
--------------------------------------------------------------------------------
1 | class Data:
2 | def __init__(self, dia=1, mes=1, ano=1970):
3 | self.dia = dia
4 | self.mes = mes
5 | self.ano = ano
6 |
7 | def __str__(self):
8 | return f'{self.dia}/{self.mes}/{self.ano}'
9 |
10 |
11 | d1 = Data(5, 12, 2019)
12 | # d1.dia = 5
13 | # d1.mes = 12
14 | # d1.ano = 2019
15 | print(d1)
16 |
17 | d2 = Data(ano=2022, mes=12)
18 | d2.dia = 12
19 | # d2.mes = 11
20 | # d2.ano = 2020
21 | print(d2)
22 |
--------------------------------------------------------------------------------
/poo/desafio_carro.py:
--------------------------------------------------------------------------------
1 | class Carro:
2 | def __init__(self, velocidade_maxima):
3 | self.velocidade_maxima = velocidade_maxima
4 | self.velocidade_atual = 0
5 |
6 | def acelerar(self, delta=5):
7 | maxima = self.velocidade_maxima
8 | nova = self.velocidade_atual + delta
9 | self.velocidade_atual = nova if nova <= maxima else maxima
10 | return self.velocidade_atual
11 |
12 | def frear(self, delta=5):
13 | nova = self.velocidade_atual - delta
14 | self.velocidade_atual = nova if nova >= 0 else 0
15 | return self.velocidade_atual
16 |
17 |
18 | if __name__ == '__main__':
19 | c1 = Carro(180)
20 |
21 | for _ in range(25):
22 | print(c1.acelerar(8))
23 |
24 | for _ in range(10):
25 | print(c1.frear(delta=20))
26 |
--------------------------------------------------------------------------------
/poo/desafio_loja.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | from datetime import datetime
3 | from loja import Cliente, Vendedor, Compra
4 |
5 |
6 | def main():
7 | cliente = Cliente('Maria Lima', 44)
8 | vendedor = Vendedor('Pedro Garrido', 36, 5000)
9 | compra1 = Compra(cliente, datetime.now(), 512)
10 | compra2 = Compra(cliente, datetime(2018, 6, 4), 256)
11 | cliente.registrar_compra(compra1)
12 | cliente.registrar_compra(compra2)
13 | print(f'Cliente: {cliente}', '(adulto)' if cliente.is_adulto() else '')
14 | print(f'Vendedor: {vendedor}')
15 |
16 | valor_total = cliente.total_compras()
17 | qtde_compras = len(cliente.compras)
18 | print(f'Total: {valor_total} em {qtde_compras} compras')
19 | print(f'Última compra: {cliente.get_data_ultima_compra()}')
20 |
21 |
22 | if __name__ == '__main__':
23 | main()
24 |
--------------------------------------------------------------------------------
/poo/loja/__init__.py:
--------------------------------------------------------------------------------
1 | from .cliente import Cliente
2 | from .vendedor import Vendedor
3 | from .compra import Compra
4 |
5 |
6 | __all__ = ['Cliente', 'Vendedor', 'Compra']
7 |
--------------------------------------------------------------------------------
/poo/loja/cliente.py:
--------------------------------------------------------------------------------
1 | from .pessoa import Pessoa
2 |
3 |
4 | # def get_data(compra):
5 | # return compra.data
6 |
7 |
8 | class Cliente(Pessoa):
9 | def __init__(self, nome, idade):
10 | super().__init__(nome, idade)
11 | self.compras = []
12 |
13 | def registrar_compra(self, compra):
14 | self.compras.append(compra)
15 |
16 | def get_data_ultima_compra(self):
17 | return None if not self.compras else \
18 | sorted(self.compras, key=lambda c: c.data)[-1].data
19 |
20 | def total_compras(self):
21 | total = 0
22 | for compra in self.compras:
23 | total += compra.valor
24 | return total
25 |
--------------------------------------------------------------------------------
/poo/loja/compra.py:
--------------------------------------------------------------------------------
1 | class Compra:
2 | def __init__(self, vendedor, data, valor):
3 | self.vendedor = vendedor
4 | self.data = data
5 | self.valor = valor
6 |
--------------------------------------------------------------------------------
/poo/loja/pessoa.py:
--------------------------------------------------------------------------------
1 | MAIOR_IDADE = 18
2 |
3 |
4 | class Pessoa:
5 | def __init__(self, nome, idade):
6 | self.nome = nome
7 | self.idade = idade
8 |
9 | def __str__(self):
10 | if not self.idade:
11 | return self.nome
12 | return f'{self.nome} ({self.idade} anos)'
13 |
14 | def is_adulto(self):
15 | return (self.idade or 0) > MAIOR_IDADE
16 |
--------------------------------------------------------------------------------
/poo/loja/vendedor.py:
--------------------------------------------------------------------------------
1 | from .pessoa import Pessoa
2 |
3 |
4 | class Vendedor(Pessoa):
5 | def __init__(self, nome, idade, salario):
6 | super().__init__(nome, idade)
7 | self.salario = salario
8 |
--------------------------------------------------------------------------------
/poo/todo_v1.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | from datetime import datetime
3 |
4 |
5 | class Tarefa:
6 | def __init__(self, descricao):
7 | self.descricao = descricao
8 | self.feito = False
9 | self.criacao = datetime.now()
10 |
11 | def concluir(self):
12 | self.feito = True
13 |
14 | def __str__(self):
15 | return self.descricao + (' (Concluída)' if self.feito else '')
16 |
17 |
18 | def main():
19 | casa = []
20 | casa.append(Tarefa('Passar roupa'))
21 | casa.append(Tarefa('Lavar prato'))
22 |
23 | # Desafio -> 'Lavar prato'
24 | [tarefa.concluir() for tarefa in casa if tarefa.descricao == 'Lavar prato']
25 |
26 | for tarefa in casa:
27 | print(f'- {tarefa}')
28 |
29 |
30 | if __name__ == '__main__':
31 | main()
32 |
--------------------------------------------------------------------------------
/poo/todo_v2.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | from datetime import datetime
3 |
4 |
5 | class Projeto:
6 | def __init__(self, nome):
7 | self.nome = nome
8 | self.tarefas = []
9 |
10 | def add(self, descricao):
11 | self.tarefas.append(Tarefa(descricao))
12 |
13 | def pendentes(self):
14 | return [tarefa for tarefa in self.tarefas if not tarefa.feito]
15 |
16 | def procurar(self, descricao):
17 | # Possível IndexError
18 | return [tarefa for tarefa in self.tarefas
19 | if tarefa.descricao == descricao][0]
20 |
21 | def __str__(self):
22 | return f'{self.nome} ({len(self.pendentes())} tarefa(s) pendente(s))'
23 |
24 |
25 | class Tarefa:
26 | def __init__(self, descricao):
27 | self.descricao = descricao
28 | self.feito = False
29 | self.criacao = datetime.now()
30 |
31 | def concluir(self):
32 | self.feito = True
33 |
34 | def __str__(self):
35 | return self.descricao + (' (Concluída)' if self.feito else '')
36 |
37 |
38 | def main():
39 | casa = Projeto('Tarefas de Casa')
40 | casa.add('Passar roupa')
41 | casa.add('Lavar prato')
42 | print(casa)
43 |
44 | casa.procurar('Lavar prato').concluir()
45 | for tarefa in casa.tarefas:
46 | print(f'- {tarefa}')
47 | print(casa)
48 |
49 | mercado = Projeto('Compras no mercado')
50 | mercado.add('Frutas secas')
51 | mercado.add('Carne')
52 | mercado.add('Tomate')
53 | print(mercado)
54 |
55 | comprar_carne = mercado.procurar('Carne')
56 | comprar_carne.concluir()
57 | for tarefa in mercado.tarefas:
58 | print(f'- {tarefa}')
59 | print(mercado)
60 |
61 |
62 | if __name__ == '__main__':
63 | main()
64 |
--------------------------------------------------------------------------------
/poo/todo_v3.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | from datetime import datetime
3 |
4 |
5 | class Projeto:
6 | def __init__(self, nome):
7 | self.nome = nome
8 | self.tarefas = []
9 |
10 | def __iter__(self):
11 | return self.tarefas.__iter__()
12 |
13 | def add(self, descricao):
14 | self.tarefas.append(Tarefa(descricao))
15 |
16 | def pendentes(self):
17 | return [tarefa for tarefa in self.tarefas if not tarefa.feito]
18 |
19 | def procurar(self, descricao):
20 | # Possível IndexError
21 | return [tarefa for tarefa in self.tarefas
22 | if tarefa.descricao == descricao][0]
23 |
24 | def __str__(self):
25 | return f'{self.nome} ({len(self.pendentes())} tarefa(s) pendente(s))'
26 |
27 |
28 | class Tarefa:
29 | def __init__(self, descricao):
30 | self.descricao = descricao
31 | self.feito = False
32 | self.criacao = datetime.now()
33 |
34 | def concluir(self):
35 | self.feito = True
36 |
37 | def __str__(self):
38 | return self.descricao + (' (Concluída)' if self.feito else '')
39 |
40 |
41 | def main():
42 | casa = Projeto('Tarefas de Casa')
43 | casa.add('Passar roupa')
44 | casa.add('Lavar prato')
45 | print(casa)
46 |
47 | casa.procurar('Lavar prato').concluir()
48 | for tarefa in casa:
49 | print(f'- {tarefa}')
50 | print(casa)
51 |
52 | mercado = Projeto('Compras no mercado')
53 | mercado.add('Frutas secas')
54 | mercado.add('Carne')
55 | mercado.add('Tomate')
56 | print(mercado)
57 |
58 | comprar_carne = mercado.procurar('Carne')
59 | comprar_carne.concluir()
60 | for tarefa in mercado:
61 | print(f'- {tarefa}')
62 | print(mercado)
63 |
64 |
65 | if __name__ == '__main__':
66 | main()
67 |
--------------------------------------------------------------------------------
/poo/todo_v4.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | from datetime import datetime, timedelta
3 |
4 |
5 | class Projeto:
6 | def __init__(self, nome):
7 | self.nome = nome
8 | self.tarefas = []
9 |
10 | def __iter__(self):
11 | return self.tarefas.__iter__()
12 |
13 | def add(self, descricao, vencimento=None):
14 | self.tarefas.append(Tarefa(descricao, vencimento))
15 |
16 | def pendentes(self):
17 | return [tarefa for tarefa in self.tarefas if not tarefa.feito]
18 |
19 | def procurar(self, descricao):
20 | # Possível IndexError
21 | return [tarefa for tarefa in self.tarefas
22 | if tarefa.descricao == descricao][0]
23 |
24 | def __str__(self):
25 | return f'{self.nome} ({len(self.pendentes())} tarefa(s) pendente(s))'
26 |
27 |
28 | class Tarefa:
29 | def __init__(self, descricao, vencimento=None):
30 | self.descricao = descricao
31 | self.feito = False
32 | self.criacao = datetime.now()
33 | self.vencimento = vencimento
34 |
35 | def concluir(self):
36 | self.feito = True
37 |
38 | def __str__(self):
39 | status = []
40 | if self.feito:
41 | status.append('(Concluída)')
42 | elif self.vencimento:
43 | if datetime.now() > self.vencimento:
44 | status.append('(Vencida)')
45 | else:
46 | dias = (self.vencimento - datetime.now()).days
47 | status.append(f'(Vence em {dias} dias)')
48 |
49 | return f'{self.descricao} ' + ' '.join(status)
50 |
51 |
52 | def main():
53 | casa = Projeto('Tarefas de Casa')
54 | casa.add('Passar roupa', datetime.now())
55 | casa.add('Lavar prato')
56 | print(casa)
57 |
58 | casa.procurar('Lavar prato').concluir()
59 | for tarefa in casa:
60 | print(f'- {tarefa}')
61 | print(casa)
62 |
63 | mercado = Projeto('Compras no mercado')
64 | mercado.add('Frutas secas')
65 | mercado.add('Carne')
66 | mercado.add('Tomate', datetime.now() + timedelta(days=3, seconds=1))
67 | print(mercado)
68 |
69 | comprar_carne = mercado.procurar('Carne')
70 | comprar_carne.concluir()
71 | for tarefa in mercado:
72 | print(f'- {tarefa}')
73 | print(mercado)
74 |
75 |
76 | if __name__ == '__main__':
77 | main()
78 |
--------------------------------------------------------------------------------
/poo/todo_v5.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | from datetime import datetime, timedelta
3 |
4 |
5 | class Projeto:
6 | def __init__(self, nome):
7 | self.nome = nome
8 | self.tarefas = []
9 |
10 | def __iter__(self):
11 | return self.tarefas.__iter__()
12 |
13 | def add(self, descricao, vencimento=None):
14 | self.tarefas.append(Tarefa(descricao, vencimento))
15 |
16 | def pendentes(self):
17 | return [tarefa for tarefa in self.tarefas if not tarefa.feito]
18 |
19 | def procurar(self, descricao):
20 | # Possível IndexError
21 | return [tarefa for tarefa in self.tarefas
22 | if tarefa.descricao == descricao][0]
23 |
24 | def __str__(self):
25 | return f'{self.nome} ({len(self.pendentes())} tarefa(s) pendente(s))'
26 |
27 |
28 | class Tarefa:
29 | def __init__(self, descricao, vencimento=None):
30 | self.descricao = descricao
31 | self.feito = False
32 | self.criacao = datetime.now()
33 | self.vencimento = vencimento
34 |
35 | def concluir(self):
36 | self.feito = True
37 |
38 | def __str__(self):
39 | status = []
40 | if self.feito:
41 | status.append('(Concluída)')
42 | elif self.vencimento:
43 | if datetime.now() > self.vencimento:
44 | status.append('(Vencida)')
45 | else:
46 | dias = (self.vencimento - datetime.now()).days
47 | status.append(f'(Vence em {dias} dias)')
48 |
49 | return f'{self.descricao} ' + ' '.join(status)
50 |
51 |
52 | class TarefaRecorrente(Tarefa):
53 | def __init__(self, descricao, vencimento, dias=7):
54 | super().__init__(descricao, vencimento)
55 | self.dias = dias
56 |
57 | def concluir(self):
58 | super().concluir()
59 | novo_vencimento = datetime.now() + timedelta(days=self.dias)
60 | return TarefaRecorrente(self.descricao, novo_vencimento, self.dias)
61 |
62 |
63 | def main():
64 | casa = Projeto('Tarefas de Casa')
65 | casa.add('Passar roupa', datetime.now())
66 | casa.add('Lavar prato')
67 | casa.tarefas.append(TarefaRecorrente('Trocar lençóis', datetime.now(), 7))
68 | casa.tarefas.append(casa.procurar('Trocar lençóis').concluir())
69 | print(casa)
70 |
71 | casa.procurar('Lavar prato').concluir()
72 | for tarefa in casa:
73 | print(f'- {tarefa}')
74 | print(casa)
75 |
76 | mercado = Projeto('Compras no mercado')
77 | mercado.add('Frutas secas')
78 | mercado.add('Carne')
79 | mercado.add('Tomate', datetime.now() + timedelta(days=3, seconds=1))
80 | print(mercado)
81 |
82 | comprar_carne = mercado.procurar('Carne')
83 | comprar_carne.concluir()
84 | for tarefa in mercado:
85 | print(f'- {tarefa}')
86 | print(mercado)
87 |
88 |
89 | if __name__ == '__main__':
90 | main()
91 |
--------------------------------------------------------------------------------
/poo/todo_v6.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | from datetime import datetime, timedelta
3 |
4 |
5 | class Projeto:
6 | def __init__(self, nome):
7 | self.nome = nome
8 | self.tarefas = []
9 |
10 | def __iter__(self):
11 | return self.tarefas.__iter__()
12 |
13 | def _add_tarefa(self, tarefa, **kwargs):
14 | self.tarefas.append(tarefa)
15 |
16 | def _add_nova_tarefa(self, descricao, **kwargs):
17 | self.tarefas.append(Tarefa(descricao, kwargs.get('vencimento', None)))
18 |
19 | def add(self, tarefa, vencimento=None, **kwargs):
20 | funcao_escolhida = self._add_tarefa if isinstance(tarefa, Tarefa) \
21 | else self._add_nova_tarefa
22 | kwargs['vencimento'] = vencimento
23 | funcao_escolhida(tarefa, **kwargs)
24 |
25 | def pendentes(self):
26 | return [tarefa for tarefa in self.tarefas if not tarefa.feito]
27 |
28 | def procurar(self, descricao):
29 | # Possível IndexError
30 | return [tarefa for tarefa in self.tarefas
31 | if tarefa.descricao == descricao][0]
32 |
33 | def __str__(self):
34 | return f'{self.nome} ({len(self.pendentes())} tarefa(s) pendente(s))'
35 |
36 |
37 | class Tarefa:
38 | def __init__(self, descricao, vencimento=None):
39 | self.descricao = descricao
40 | self.feito = False
41 | self.criacao = datetime.now()
42 | self.vencimento = vencimento
43 |
44 | def concluir(self):
45 | self.feito = True
46 |
47 | def __str__(self):
48 | status = []
49 | if self.feito:
50 | status.append('(Concluída)')
51 | elif self.vencimento:
52 | if datetime.now() > self.vencimento:
53 | status.append('(Vencida)')
54 | else:
55 | dias = (self.vencimento - datetime.now()).days
56 | status.append(f'(Vence em {dias} dias)')
57 |
58 | return f'{self.descricao} ' + ' '.join(status)
59 |
60 |
61 | class TarefaRecorrente(Tarefa):
62 | def __init__(self, descricao, vencimento, dias=7):
63 | super().__init__(descricao, vencimento)
64 | self.dias = dias
65 |
66 | def concluir(self):
67 | super().concluir()
68 | novo_vencimento = datetime.now() + timedelta(days=self.dias)
69 | return TarefaRecorrente(self.descricao, novo_vencimento, self.dias)
70 |
71 |
72 | def main():
73 | casa = Projeto('Tarefas de Casa')
74 | casa.add('Passar roupa', datetime.now())
75 | casa.add('Lavar prato')
76 | casa.add(TarefaRecorrente('Trocar lençóis', datetime.now(), 7))
77 | casa.add(casa.procurar('Trocar lençóis').concluir())
78 | print(casa)
79 |
80 | casa.procurar('Lavar prato').concluir()
81 | for tarefa in casa:
82 | print(f'- {tarefa}')
83 | print(casa)
84 |
85 | mercado = Projeto('Compras no mercado')
86 | mercado.add('Frutas secas')
87 | mercado.add('Carne')
88 | mercado.add('Tomate', datetime.now() + timedelta(days=3, seconds=1))
89 | print(mercado)
90 |
91 | comprar_carne = mercado.procurar('Carne')
92 | comprar_carne.concluir()
93 | for tarefa in mercado:
94 | print(f'- {tarefa}')
95 | print(mercado)
96 |
97 |
98 | if __name__ == '__main__':
99 | main()
100 |
--------------------------------------------------------------------------------
/poo/todo_v7.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | from datetime import datetime, timedelta
3 |
4 |
5 | class Projeto:
6 | def __init__(self, nome):
7 | self.nome = nome
8 | self.tarefas = []
9 |
10 | def __iter__(self):
11 | return self.tarefas.__iter__()
12 |
13 | def __iadd__(self, tarefa):
14 | tarefa.dono = self
15 | self._add_tarefa(tarefa)
16 | return self
17 |
18 | def _add_tarefa(self, tarefa, **kwargs):
19 | self.tarefas.append(tarefa)
20 |
21 | def _add_nova_tarefa(self, descricao, **kwargs):
22 | self.tarefas.append(Tarefa(descricao, kwargs.get('vencimento', None)))
23 |
24 | def add(self, tarefa, vencimento=None, **kwargs):
25 | funcao_escolhida = self._add_tarefa if isinstance(tarefa, Tarefa) \
26 | else self._add_nova_tarefa
27 | kwargs['vencimento'] = vencimento
28 | funcao_escolhida(tarefa, **kwargs)
29 |
30 | def pendentes(self):
31 | return [tarefa for tarefa in self.tarefas if not tarefa.feito]
32 |
33 | def procurar(self, descricao):
34 | # Possível IndexError
35 | return [tarefa for tarefa in self.tarefas
36 | if tarefa.descricao == descricao][0]
37 |
38 | def __str__(self):
39 | return f'{self.nome} ({len(self.pendentes())} tarefa(s) pendente(s))'
40 |
41 |
42 | class Tarefa:
43 | def __init__(self, descricao, vencimento=None):
44 | self.descricao = descricao
45 | self.feito = False
46 | self.criacao = datetime.now()
47 | self.vencimento = vencimento
48 |
49 | def concluir(self):
50 | self.feito = True
51 |
52 | def __str__(self):
53 | status = []
54 | if self.feito:
55 | status.append('(Concluída)')
56 | elif self.vencimento:
57 | if datetime.now() > self.vencimento:
58 | status.append('(Vencida)')
59 | else:
60 | dias = (self.vencimento - datetime.now()).days
61 | status.append(f'(Vence em {dias} dias)')
62 |
63 | return f'{self.descricao} ' + ' '.join(status)
64 |
65 |
66 | class TarefaRecorrente(Tarefa):
67 | def __init__(self, descricao, vencimento, dias=7):
68 | super().__init__(descricao, vencimento)
69 | self.dias = dias
70 | self.dono = None
71 |
72 | def concluir(self):
73 | super().concluir()
74 | novo_vencimento = datetime.now() + timedelta(days=self.dias)
75 | nova_tarefa = TarefaRecorrente(
76 | self.descricao, novo_vencimento, self.dias)
77 | if self.dono:
78 | self.dono += nova_tarefa
79 | return nova_tarefa
80 |
81 |
82 | def main():
83 | casa = Projeto('Tarefas de Casa')
84 | casa.add('Passar roupa', datetime.now())
85 | casa.add('Lavar prato')
86 | casa += TarefaRecorrente('Trocar lençóis', datetime.now(), 7)
87 | casa.procurar('Trocar lençóis').concluir()
88 | print(casa)
89 |
90 | casa.procurar('Lavar prato').concluir()
91 | for tarefa in casa:
92 | print(f'- {tarefa}')
93 | print(casa)
94 |
95 | mercado = Projeto('Compras no mercado')
96 | mercado.add('Frutas secas')
97 | mercado.add('Carne')
98 | mercado.add('Tomate', datetime.now() + timedelta(days=3, seconds=1))
99 | print(mercado)
100 |
101 | comprar_carne = mercado.procurar('Carne')
102 | comprar_carne.concluir()
103 | for tarefa in mercado:
104 | print(f'- {tarefa}')
105 | print(mercado)
106 |
107 |
108 | if __name__ == '__main__':
109 | main()
110 |
--------------------------------------------------------------------------------
/poo/todo_v8.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | from datetime import datetime, timedelta
3 |
4 |
5 | class TarefaNaoEncontrada(Exception):
6 | pass
7 |
8 |
9 | class Projeto:
10 | def __init__(self, nome):
11 | self.nome = nome
12 | self.tarefas = []
13 |
14 | def __iter__(self):
15 | return self.tarefas.__iter__()
16 |
17 | def __iadd__(self, tarefa):
18 | tarefa.dono = self
19 | self._add_tarefa(tarefa)
20 | return self
21 |
22 | def _add_tarefa(self, tarefa, **kwargs):
23 | self.tarefas.append(tarefa)
24 |
25 | def _add_nova_tarefa(self, descricao, **kwargs):
26 | self.tarefas.append(Tarefa(descricao, kwargs.get('vencimento', None)))
27 |
28 | def add(self, tarefa, vencimento=None, **kwargs):
29 | funcao_escolhida = self._add_tarefa if isinstance(tarefa, Tarefa) \
30 | else self._add_nova_tarefa
31 | kwargs['vencimento'] = vencimento
32 | funcao_escolhida(tarefa, **kwargs)
33 |
34 | def pendentes(self):
35 | return [tarefa for tarefa in self.tarefas if not tarefa.feito]
36 |
37 | def procurar(self, descricao):
38 | try:
39 | # Possível IndexError
40 | return [tarefa for tarefa in self.tarefas
41 | if tarefa.descricao == descricao][0]
42 | except IndexError as e:
43 | raise TarefaNaoEncontrada(str(e))
44 |
45 | def __str__(self):
46 | return f'{self.nome} ({len(self.pendentes())} tarefa(s) pendente(s))'
47 |
48 |
49 | class Tarefa:
50 | def __init__(self, descricao, vencimento=None):
51 | self.descricao = descricao
52 | self.feito = False
53 | self.criacao = datetime.now()
54 | self.vencimento = vencimento
55 |
56 | def concluir(self):
57 | self.feito = True
58 |
59 | def __str__(self):
60 | status = []
61 | if self.feito:
62 | status.append('(Concluída)')
63 | elif self.vencimento:
64 | if datetime.now() > self.vencimento:
65 | status.append('(Vencida)')
66 | else:
67 | dias = (self.vencimento - datetime.now()).days
68 | status.append(f'(Vence em {dias} dias)')
69 |
70 | return f'{self.descricao} ' + ' '.join(status)
71 |
72 |
73 | class TarefaRecorrente(Tarefa):
74 | def __init__(self, descricao, vencimento, dias=7):
75 | super().__init__(descricao, vencimento)
76 | self.dias = dias
77 | self.dono = None
78 |
79 | def concluir(self):
80 | super().concluir()
81 | novo_vencimento = datetime.now() + timedelta(days=self.dias)
82 | nova_tarefa = TarefaRecorrente(
83 | self.descricao, novo_vencimento, self.dias)
84 | if self.dono:
85 | self.dono += nova_tarefa
86 | return nova_tarefa
87 |
88 |
89 | def main():
90 | casa = Projeto('Tarefas de Casa')
91 | casa.add('Passar roupa', datetime.now())
92 | casa.add('Lavar prato')
93 | casa += TarefaRecorrente('Trocar lençóis', datetime.now(), 7)
94 | casa.procurar('Trocar lençóis').concluir()
95 | print(casa)
96 |
97 | try:
98 | casa.procurar('Lavar prato - ERRO').concluir()
99 | except TarefaNaoEncontrada as e:
100 | print(f'A causa foi "{str(e)}"!')
101 | finally:
102 | print('Sempre será executado!')
103 |
104 | casa.procurar('Lavar prato').concluir()
105 | for tarefa in casa:
106 | print(f'- {tarefa}')
107 | print(casa)
108 |
109 | mercado = Projeto('Compras no mercado')
110 | mercado.add('Frutas secas')
111 | mercado.add('Carne')
112 | mercado.add('Tomate', datetime.now() + timedelta(days=3, seconds=1))
113 | print(mercado)
114 |
115 | comprar_carne = mercado.procurar('Carne')
116 | comprar_carne.concluir()
117 | for tarefa in mercado:
118 | print(f'- {tarefa}')
119 | print(mercado)
120 |
121 |
122 | if __name__ == '__main__':
123 | main()
124 |
--------------------------------------------------------------------------------
/poo_avancada/contador_objetos.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | class ClasseSimples:
3 | contador = 0
4 |
5 | def __init__(self):
6 | # self.__class__.contador += 1
7 | self.contar()
8 |
9 | @classmethod
10 | def contar(cls):
11 | cls.contador += 1
12 |
13 |
14 | if __name__ == '__main__':
15 | lista = [ClasseSimples(), ClasseSimples(), ClasseSimples()]
16 | print(ClasseSimples.contador) # Esperado 3
17 |
--------------------------------------------------------------------------------
/poo_avancada/evolucao_v1.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | class Humano:
3 | # atributo de classe
4 | especie = 'Homo Sapiens'
5 |
6 | def __init__(self, nome):
7 | self.nome = nome
8 |
9 | def das_cavernas(self):
10 | self.especie = 'Homo Neanderthalensis'
11 | return self
12 |
13 |
14 | if __name__ == '__main__':
15 | jose = Humano('José')
16 | grokn = Humano('Grokn').das_cavernas()
17 |
18 | print(f'Humano.especie: {Humano.especie}')
19 | print(f'jose.especie: {jose.especie}')
20 | print(f'grokn.especie: {grokn.especie}')
21 |
--------------------------------------------------------------------------------
/poo_avancada/evolucao_v2.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 |
3 |
4 | class Humano:
5 | # atributo de classe
6 | especie = 'Homo Sapiens'
7 |
8 | def __init__(self, nome):
9 | self.nome = nome
10 |
11 | def das_cavernas(self):
12 | self.especie = 'Homo Neanderthalensis'
13 | return self
14 |
15 | @staticmethod
16 | def especies():
17 | adjetivos = ('Habilis', 'Erectus', 'Neanderthalensis', 'Sapiens')
18 | return ('Australopiteco',) + tuple(f'Homo {adj}' for adj in adjetivos)
19 |
20 | @classmethod
21 | def is_evoluido(cls):
22 | return cls.especie == cls.especies()[-1]
23 |
24 |
25 | class Neanderthal(Humano):
26 | especie = Humano.especies()[-2]
27 |
28 |
29 | class HomoSapiens(Humano):
30 | especie = Humano.especies()[-1]
31 |
32 |
33 | if __name__ == '__main__':
34 | jose = HomoSapiens('José')
35 | # HomoSapiens.das_cavernas(jose)
36 |
37 | grokn = Neanderthal('Grokn')
38 | print(
39 | f'Evolução (a partir da classe): {", ".join(HomoSapiens.especies())}')
40 | print(f'Evolução (a partir da instancia): {", ".join(jose.especies())}')
41 | print(f'Homo Sapiens evoluído? {HomoSapiens.is_evoluido()}')
42 | print(f'Neanderthal evoluído? {Neanderthal.is_evoluido()}')
43 | print(f'José evoluído? {jose.is_evoluido()}')
44 | print(f'Grokn evoluído? {grokn.is_evoluido()}')
45 |
--------------------------------------------------------------------------------
/poo_avancada/evolucao_v3.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 |
3 |
4 | class Humano:
5 | # atributo de classe
6 | especie = 'Homo Sapiens'
7 |
8 | def __init__(self, nome):
9 | self.nome = nome
10 | self._idade = None
11 |
12 | def get_idade(self):
13 | return self._idade
14 |
15 | def set_idade(self, idade):
16 | if idade < 0:
17 | raise ValueError('Idade deve ser um número positivo!')
18 | self._idade = idade
19 |
20 | def das_cavernas(self):
21 | self.especie = 'Homo Neanderthalensis'
22 | return self
23 |
24 | @staticmethod
25 | def especies():
26 | adjetivos = ('Habilis', 'Erectus', 'Neanderthalensis', 'Sapiens')
27 | return ('Australopiteco',) + tuple(f'Homo {adj}' for adj in adjetivos)
28 |
29 | @classmethod
30 | def is_evoluido(cls):
31 | return cls.especie == cls.especies()[-1]
32 |
33 |
34 | class Neanderthal(Humano):
35 | especie = Humano.especies()[-2]
36 |
37 |
38 | class HomoSapiens(Humano):
39 | especie = Humano.especies()[-1]
40 |
41 |
42 | if __name__ == '__main__':
43 | jose = HomoSapiens('José')
44 | jose.set_idade(40)
45 | print(f'Nome: {jose.nome} Idade: {jose.get_idade()}')
46 |
--------------------------------------------------------------------------------
/poo_avancada/evolucao_v4.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 |
3 |
4 | class Humano:
5 | # atributo de classe
6 | especie = 'Homo Sapiens'
7 |
8 | def __init__(self, nome):
9 | self.nome = nome
10 | self._idade = None
11 |
12 | @property
13 | def idade(self):
14 | return self._idade
15 |
16 | @idade.setter
17 | def idade(self, idade):
18 | if idade < 0:
19 | raise ValueError('Idade deve ser um número positivo!')
20 | self._idade = idade
21 |
22 | def das_cavernas(self):
23 | self.especie = 'Homo Neanderthalensis'
24 | return self
25 |
26 | @staticmethod
27 | def especies():
28 | adjetivos = ('Habilis', 'Erectus', 'Neanderthalensis', 'Sapiens')
29 | return ('Australopiteco',) + tuple(f'Homo {adj}' for adj in adjetivos)
30 |
31 | @classmethod
32 | def is_evoluido(cls):
33 | return cls.especie == cls.especies()[-1]
34 |
35 |
36 | class Neanderthal(Humano):
37 | especie = Humano.especies()[-2]
38 |
39 |
40 | class HomoSapiens(Humano):
41 | especie = Humano.especies()[-1]
42 |
43 |
44 | if __name__ == '__main__':
45 | jose = HomoSapiens('José')
46 | jose.idade = 40
47 | print(f'Nome: {jose.nome} Idade: {jose.idade}')
48 |
--------------------------------------------------------------------------------
/poo_avancada/evolucao_v5.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 |
3 |
4 | class Humano:
5 | # atributo de classe
6 | especie = 'Homo Sapiens'
7 |
8 | def __init__(self, nome):
9 | self.nome = nome
10 | self._idade = None
11 |
12 | @property
13 | def inteligente(self):
14 | raise NotImplementedError('Propriedade não implementada!')
15 |
16 | @property
17 | def idade(self):
18 | return self._idade
19 |
20 | @idade.setter
21 | def idade(self, idade):
22 | if idade < 0:
23 | raise ValueError('Idade deve ser um número positivo!')
24 | self._idade = idade
25 |
26 | def das_cavernas(self):
27 | self.especie = 'Homo Neanderthalensis'
28 | return self
29 |
30 | @staticmethod
31 | def especies():
32 | adjetivos = ('Habilis', 'Erectus', 'Neanderthalensis', 'Sapiens')
33 | return ('Australopiteco',) + tuple(f'Homo {adj}' for adj in adjetivos)
34 |
35 | @classmethod
36 | def is_evoluido(cls):
37 | return cls.especie == cls.especies()[-1]
38 |
39 |
40 | class Neanderthal(Humano):
41 | especie = Humano.especies()[-2]
42 |
43 | @property
44 | def inteligente(self):
45 | return False
46 |
47 |
48 | class HomoSapiens(Humano):
49 | especie = Humano.especies()[-1]
50 |
51 | @property
52 | def inteligente(self):
53 | return True
54 |
55 |
56 | if __name__ == '__main__':
57 | anonimo = Humano('John Doe')
58 |
59 | try:
60 | print(anonimo.inteligente)
61 | except NotImplementedError:
62 | print('propriedade abstrata')
63 |
64 | jose = HomoSapiens('José')
65 | print('{} da classe {}, inteligente: {}'
66 | .format(jose.nome, jose.__class__.__name__, jose.inteligente))
67 | grogn = Neanderthal('Grogn')
68 | print('{} da classe {}, inteligente: {}'
69 | .format(grogn.nome, grogn.__class__.__name__, grogn.inteligente))
70 |
--------------------------------------------------------------------------------
/poo_avancada/evolucao_v6.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | from abc import ABCMeta, abstractproperty
3 |
4 |
5 | class Humano(metaclass=ABCMeta):
6 | # atributo de classe
7 | especie = 'Homo Sapiens'
8 |
9 | def __init__(self, nome):
10 | self.nome = nome
11 | self._idade = None
12 |
13 | @abstractproperty
14 | def inteligente(self):
15 | pass
16 |
17 | @property
18 | def idade(self):
19 | return self._idade
20 |
21 | @idade.setter
22 | def idade(self, idade):
23 | if idade < 0:
24 | raise ValueError('Idade deve ser um número positivo!')
25 | self._idade = idade
26 |
27 | def das_cavernas(self):
28 | self.especie = 'Homo Neanderthalensis'
29 | return self
30 |
31 | @staticmethod
32 | def especies():
33 | adjetivos = ('Habilis', 'Erectus', 'Neanderthalensis', 'Sapiens')
34 | return ('Australopiteco',) + tuple(f'Homo {adj}' for adj in adjetivos)
35 |
36 | @classmethod
37 | def is_evoluido(cls):
38 | return cls.especie == cls.especies()[-1]
39 |
40 |
41 | class Neanderthal(Humano):
42 | especie = Humano.especies()[-2]
43 |
44 | @property
45 | def inteligente(self):
46 | return False
47 |
48 |
49 | class HomoSapiens(Humano):
50 | especie = Humano.especies()[-1]
51 |
52 | @property
53 | def inteligente(self):
54 | return True
55 |
56 |
57 | if __name__ == '__main__':
58 |
59 | # try:
60 | # anonimo = Humano('John Doe')
61 | # print(anonimo.inteligente)
62 | # except TypeError:
63 | # print('classe abstrata')
64 |
65 | jose = HomoSapiens('José')
66 | print('{} da classe {}, inteligente: {}'
67 | .format(jose.nome, jose.__class__.__name__, jose.inteligente))
68 | grogn = Neanderthal('Grogn')
69 | print('{} da classe {}, inteligente: {}'
70 | .format(grogn.nome, grogn.__class__.__name__, grogn.inteligente))
71 |
--------------------------------------------------------------------------------
/poo_avancada/iterator.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | class RGB:
3 | def __init__(self):
4 | self.cores = ['red', 'green', 'blue'][::-1]
5 |
6 | def __iter__(self):
7 | return self
8 |
9 | def __next__(self):
10 | try:
11 | return self.cores.pop()
12 | except IndexError:
13 | raise StopIteration()
14 |
15 |
16 | if __name__ == '__main__':
17 | cores = RGB()
18 | print(next(cores))
19 | print(next(cores))
20 | print(next(cores))
21 |
22 | try:
23 | print(next(cores))
24 | except StopIteration:
25 | print('Acabou!')
26 |
27 | for cor in RGB():
28 | print(cor)
29 |
--------------------------------------------------------------------------------
/poo_avancada/mixins.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | class HtmlToStringMixin:
3 | def __str__(self):
4 | # Conversão para HTML
5 | html = super().__str__() \
6 | .replace('(', '(') \
7 | .replace(')', ')')
8 | return f'{html}'
9 |
10 |
11 | class Pessoa:
12 | def __init__(self, nome):
13 | self.nome = nome
14 |
15 | def __str__(self):
16 | return self.nome
17 |
18 |
19 | class Animal:
20 | def __init__(self, nome, pet=True):
21 | self.nome = nome
22 | self.pet = pet
23 |
24 | def __str__(self):
25 | return self.nome + ' (pet)' if self.pet else ''
26 |
27 |
28 | class PessoaHtml(HtmlToStringMixin, Pessoa):
29 | pass
30 |
31 |
32 | class AnimalHtml(HtmlToStringMixin, Animal):
33 | pass
34 |
35 |
36 | if __name__ == '__main__':
37 | p1 = Pessoa('Maria Eduarda')
38 | print(p1)
39 |
40 | p2 = PessoaHtml('Roberto Carlos')
41 | print(p2)
42 |
43 | toto = AnimalHtml('Totó')
44 | print(toto)
45 |
--------------------------------------------------------------------------------
/poo_avancada/multipla.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | class Animal:
3 | @property
4 | def capacidades(self):
5 | return ('dormir', 'comer', 'beber')
6 |
7 |
8 | class Homem(Animal):
9 | @property
10 | def capacidades(self):
11 | return super().capacidades + ('amar', 'falar', 'estudar')
12 |
13 |
14 | class Aranha(Animal):
15 | @property
16 | def capacidades(self):
17 | return super().capacidades + ('fazer teia', 'andar pelas paredes')
18 |
19 |
20 | class HomemAranha(Homem, Aranha):
21 | @property
22 | def capacidades(self):
23 | return super().capacidades + \
24 | ('bater em bandidos', 'atirar teias entre prédios')
25 |
26 |
27 | if __name__ == '__main__':
28 | john = Homem()
29 | print(f'John: {john.capacidades}')
30 |
31 | aranha = Aranha()
32 | print(f'Aranha: {aranha.capacidades}')
33 |
34 | peter = HomemAranha()
35 | print(f'Peter Parker: {peter.capacidades}')
36 |
--------------------------------------------------------------------------------
/programacao_funcional/closure.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | def multiplicar(x):
3 | def calcular(y):
4 | return x * y
5 | return calcular
6 |
7 |
8 | if __name__ == '__main__':
9 | dobro = multiplicar(2)
10 | triplo = multiplicar(3)
11 | print(dobro)
12 | print(triplo)
13 | print(f'O triplo de 3 é {triplo(3)}')
14 | print(f'O dobro de 7 é {dobro(7)}')
15 |
--------------------------------------------------------------------------------
/programacao_funcional/desafio_mdc.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | def mdc(numeros):
3 | def calc(divisor):
4 | return divisor if sum(map(lambda x: x % divisor, numeros)) == 0 \
5 | else calc(divisor - 1)
6 | return calc(min(numeros))
7 |
8 |
9 | if __name__ == '__main__':
10 | print(mdc([21, 7])) # 7
11 | print(mdc([125, 40])) # 5
12 | print(mdc([9, 564, 66, 3])) # 3
13 | print(mdc([55, 22])) # 11
14 | print(mdc([15, 150])) # 15
15 | print(mdc([7, 9])) # 1
16 |
--------------------------------------------------------------------------------
/programacao_funcional/fatorial_recursivo.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | def fatorial(n):
3 | return n * (fatorial(n - 1) if (n - 1) > 1 else 1)
4 |
5 |
6 | if __name__ == '__main__':
7 | print(f'10! = {fatorial(10)}')
8 |
9 | # 6 semanas em sugundos é igual a 10!
10 | print(6 * 7 * 24 * 60 * 60)
11 |
--------------------------------------------------------------------------------
/programacao_funcional/filter.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 |
3 | pessoas = [
4 | {'nome': 'Pedro', 'idade': 11},
5 | {'nome': 'Mariana', 'idade': 18},
6 | {'nome': 'Arthur', 'idade': 26},
7 | {'nome': 'Rebeca', 'idade': 6},
8 | {'nome': 'Tiago', 'idade': 19},
9 | {'nome': 'Gabriela', 'idade': 17},
10 | ]
11 |
12 | menores = filter(lambda p: p['idade'] < 18, pessoas)
13 | print(list(menores))
14 |
15 | nomes_grandes = filter(lambda p: len(p['nome']) >= 7, pessoas)
16 | print(tuple(nomes_grandes))
17 |
--------------------------------------------------------------------------------
/programacao_funcional/funcao_alta_ordem.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | from funcao_primeira_classe import dobro, quadrado
3 |
4 |
5 | def processar(titulo, lista, funcao):
6 | print(f'Processando: {titulo}')
7 | for i in lista:
8 | print(i, '=>', funcao(i))
9 |
10 |
11 | if __name__ == '__main__':
12 | processar('Dobros de 1 a 10', range(1, 11), dobro)
13 | processar('Quadrados de 1 a 10', range(1, 11), quadrado)
14 |
--------------------------------------------------------------------------------
/programacao_funcional/funcao_primeira_classe.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | def dobro(x):
3 | return x * 2
4 |
5 |
6 | def quadrado(x):
7 | return x ** 2
8 |
9 |
10 | if __name__ == '__main__':
11 | d = dobro
12 | print(d(5))
13 |
14 | q = quadrado
15 | print(q(5))
16 |
17 | # Retornar alternadamente o dobro ou quadrado nos números de 1 a 10
18 | funcs = [dobro, quadrado] * 5
19 | for func, numero in zip(funcs, range(1, 11)):
20 | print(f'O {func.__name__} de {numero} é {func(numero)}')
21 |
--------------------------------------------------------------------------------
/programacao_funcional/funcoes_imutabilidade_v1.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | from functools import reduce
3 | from operator import add
4 |
5 | valores = [30, 10, 25, 70, 100, 94]
6 |
7 | print(sorted(valores))
8 | print(valores)
9 |
10 | # valores.sort()
11 | # print(valores)
12 | print(min(valores))
13 | print(max(valores))
14 | print(sum(valores))
15 | print(reduce(add, valores))
16 | print(reversed(valores))
17 | print(list(reversed(valores)))
18 | print(valores)
19 |
20 | # valores.reverse()
21 | # print(valores)
22 |
--------------------------------------------------------------------------------
/programacao_funcional/funcoes_imutabilidade_v2.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | from functools import reduce
3 | from operator import add
4 |
5 | valores = (30, 10, 25, 70, 100, 94)
6 |
7 | print(sorted(valores))
8 | print(valores)
9 |
10 | print(min(valores))
11 | print(max(valores))
12 | print(sum(valores))
13 | print(reduce(add, valores))
14 | print(reversed(valores))
15 | print(tuple(reversed(valores)))
16 | print(valores)
17 |
--------------------------------------------------------------------------------
/programacao_funcional/funcoes_lambda.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | compras = (
3 | {'quantidade': 2, 'preco': 10},
4 | {'quantidade': 3, 'preco': 20},
5 | {'quantidade': 5, 'preco': 14},
6 | )
7 |
8 | totais = tuple(
9 | map(
10 | lambda compra: compra['quantidade'] * compra['preco'],
11 | compras
12 | )
13 | )
14 |
15 | print('Preços totais:', totais)
16 | print('Total geral:', sum(totais))
17 |
--------------------------------------------------------------------------------
/programacao_funcional/funcoes_lambda_alternativa.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | compras = (
3 | {'quantidade': 2, 'preco': 10},
4 | {'quantidade': 3, 'preco': 20},
5 | {'quantidade': 5, 'preco': 14},
6 | )
7 |
8 |
9 | def calc_preco_total(compra):
10 | return compra['quantidade'] * compra['preco']
11 |
12 |
13 | totais = tuple(map(calc_preco_total, compras))
14 |
15 | print('Preços totais:', totais)
16 | print('Total geral:', sum(totais))
17 |
--------------------------------------------------------------------------------
/programacao_funcional/generators_v1.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | def cores_arco_iris():
3 | yield 'vermelho'
4 | yield 'laranja'
5 | yield 'amarelo'
6 | yield 'verde'
7 | yield 'azul'
8 | yield 'índigo'
9 | yield 'violeta'
10 |
11 |
12 | if __name__ == '__main__':
13 | generator = cores_arco_iris()
14 | print(type(generator))
15 | while True:
16 | print(next(generator))
17 |
--------------------------------------------------------------------------------
/programacao_funcional/generators_v2.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | from generators_v1 import cores_arco_iris
3 |
4 | if __name__ == '__main__':
5 | generator = cores_arco_iris()
6 | for cor in generator:
7 | print(cor)
8 | print('Fim!')
9 |
--------------------------------------------------------------------------------
/programacao_funcional/generators_v3.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | def sequence():
3 | num = 0
4 | while True:
5 | num += 1
6 | yield num
7 |
8 |
9 | if __name__ == '__main__':
10 | seq = sequence()
11 |
12 | print(next(seq))
13 | print(next(seq))
14 | print(next(seq))
15 | print(next(seq))
16 | print(next(seq))
17 | print(next(seq))
18 | print(next(seq))
19 | print(next(seq))
20 | print(next(seq))
21 |
--------------------------------------------------------------------------------
/programacao_funcional/imperativo.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | from locale import setlocale, LC_ALL
3 | from calendar import mdays, month_name
4 |
5 | # Português do Brasil
6 | setlocale(LC_ALL, 'pt_BR')
7 |
8 | # Listar todos os meses do ano com 31 dias
9 | print('Meses com 31 dias:')
10 | for mes in range(1, 13):
11 | if mdays[mes] == 31:
12 | print(f'- {month_name[mes]}')
13 |
--------------------------------------------------------------------------------
/programacao_funcional/implementando_map_v1.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | # Implementação simplificada do map
3 |
4 |
5 | def mapear(funcao, lista):
6 | for elemento in lista:
7 | yield funcao(elemento)
8 |
9 |
10 | if __name__ == "__main__":
11 | resultado = mapear(lambda x: x ** 2, [2, 3, 4])
12 | print(list(resultado))
13 |
--------------------------------------------------------------------------------
/programacao_funcional/implementando_map_v2.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | # Implementação simplificada do map
3 |
4 |
5 | def mapear(funcao, lista):
6 | return (funcao(elemento) for elemento in lista)
7 |
8 |
9 | if __name__ == "__main__":
10 | resultado = mapear(lambda x: x ** 2, [2, 3, 4])
11 | print(tuple(resultado))
12 |
--------------------------------------------------------------------------------
/programacao_funcional/imutabilidade_v1.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | from locale import setlocale, LC_ALL
3 | from calendar import mdays, month_name
4 | from functools import reduce
5 |
6 | # Português do Brasil
7 | setlocale(LC_ALL, 'pt_BR')
8 |
9 | # Listar todos os meses do ano com 31 dias
10 | # 1. (filter) pegar os indices de todos os meses com 31 dias 1, 3, 5...
11 | # 2. (map) transformar os índices em nome
12 | # 3. (reduce) juntar tudo para imprimir
13 | meses_31 = filter(lambda mes: mdays[mes] == 31, range(1, 13))
14 | meses_nomes = map(lambda mes: month_name[mes], meses_31)
15 | juntar_meses = reduce(lambda todos, nome_mes: f'{todos}\n- {nome_mes}',
16 | meses_nomes, 'Meses com 31 dias:')
17 |
18 | print(juntar_meses)
19 |
20 | print(
21 | reduce(
22 | lambda todos, nome_mes: f'{todos}\n- {nome_mes}',
23 | map(
24 | lambda mes: month_name[mes],
25 | filter(
26 | lambda mes: mdays[mes] == 31,
27 | range(1, 13)
28 | )
29 | ),
30 | 'Meses com 31 dias:'
31 | )
32 | )
33 |
--------------------------------------------------------------------------------
/programacao_funcional/imutabilidade_v2.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | from locale import setlocale, LC_ALL
3 | from calendar import mdays, month_name
4 | from functools import reduce
5 |
6 | # Português do Brasil
7 | setlocale(LC_ALL, 'pt_BR')
8 |
9 |
10 | def mes_com_31(mes):
11 | return mdays[mes] == 31
12 |
13 |
14 | def get_nome_mes(mes):
15 | return month_name[mes]
16 |
17 |
18 | def juntar_meses(todos, nome_mes):
19 | return f'{todos}\n- {nome_mes}'
20 |
21 |
22 | print(reduce(juntar_meses,
23 | map(get_nome_mes, filter(mes_com_31, range(1, 13))),
24 | 'Meses com 31 dias:'))
25 |
--------------------------------------------------------------------------------
/programacao_funcional/map.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 |
3 | lista_1 = [1, 2, 3]
4 | dobro = map(lambda x: x * 2, lista_1)
5 | print(list(dobro))
6 |
7 | lista_2 = [
8 | {'nome': 'João', 'idade': 31},
9 | {'nome': 'Maria', 'idade': 37},
10 | {'nome': 'José', 'idade': 26}
11 | ]
12 | so_nomes = map(lambda p: p['nome'], lista_2)
13 | print(list(so_nomes))
14 |
15 | so_idades = map(lambda p: p['idade'], lista_2)
16 | print(sum(so_idades))
17 |
18 | # Desafio: usando map retorne frases ' tem anos.'
19 | frases = map(lambda p: f'{p["nome"]} tem {p["idade"]} anos.', lista_2)
20 | print(list(frases))
21 |
--------------------------------------------------------------------------------
/programacao_funcional/reduce.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python3
2 | from functools import reduce
3 |
4 | pessoas = [
5 | {'nome': 'Pedro', 'idade': 11},
6 | {'nome': 'Mariana', 'idade': 18},
7 | {'nome': 'Arthur', 'idade': 26},
8 | {'nome': 'Rebeca', 'idade': 6},
9 | {'nome': 'Tiago', 'idade': 19},
10 | {'nome': 'Gabriela', 'idade': 17},
11 | ]
12 |
13 | so_idades = map(lambda p: p['idade'], pessoas)
14 | menores = filter(lambda idade: idade < 18, so_idades)
15 | soma_idades = reduce(lambda idades, idade: idades + idade, menores, 0)
16 | print(soma_idades)
17 |
--------------------------------------------------------------------------------
/projeto-teste/.gitignore:
--------------------------------------------------------------------------------
1 | .venv
--------------------------------------------------------------------------------
/projeto-teste/requirements.txt:
--------------------------------------------------------------------------------
1 | certifi==2019.6.16
2 | chardet==3.0.4
3 | idna==2.7
4 | requests==2.19.1
5 | urllib3==1.23
6 |
--------------------------------------------------------------------------------