Python Tutorial - Python for Beginners [Full Course]

Python Tutorial - Python for Beginners [Full Course]

SUBTITLE'S INFO:

Language: Portuguese

Type: Human

Number of phrases: 4530

Number of words: 50061

Number of symbols: 221140

DOWNLOAD SUBTITLES:

DOWNLOAD AUDIO AND VIDEO:

SUBTITLES:

Subtitles prepared by human
00:00
Olá, meu nome é Mosh e vou ser seu instrutor neste curso de Python. Neste curso, você aprenderá tudo que precisa para começar a programar em Python. O Python é uma das linguagens de programação mais populares, e todos os dias as pessoas o usam para fazer coisas legais como automação, eles usam isso em AI, assim como criação de aplicativos e sites como o Instagram e o Dropbox. Então, se você está procurando para um trabalho, o Python é para você. Neste curso vou te ensinar tudo você precisa começar com o Python. Nós vamos falar sobre todos os principais conceitos em Python, e depois vamos construir três projetos em Python juntos. Aqui está o primeiro projeto que vamos construir. Nós vamos aprender como criar este lindo site para uma mercearia imaginária. Aqui na página inicial, podemos ver todos dos produtos na loja, e também temos uma área de administração para gerenciar o estoque. Nós vamos construir isso usando um framework popular em Python chamado Django. Agora, se você nunca construiu um site antes, não se preocupe, vou ensinar tudo do zero. Você também aprenderá a usar o Python em aprendizado de máquina ou inteligência artificial. Então você aprenderá a escrever uma programação Python que irá prever a música que as pessoas gostam com base em seu perfil. Assim como o YouTube
01:04
recomenda vídeos com base nos vídeos que você assistiu antes. Eu também vou te mostrar python para automatizar tarefas repetitivas e chatas que desperdiçam seu tempo. Você vai escrever um programa em Python que irá processar milhares de planilhas em menos de um segundo. Eu desenhei este curso de Python para quem quer aprender Python. Se você é um iniciante, não se preocupe, eu vou segurar sua mão durante todo este curso. Você não é muito velho nem muito jovem, e o Python é super fácil de aprender. Você pode escrever seu primeiro Programa Python em literalmente segundos. Além disso, vou lhe dar bastante de exercícios para ajudá-lo a construir sua confiança escrevendo programas legais em Python. Meu nome é Mosh, sou engenheiro de software com duas décadas de experiência e eu ensinei mais de 3 milhões de pessoas a codificar. Estou super animada por te ensinar Python neste curso. Então eu espero que você fique por aqui e aprenda isso poderosa linguagem de programação. Neste tutorial vou mostrar como baixar e instale o Python no seu computador. Então a primeira coisa que eu quero que você faça é abrir o seu navegador e vá para o Python .org. Nesta página, clique em downloads,
02:08
aqui você pode ver a versão mais recente do Python atualmente, no momento da gravação deste vídeo a última versão é python 3.7.2. As chances são no futuro, quando você está assistindo este tutorial, há um novo versão do Python disponível, não se preocupe, todos os materiais que você vai aprender neste curso também será aplicado à versão mais recente do Python. Então vamos em frente e baixe o Python 3, tudo bem agora, olhe para sua pasta de downloads, aqui, devemos ter o instalador do Python 3 basta clicar duas vezes, se você estiver no Windows você vai ver esta caixa de seleção aqui, adicione o Python para python, isso é realmente importante, certifique-se de marcar esta caixa, caso contrário você não será capaz de siga este tutorial. Se você estiver em um Mac, você vai ver um instalador como este, com esse assistente de configuração vamos instalar o Python 3 no nosso computador. Então, basta clicar em continuar e, novamente, e novamente, e concordar com o contrato de licença, e instalá-lo, isso vai demorar alguns segundos, então eu vou para pausar a gravação.
03:12
Tudo bem, nós instalamos com sucesso o Python 3 em nosso computador. Vamos fechar isso. Tudo bem, em seguida, precisamos instalar um editor de código, nós vemos um editor de código para escrever nosso código, assim como como usamos o Microsoft Word para escrever documentos, usamos um editor de código para escrever código. Agora há tantos editores de código por aí, o que vou mostrar neste tutorial é PyCharm. Esse é um dos editores de código mais populares para escrever código Python. Você pode obtê-lo de jetbrains.com / pycharm. Agora mais precisamente pycharm é considerado um IDE, que é curto para desenvolvimento integrado meio Ambiente. E isso é basicamente um editor de código em esteróides, Ele tem alguns recursos adicionais que facilitam a gravação de código. assim vamos em frente e baixe o PyCharm. Agora aqui no página de download, você pode ver duas versões do PyCharm, uma é a adição profissional que tem recursos adicionais e você tem que pagar por eles. O outro é o edição comunitária, que é absolutamente gratuita, e é isso que vamos usar neste tutorial. Então, vá em frente e faça o download também.
04:16
Agora, mais uma vez, olhe para sua pasta de downloads, mais uma vez você deve ter pycharm então clique duas vezes isso, agora se você é no Windows, você verá um assistente de instalação, clique em next, next, next até você instalar o pycharm. Se você está no Mac, você precisa arrastar e soltar este ícone na pasta de aplicativos, então arraste e solte tudo bem, agora vamos clicar duas vezes para executá-lo, a primeira vez que executarmos o pycharm, vamos obter esse aviso, porque este é um aplicativo que baixamos da internet. Então vamos em frente e abri-lo Em seguida, você verá essa caixa de diálogo para importar algumas configurações. Deixe isso para não importe configurações, isso realmente não importa. OK, Nesta página, selecione Eu nunca usei PyCharm você pode ver alguma palavra-chave atalhos que podem ser úteis no futuro, basta aceitar isso e, na parte inferior, clique no botão seguinte. E depois vem novamente, mais uma vez e, finalmente, começar a usar o pycharm. Então aqui está a página principal do PyCharm toda vez que você abre clique em criar novo projeto,
05:20
este é o local do nosso projeto, vamos chamar nosso projeto Hello Mundo. Agora antes de clicar e criar, expanda este item aqui, certifique-se de que o interpretador base esteja configurado para Python 3. O interpretador Python é basicamente um programa que sabe como executar o código Python, ele saberá interpretar ou traduzir instruções do Python em instruções que um computador possa entender. Agora, os computadores Mac, por padrão, vêm com um instalação do Python, que é o Python 2, é considerado legado o que significa que não é mais mantido ou suportado. Então, mais cedo nós baixamos Python 3, certifique-se de que isso esteja definido como Python 3, se não desta lista, selecione Python 3.7. Tudo bem, agora vamos em frente e criar este projeto, Agora clique aqui com o botão direito Pasta Hello World e vá para o novo Arquivo Python, chame este arquivo app.py. Então, por convenção, todos os arquivos Python devem ter este
06:28
extensão py. Tudo bem, vamos em frente Agora vamos recolher este painel do projeto clicando aqui e escreva nosso primeiro programa python. Simplesmente digite print, pr int, todos em minúsculas, abra e feche parênteses, e dentro desses parênteses, adicione citações que pode usar aspas simples ou aspas duplas, agora Entre os códigos, escreva seu nome. Eu sou Mosh Hamedani, então aqui, então esta é sua primeira programação em Python. Com este pedaço de código você pode imprimir seu nome na tela. Agora, para rodar isso, vá na parte superior, no menu de execução, clique em executar, Observe também que há um atalho associado a este comando, quando Eu programo sempre uso atalhos porque isso aumenta minha produtividade. Então, aqui em um computador Mac, o atalho é controle, opção e R. No Windows é diferente. Então vamos fazer isso, agora está perguntando onde você quer rodar isso, clique em app, abaixo, você deve ver esta pequena janela de terminal, esta
07:32
é uma pequena janela para o nosso programa, então aqui você pode ver nossos resultados para saída para o nosso programa. No futuro, à medida que você aprende mais sobre Python, capaz de criar aplicativos que tenham uma interface gráfica com o usuário, ou pegajosos. Isso é um pouco complicado, então por enquanto vamos usar esse pequeno janela do terminal para ver os resultados do nosso programa. Então, como você pode ver meu nome é impresso aqui, agora que você imprime o código, essa janela pode atrapalhar sempre redimensionar ou minimizar itty colocando isso ícone aqui, então este foi o nosso primeiro programa python. Agora Se você não viu o resultado que mostrei neste vídeo, use a caixa de comentários abaixo e diga-me qual erro você encontrou, eu farei o meu melhor para ajudá-lo a seguir em frente. Neste tutorial em Python, vamos levar este programa para o próximo nível e torná-lo mais interessante. Então, vou mostrar como desenhar um pêlo de cachorro. Agora como parte de Neste tutorial, você aprenderá como o código Python é executado e também aprenderá sobre alguns termos de programação. Então pressione enter e na linha 2 escrever outra declaração de impressão, para imprimir, abrir e fechar parêntese, adicione uma cotação, agora aqui você quer desenhar um cachorro.
08:40
Então, adicione um o, que é a cabeça do nosso cachorro, seguido por 4 hífens. Então esse é o corpo. tudo bem, agora mais uma vez outra declaração de impressão com cotações, agora precisamos desenhar as pernas. Então adicione um espaço. Siga-o por 4 barras verticais. Então, assim, então aqui está um pequeno ponto imaginário. Agora vamos execute este programa e veja o que obtemos. Então, no canto superior direito, você verá este botão de reprodução, clique aí, lá vai você, então nós temos o nosso nome e logo abaixo temos o nosso cachorro imaginário. Agora o que você precisa entender aqui, é que nosso código python é executado linha por linha do topo. Então, mais cedo eu te falei sobre o interpretador Python esse é o programa que sabe traduzir ou interpretar nosso código Python em instruções que um computador pode entender. Então quando nós rodamos este programa clicando neste programa aqui, intérprete python começa a executar ou executar o nosso programa linha por linha a partir do topo. Então primeiro ele executa a linha 1,
09:44
depois, passa para a linha 2 e assim por diante. Então é assim que python programas são executados. Agora deixe-me mostrar uma coisa legal. Vamos adicionar outra declaração impressa, com citações agora entre as citações, adicione uma estrela ou um asterisco, como isto. Agora, após a citação e antes dos parênteses, adicione um espaço, mais uma vez, adicione um asterisco, espaço, 10. O que está acontecendo aqui? Bem, em qualquer lugar temos citações como aqui ou aqui estamos definindo uma string, uma string é um termo de programação que significa uma série de personagens então aqui nós temos uma string, nós também temos uma string na linha 3, assim como a linha 2 e a linha 1. Agora, aqui, estamos multiplicando a string por número 10. Então, esse é o operador de multiplicação, assim como a multiplicação operador temos em matemática. Então, com esse pedaço de código, podemos desenhe 10 asteriscos no terminal, deixe-me mostrar-lhe. Então vamos rodar esse programa mais uma vez, lá vai você. Então nós temos 10
10:48
asteriscos. Agora o que temos aqui, este pedaço de código aqui, é chamado uma expressão. Uma expressão é um pedaço de código que produz um valor. Então, quando o interpretador Python tenta executar a linha 4, primeiro ele avaliará o código que colocamos entre parênteses, para que pudéssemos avaliar nossas expressões Nossa expressão produzirá 10 asteriscos e depois esses asteriscos serão impressos no terminal. Agora como um exercício você pode usar estas instruções de impressão para desenhar outra forma, você pode desenhar um coração, um bola, o que você quiser. Eu vou te ver no próximo tutorial. Uma das perguntas que recebo muito no meu canal é Quanto tempo leva para aprender Python e se tornar pronto para o trabalho? Bem, não há um único responda. Isso realmente depende de você e quanto esforço e compromisso você quer colocar nisso. Mas eu diria que se você passar 2 horas todos os dias consistentemente, após cerca de 3 meses você deve ser capaz de escrever programas básicos em python, mas honestamente, isso não lhe dá trabalho. Para conseguir um emprego, você precisa se especializar em uma área,
11:52
o que você quer usar python para? Você quer construir aplicações web ou aplicativos de desktop? Ou você quer usá-lo em aprendizado de máquina e inteligência artificial? Então, o que você quer fazer, você precisa fazer cursos adicionais. Por exemplo, se você quiser se tornar um desenvolvedor da Web, além de aprender Python, você também deve aprender sobre html, alguns css, alguns JavaScript e Django, que é um framework popular em Python para a criação de aplicativos da web. Aprender todas essas coisas te levaria outra 6 meses, então no total você precisa de 9 a 12 meses para se tornar trabalho pronto. Nesse ponto, você pode obter um trabalho de desenvolvedor júnior com um salário de cerca de 50-60 mil dólares por ano. Agora, enquanto você trabalha mais como você faz mais projetos Python, seu currículo começa a construir e você pode pedir US $ 100.000 por ano, ou US $ 120.000 um ano, dependendo de onde você está, qual empresa, qual área geográfica, isso realmente depende, não há uma resposta única. Então você está animado para aprende Python e começa nessa carreira? Se você é, eu encorajaria você para fazer um compromisso e gastar 2 horas todos os dias praticando
12:56
python. E use a caixa de comentários abaixo e deixe-me saber por que você está aprendendo Python, o que você quer fazer com isso? Qual é o teu emprego de sonho? Eu adoraria ouvir sua história. Neste tutorial em Python, você aprenderá sobre variáveis, que são um dos mais fundamentais conceitos em programação, eles não são específicos para o Python, eles existem em praticamente todas as linguagens de programação existentes. Nós usamos variáveis para armazenar temporariamente dados na memória de um computador. Aqui está um exemplo vamos digitar price = 10, quando o Python intérprete executa este código, ele irá alocar alguma memória, então ele irá armazenar o número 10 em que a memória e, finalmente, ele irá anexar este etiqueta de preço nesse local de memória. Como um metahor imagine que tenhamos uma caixa. Naquela caixa, temos o número 10 e preço é o rótulo que colocamos na caixa. Agora podemos usar esse rótulo em qualquer lugar em nosso programa para acessar o valor que temos nessa caixa. Esta é uma explicação muito simplificada. Então agora, vamos preço de impressão no terminal. Imprimir, agora desta vez não vamos adicione citações, porque se colocarmos aspas aqui, veremos o texto
14:04
preço no terminal. Agora o valor da variável de preço. Então, coloque em cotações e digite preço, Agora, vamos rodar este programa mais uma vez, lá vai você. Então nós vemos 10, no terminal. Então é assim que definimos variáveis, nós começar com um identificador que é o nome da nossa variável, então, um sinal de igual e, finalmente, um valor. Agora, mais precisamente, quando este número 10 está prestes a ser armazenado na memória, primeiro será é convertido para este binário para apresentação. Então esse número 10, está no sistema decimal que tem todos os dígitos de 0 a 9. Computadores não entendem todos esses dígitos, eles só entendem 0s e 1s. Então, quando nós armazenamos o número 10 na memória do computador primeiro ele será convertido em sua representação binária que será um monte de 0 e 1, como 001, 001, seja qual for Eu não sei. Em seguida, ele será armazenado na memória do computador. Assim, vamos levar este programa para o próximo nível. Na segunda linha podemos atualizar o valor dessa variável de preço, para que possamos redefini-la
15:08
para um novo valor como 20, agora quando executamos nosso programa, nós deveríamos ver 20, porque como eu disse antes do intérprete Python executar nossa código linha por linha a partir do topo. Então, primeiro vamos definir o preço para 10, então redefinimos para 20, e finalmente nós imprimi-lo no terminal, vamos executar o terminal, lá vai você, então, nós vemos 20 aqui, ok? Agora estes números que temos aqui são números inteiros sem um ponto decimal. Na programação, nos referimos a esses números como números inteiros. Mas o inteiro é um número sem um ponto decimal. Nós também podemos usar números com um ponto decimal, por exemplo, na linha 2, podemos definir outra variável chamada rating e configurá-lo para número 4.9. Agora, na programação, nos referimos a esse tipo de número um número de ponto flutuante de float para breve. Então nós temos inteiros e flutua. Podemos também definir uma variável e definir a uma string, por exemplo, nome é igual a Mosh, também temos outro tipo de valor que é chamado booleano,
16:12
o que pode ser verdadeiro ou falso. Eles são linha sim e não em inglês. Aqui está um exemplo, vou definir uma variável, é sublinhado publicado por isso usamos um sublinhado para separar várias palavras em nosso nome de variáveis. Nós configuramos isso para verdadeiro ou falso. Esses são valores booleanos. Agora note que o Python é um caso linguagem sensível, o que significa que é sensível a letras minúsculas e maiúsculas. Então, quando definimos variáveis, devemos sempre usar letras minúsculas, mas aqui false e true são palavras-chave especiais no linguagem, por isso, se soletrarmos com um f minúsculo, o Python não entende isso. Você pode ver que temos um sublinhado vermelho aqui, o que indica um erro. Certifique-se de soletrar isso com um F maiúsculo, ou se você quiser definir isso como verdadeiro, certifique-se de que o T é o capital, então neste programa, você está armazenando valores simples na memória do nosso computador. Simples valores podem ser números, que podem ser inteiros ou flutuantes ou eles podem ser cordas ou booleanos. Mas em Python
17:16
Também podemos armazenar valores complexos, como listas e valores. E é isso que eu vou te mostrar no futuro. Então, antes de ir mais longe, eu quero você fazer um pequeno exercício. Imagine que vamos escrever um programa para um hospital. Então, nós verificamos um paciente chamado John Smith. Ele é 20 anos e é um novo paciente. Eu quero que você defina 3 variáveis ​​aqui, por seu nome, sua idade e outra variável pois se é um paciente novo ou existente. Então pause o vídeo e gaste um minuto neste exercício. Quando terminar, volte, continue e veja minha solução. Tudo bem, então aqui precisamos três variáveis, a primeira é o nome do paciente, nós definimos isso para John Smith. Nós também podemos chame este nome completo, estes são ambos nomes válidos para nossas variáveis. A segunda variável é para a idade do nosso paciente. Então idade é 20 e, finalmente, precisamos de uma variável para dizer se isso é um novo ou paciente existente. É aí que podemos usar um valor booleano. Então, nós definimos uma variável, é nova e
18:20
nós definimos para true. Então você aprendeu a imprimir mensagens na janela do terminal. Neste tutorial, vou mostrar como receber entrada do usuário. Então, vamos escrever um pequeno programa que pede o nome do usuário e, em seguida, imprimiremos uma mensagem de saudação personalizada para esse usuário. Então, ao invés de imprimir, vamos usar entrada. Agora, essas duas entradas e impressões são funções construídas no Python. Como uma metáfora pensa do controle remoto da TV. Neste controle remoto, temos um monte de botões, estas são as funções embutidas na sua tv, você pode ligá-lo, desligue-o, mude o volume e assim por diante. Em Python também temos funções para tarefas comuns, como imprimir mensagens, receber entrada, e assim por diante. Então, vamos usar a função de entrada, agora sempre que tem esses parênteses, vamos dizer que estamos chamando ou executando essa função, é como pressionar um botão em um controle remoto. Então onde vai chamar a função de entrada e entre parênteses
19:24
queremos adicionar uma string para imprimir algo no terminal, qual é o seu nome? Com um ponto de interrogação seguido por um espaço. Você vai ver porque em um segundo. Então esta função de entrada imprimirá esta mensagem no terminal e esperará que o usuário insira um valor. O que quer que o usuário insira essa função de entrada Retorna. Então agora podemos obter esse valor e armazená-lo na memória usando uma variável. Então nós pegamos o resultado e colocamos em uma variável chamada nome. OK? Agora na segunda linha nós queremos imprimir uma mensagem como Hi John ou Hi Mosh ou qualquer outra coisa, então, imprimir, citações Oi com um espaço, Agora, após a cotação, queremos imprimir dinamicamente o que temos na variável de nome. Então nós tivemos um sinal de mais e, em seguida, nome. Então aqui nós temos Oi, que é uma string, estamos concatenando ou combinando a string com outra string, é isso que temos na variável de nome. Então aqui está outro exemplo de
20:28
uma expressão. Lembre-se que é uma expressão? É um pedaço de código que usa um valor. Então essa expressão concatena ou combina 2 cordas. Vamos rodar esse programa e ver o que acontece. Então corra Ok, aqui está uma pergunta, qual é o seu nome? Mosh Agora note que anteriormente nós adicionamos um espaço após o ponto de interrogação, nós fiz isso, então aqui na janela do terminal o cursor está separado do ponto de interrogação, caso contrário, seria tão próximo. Então vamos digitar seja o que for aqui, mais entrar, agora recebemos esta mensagem, Oi, Mosh. Ora aqui está um pequeno exercício para você. Eu quero que você estenda este programa e faça duas perguntas. Primeiro todo o nome da pessoa e depois sua cor favorita. E então imprima uma mensagem como Mosh gosta azul. Então pause o vídeo, faça este exercício e depois volte e continue assistindo. Tudo bem, então aqui está a primeira pergunta logo depois disso, todas as funções de entrada mais uma vez, desta vez vamos fazer uma pergunta diferente. Qual é a sua cor preferida? Agora, obtemos o novo valor e o armazenamos na variável
21:36
chamado cor, ou você poderia chamá-lo de sublinhado favorito. cor. Ou trabalha. E finalmente vamos mudar o que nós passamos para a função de impressão, então primeiro nós imprimimos o nome então nós concatenar isso com uma string, aqui vamos tipo gosta, nós também colocamos um espaço antes e depois gosta, e mais uma vez nós concatenar isso. Com a cor favorita. Então, cor favorita agora vamos rodar esse programa, então qual é o seu nome Mosh entra, cor favorita, azul, entra, nós recebemos esta mensagem, Mosh gosta de azul. Ei pessoal Mosh aqui, eu só queria que você soubesse disso você realmente não tem que memorizar nada neste curso porque eu montei uma folha de cola com notas de resumo. Então você pode rever rapidamente os materiais deste curso. O link está abaixo deste vídeo. Então eu fiz o meu melhor para criar o melhor curso de Python possível no Youtube. E eu realmente aprecio se você apoiar o meu trabalho duro por gostar deste vídeo e compartilhá-lo com
22:40
outros, para que eles possam aprender também. E não se esqueça de se inscrever no meu canal, para mais tutoriais como este. Tudo bem, agora, vamos para o próximo tutorial. Neste tutorial do Python, vamos escrever um programa que perguntará o ano em que nascemos em, e então ele irá calcular a nossa idade e imprimi-lo no terminal. Então, vamos começar com nossa função de entrada, entrada vamos imprimir o nascimento aqui, seguido por dois pontos, e um espaço. Agora vamos pegar o valor de retorno e armazená-lo em uma variável, chamado birth_year. Então, como eu disse antes, usamos um sublinhado para separar várias palavras Em seguida, precisamos calcular a idade, então definimos outra variável chamada idade, e aqui fazemos algumas contas básicas, atualmente estamos em 2019, então vamos escrever uma expressão como isso. 2019 - nascimento ano. Agora finalmente vamos imprimir idade no terminal. Vamos executar o nosso programa e ver o que acontece. Então, meu ano de nascimento é 1982, entra,
23:48
oops, temos um erro, o que está acontecendo aqui? assim sempre que você vir esta mensagem, significa que há algo errado com seu programa. Com a informação aqui, podemos encontrar exatamente onde o erro ocorreu. Assim, ao lado do arquivo você pode ver o arquivo que gerou este erro, neste caso isto é app.py. assim atualmente nosso programa tem apenas um único arquivo, mas programas complexos reais geralmente tem centenas ou mesmo milhares de arquivos. Então neste arquivo, na linha 2, é aqui que recebemos este erro, e certo abaixo disso, podemos ver o trecho de código que gerou esse erro. Então é aí que estamos calculando a idade e logo abaixo que você pode ver o tipo de erro. Neste caso, temos um erro de tipo, e aqui está o mensagem. Tipos de operandos não suportados para subtração. Int e str. Então int é curto para inteiro e isso representa um número inteiro e str é curto para string, então aqui estamos subtraindo uma string de um inteiro e o Python não sabe o que fazer com ela.
24:52
Deixe-me explicar. Então eu vou fechar a janela do terminal. Então depois a primeira linha que executamos, temos este conjunto variável de ano de nascimento para uma string, então o que digitarmos no terminal é sempre tratado como uma string, mesmo se você digitar o número, em outras palavras, quando executamos este programa, esta variável de ano de nascimento será definida para uma string, com quatro caracteres. 1982. Esta string é diferente do número real 1982. Um é um inteiro e o outro é uma string. Certo? Então, de volta para a linha 2, onde esta ocorreu um erro. Em tempo de execução, o que significa que quando executamos nosso programa esta expressão no lado direito do operador de atribuição vai ficar assim. 2019 - corda 1982. Python não sabe como interpretar ou como avaliar essa expressão. Para corrigir esse problema precisamos converter este 1982 em um inteiro e então poderemos subtraí-lo a partir de 2019 e
25:56
é fácil. Até agora você aprendeu sobre duas funções incorporadas um é imprimir o outro é entrada. Nós temos algumas outras funções para converter valores em diferentes tipos. Então nós temos int para converter uma string em um inteiro, também temos flutuar para converter uma string em um float, ou um número com um ponto decimal. E também temos bool para converter uma string em um valor booleano. Então, para consertar esse problema, precisamos voltar na linha 2, e passar esta variável do ano de nascimento para a função int como esta. parêntese int, como este então nós passamos essa string para a função int, int irá convertê-lo em um itneger e, em seguida, o interpretador Python poderá avaliar essa expressão. Agora vamos rodar esse programa mais uma vez, então nascer ano é 1982 entrar, então eu sou 37 anos de idade. Em Python temos uma função útil para obter o tipo de variáveis, por exemplo, vamos imprimir o tipo
27:00
do ano do nascimento, logo após a linha 1, vamos imprimir, agora aqui vamos chamar outra função embutida, chamado tipo, e agora vamos passar o nascimento ano, ok, agora da mesma forma depois da linha 3, vamos também imprimir o tipo de idade, então imprimir tipo de idade. OK? Então, vamos executar o nosso programa, então ano de nascimento mais um tempo, 1982, ok, aqui está o resultado então o tipo de ano de nascimento como você pode ver é uma classe de str ou strings, olhamos para as classes no futuro, então por agora não se preocupe com eles, e também abaixo deles você enlata o tipo de a variável age é int ou integer. assim aqui está o que você precisa tirar. Sempre que você usa a função de entrada, você sempre pega uma string, então se você está esperando um valor numérico você deve sempre converter essa string em um inteiro ou um flutuador. Então aqui está um pequeno exercício para você. Eu quero que você escreva um programa
28:04
pergunte ao usuário seu peso e então converta-o em quilogramas e imprima-o em um terminal. Então pause o vídeo, faça o exercício e quando estiver pronto volte para assistir. Tudo bem, então vamos usar nossa função de entrada e perguntar para o peso em libras aqui nós temos o peso em libras ou libras agora precisamos converter isso em quilogramas, é muito fácil nós definimos outra variável weight_kg nós definimos isso para weight_lbs vezes 0,45. E finalmente vamos imprimir o sublinhado de peso kg. Vamos rodar esse programa em Python e ver o que acontece. assim meu peso é 160, tudo bem, mais uma vez, temos um erro, Não é possível multiplicar a sequência por não int do tipo flutuador. Então, como eu disse antes, esta função de entrada retorna uma string, então não podemos multiplicar uma string por um float.
29:08
Python não sabe o que fazer com isso. Então, neste caso, devemos converter este número por um inteiro ou float e, em seguida, multiplique por 0,45. Então vamos chamar a função int. E passar peso sublinhar libras. E execute o nosso programa mais uma vez, 160 ok, então eu tenho 72 kg. Neste tutorial, você aprenderá mais sobre strings em Python. Então, eu defini essa variável de curso e defini-a como Python para iniciantes Agora, anteriormente, eu disse que você poderia usar aspas simples e duplas para definir uma string, mas há momentos em que você tem que usar um formulário específico, caso contrário, você vai se deparar com problemas. Aqui está um exemplo. Imagine que você queria mude esta corda no curso dos Pythons para novatos. Então, nós queremos adicionar um apóstrofo, como este, Curso para Iniciantes. Você pode dizer imediatamente que isso vai louco, porque a nossa string começa aqui e depois termina aqui, todos esses personagens que temos aqui depois do segundo apóstrofo
30:16
O interpretador Python não sabe o que são. Então, para resolver esse problema precisamos usar aspas duplas para definir nossa string para que possamos ter uma aspa simples no meio da string. Então vamos mudar isso para aspas duplas, agora você pode vê-lo adiciona outra aspa dupla para fechá-lo, você tem que remover manualmente isso, e também mais uma vez no começo da string, precisamos adicionar outra aspa dupla. Agora você pode ver o erro se foi, por isso, se você imprimir curso nós vemos o curso de Python para iniciantes. Lindo. Agora vamos dizer que não queremos esse apóstrofo aqui, então temos Python para iniciantes, mas queremos colocar iniciantes em aspas duplas. Mais uma vez, se você adicionar uma aspa dupla aqui, o interpretador Python confuso porque assume a segunda aspa dupla indica que final da string, por isso não sabe o que são esses personagens, então para resolver isso precisamos mudar nossas aspas duplas para aspas simples como isso. E então podemos adicionar aspas duplas no meio da corda. Agora vamos rodar este programa, aí vai você.
31:20
Então, pegamos o Python para iniciantes. Então esses são os casos para usar aspas simples ou duplas. Agora em todos os exemplos Eu mostrei até agora que lidamos apenas com strings curtas, mas e se você quisesse definir uma string com vários comprimentos? Por exemplo, e se você quisesse definir uma string para a mensagem que enviamos por email. Nesse caso, precisamos usar citações triplas. Assim. Nós deletamos isso. Agora nós adicionamos três citações, então 1, 2, 3, lá você vai, Então, nós temos três citações para começar nossa string e três para terminá-lo. Novamente, essas citações podem ser aspas simples ou duplas. OK? Agora, com isso podemos definir uma string que se estende várias linhas. Por exemplo, podemos dizer oi Jon aqui está o nosso primeiro email para você. Obrigado, A equipe de suporte. Curtiu isso. Agora, vamos executar este programa e aqui está o resultado. Então, nós temos essa bela multi linha corda. Agora vamos mudar isso de volta para algo simples
32:24
Assim, podemos observar outras características de strings e Python. Então, vou usar aspas simples e definir o nome do curso para Python para iniciantes. Agora aqui vamos usar o quadrado colchetes para obter um caractere e um determinado índice nesta cadeia. Deixe-me te mostrar. Então, para obter o primeiro caractere, usamos colchetes e digite 0. Então, o índice do primeiro caractere na cadeia é 0. Em outras palavras, é assim que Python seqüências de caracteres são indexadas. 0, 1, 2, 3, 4, etc. Então o índice do primeiro caractere é 0, o segundo caractere é 1 e assim por diante. Então deixe-me apagar isso e executar este programa nós começamos p. Nós também podemos usar um negativo indexe aqui. E esse é um dos recursos que não temos em outras linguagens de programação até onde sei. Então, temos índice negativo, podemos obter os personagens começou a partir do final. Então, se eu passar 1 negativo aqui, Assumindo que 0 é o índice do primeiro caractere 1 negativo é o índice do último caractere. Então, quando corremos
33:28
este programa devemos ver s. Vamos correr, lá vai você temos s, se passarmos 2 negativos, isso vai voltar o segundo personagem do final. Vamos correr mais uma vez agora temos R porque esse é o segundo personagem do final. OK? Então, preste muita atenção a esta sintaxe de colchetes porque muitas vezes é o tópico para testes online do Python ou exames universitários, por isso, se você está se preparando para um teste python, não deixe de assistir a este tutorial mais uma vez e entender exatamente como esta sintaxe de colchetes funciona, também podemos usar um semelhante sintaxe para extrair alguns caracteres em vez de 1 caractere. Por exemplo, se digitarmos 0, cólon 3, o interpretador Python retornará todos os caracteres começando com este índice todo o caminho até este segundo índice, mas não retorna o caractere neste índice. Em outras palavras, de volta a esses índices então você tem 0, 1, 2, 3 e assim por diante. Quando você executa este programa.
34:32
O interpretador Python retornará os caracteres a partir do índice 0 até o índice 3, mas exclui o caractere e o índice 3, então, quando rodarmos esse programa em Python, vamos ver o pyt . Deixe-me te mostrar, então vamos delete esta linha, rode este programa, lá vai você. Nós temos pyt. Agora aqui também temos valores padrão para o índice inicial e final. Então, se nós não fornecermos o índice final, o Python retornará todos os caracteres para o final da string. Vamos dar uma olhada. Então corra este programa, lá vai você, Python para iniciantes. Mas se você alterar o índice inicial para 1, isso irá excluir o primeiro caractere assim quando nós executar este programa, vemos ython então p é removido. OK? Agora, da mesma forma, temos um valor padrão para o iniciar o índice, por isso, se não fornecermos o índice inicial mas adicione um índice final como 5. O interpretador Python assumirá 0 como o índice inicial, então, vamos rodar
35:36
este programa, lá vai você, nós pegamos pytho. Agora, e se nós deixarmos o começo e o fim índice? Bem, eu te disse? Agora, neste caso, 0 será assumido como o índice inicial, e o comprimento da string assumirá como o índice final. Então, com essa sintaxe, basicamente você pode copiar or clone a string. In other words, if I define another variable here, let's call it another and set it to course square brackets with just a colon, now this expression will return all the characters in the course variable so variable will be copy of our first variable. Let's take a look, so, let's print another, and load our program there you go, we get Python for beginners. Então mais uma vez the square bracket syntax is pretty important if you're preparing for online python tests, or college exams, make sure to watch this tutorial again. Now here's a little exercise for you. I'm going to delete all this code define a variable, called name, and set it to Jennifer.
36:40
Now when we print name of 1: negative 1 what do you think we're going to see on the terminal? I want you to use your knowledge to tell what we're going to see on the terminal, we're now running this program. assim pause the video, think about it for a few seconds, then come back and continue watching. So this expression will return the characters starting from index 1 which is the second character all the way to the first character from the end, but excluding the character at this index. In this case, the first character from the in is r, so r will be excluded, in other words we're going to see all the characters starting from e all the way to the second e. Vamos dar uma olhada. So I'm going to run this program ai está. This is what we get, I hope you guessed it right. In this tutorial, we're going to look at formatted strings in Python programming language. Formatted strings are
37:48
particularly useful in situations where you dynamically generate some text with your variables. Deixe-me te mostrar. Let's say we have two variables first name and last name. So first we set this to John, and last we set this to Smith. Agora é melhor to call these variables first name and last name, because they're more descriptive. But here I'm using shorter names because I want you to see the entire code on display tela. So let's say with these two variables, we want to generate some text like this. Jon, in square brackets Smith is a coder. Let's say we want to print this on the terminal. Como vamos fazer isso? Well, we define another variable like message, now here we add the first name, now we need to concatenate this, with a string that contains a space and a square bracket next we need to add a last name, then we need to add a string that contains the closing square brackets followed by is a coder OK? Então,
38:52
if you print message and run this program to see John Smith is a coder, right? Agora, while this approach perfectly works, it's not ideal because as our text gets more complicated it becomes harder to visualize the output. So someone else reading this code, they have to visualize all the string concatenations in their head. This is where we use formatted strings, they make it easier for us to visualize the output. Assim, I'm going to define another variable, let's say msg short for message, and set this to a formatted string. A formatted string is one that is prefixed with an f. So f, citações. Now in between the quotes, first we want to add the value of the first name variable, so, we add curly braces and here we type first. Next we add a space, we add our square brackets, in between the square brackets, we want to display the last name so once again we add curly braces, and type last, and finally here we type
39:56
is a coder. So this is what we call the formatted corda. With these curly braces, we're defining place holders or holes in our string, and when we run our program these holes will be filled with the value of our variables. So here we have two place holders or two holes in our string. One is for the value of our first name variable and the other is for the value of the last name variable. But compare this formatted string with string concatenation. With this formatted string we can easily visualize what the output looks like, right? Now let's print this other terminal to make sure we get the same exact output. So, let's print message ai está. So Jon Smith is a coder. So to define formatted strings, prefix your strings with an F and then use curly braces to dynamically insert values into your strings. In this Python tutorial, I'm going to show you some really cool things you can do with Python cordas. So let's start by defining a variable,
41:04
course and we set that to Python for beginners. Now to calculate the number of characters in this string, you can use a built in function called len. So len we give it this course variable, and then, we can print the result. Let's run this program, so as you can see we have 20 characters in this string, this is particularly useful when you receive input from the user. For example you have noticed that when you fill out a form online, each input field often has a limit. For example, you might have 50 characters for your name, so using this len function we can enforce a limit on the number of characters in an input field. If the user types in more characters than we allow, we can display an error, now, this, len function is another function built into Python, it's a general purpose function, so it's not limited to counting the number of characters in a string, in the future when we look at lists, I want to show you that we can use this function to count the number of items in a list. So it's a general purpose
42:08
função. Now we also have functions specifically for strings for example we have functions for converting all these characters to upper case or lower case. To access these functions we use the dot operator. deixe-me te mostrar. So first we type course, then dot look these are all the functions that are specific to strings. Now in more accurate terms, you refer to these function as methods, this is a term in object oriented programming that we want to look at in the future, but for now, what I want you to take away, is that when a function belongs to something else, or is specific to some kind of object, we refer to that function as a method. For example, here we have this function, upper, for converting the string into upper case, now more accurately because this function is specific to a string, we refer to this as a method. In contrast len and print are general purpose functions, they don't belong to strings or numbers or other kinds of objects. So this is the difference between functions and methods. Now let's take look at this
43:12
upper method. So, let's print the results and we run our program, there you go, you get all these characters displayed in uppercase. Now note this method does not change or modify our original string, in fact it creates a new string and returns it. Assim, if we print our course variable right after we call the upper method, we can see that our course variable still has it's original form, so let's run this program one more time, there you vai. Look, here is our original course variable, it's not modified. Now similar to the upper method we have another method for converting a string into lower case. Então deixe-me mostrar-lhe Print, course.lower. Now, let's run the program, so on the second line you can see, all characters are in lower case. Now there are times that you want to find a character or a sequence of characters in a string. In those situations you can use the find method. So let me delete
44:16
these few lines. Call course. find here we pass a character, let's say p, and this will return the index of the first occurrence of that character, let me show you. So let's print the result we get 0, because the index of the first capital p in the string is 0. As another example, if we pass a lower case o here, let's see what we get, we get 4 because the index of this o here is 4. Now note that the find method is case sensitive, so it's sensitive to lower case and and upper case characters. As an example if you pass an upper case here and run this program, we get negative 1 because we don't have an upper case o anywhere in this string, okay? We can also pass a sequence of characters, for example, we can pass beginners with a capital B let's run this program, we get 11 because
45:20
beginners starts with index 11, now we also have method for replacing a character or a sequence of characters and that is called replace. So let's change find to replace let's say we want to replace beginners with absolute beginners, so we add a comma to pass a second value to this function, or more accurately this method. We add a string, here I'm going to pass absolute beginners. Okay, now let's run this program, so, we get python for absolute beginners. Again, this method like the find method is case sensitive so if you pass beginners all in lowercase, this method is not going to find this exact word in our string, so it's not going to place it with absolute beginners. Vamos dar uma olhada. So I'm going to run the program One more time, look, we still get python for beginners. We can also replace a single character, for example we can replace capital p with let's say capital
46:24
j. Now when we run this program we get jython for beginners. So these are the find and replace methods and one last things I want to show you in this tutorial. tem times that you want to check the existence of a character or sequence of characters in your corda. In those situations you use the in operator, so let's say you want to know if this string contains the word python. We can write an expression like this. String python space in space course. So we're checking to see if python is in course variable. And this is an expression that produces a boolean value, and I get true or false, so we refer to this expression as a boolean expression, now if we print this on the terminal, we should get true, and by the way I'm going to delete the second line, we don't need it anymore, so run the program we get true, but if I change this capitol p to a lower case p and run the program we get false because we don't have
47:28
is exact sequence of characters in our strings. Now note that the difference between the in operator and the find method is that our find method returns the index of character or sequence of characters but the in operator produces a boolean value. Do we have this or not? So that's the difference. Now let's recap all the cool things you learned to do with strings in this tutorial. We can use the len function to count the number of characters in a string, this is the general purpose function built into python, we also have specific functions for strings which we refer to as methods, these include upper for converting a string into uppercase you also have lower and title methods, you learn about the find method which returns the index of a character or sequence of characters, we have the replace method for replacing characters and words in a string and finally you learned about the in operator. So some characters
48:32
in a string. So, you have learned that in Python programming language you have 2 types of numbers, integers which are whole numbers like 10, they don't have a decimal point, and floating point numbers or floats. Which are numbers with a decimal point. Now in this tutorial you're going to look at the arithmetic operations supported in python language these are the same arithmetic operations that we have in math, we can add numbers, multiply them and so on. So let's look at a few examples, we can print, 10 plus 3, so this is the addition operator, we also have subtraction, we have multiplication, we have two kinds of division, here's one with a forward slash, let's run this program and see what we get. we get a floating point number. But we also have another division operator for getting an integer. assim if we add another slash here and run this program we get an integer. Nós temos
49:40
another operator called modulis (?) which is a percent sign. And this returns the remainder of the division. So when we run this program we should get 1, there you go. E one last operator we have here is exponent which is the power. So, that is indicated with 2 asterisks and this will return 10 to the power of 3. So let's run this program we get 1000 so these are the arithmetic operators in python programming language. Now for all these operators that you learned we have an augmented assignment operator. Isso é very useful, let me show you. So let's say we have a variable called x we set it to 10, now we want to increment this by 3, we'll have to write code like this. X we set this to x plus 3. So Python interpreter will add 10 to 3, the result is 13, and then it gets stored into x again. So when we print x we should see 13, there you go. So this is how you can increment
50:44
a number, right? Now augmented assignment operator is a way to write the same code but in a shorter form. este is how it works. We type x plus equals 3. What we have on line 3 is exactly like what we have on line 2. So this is what we call the augmented assignment operator we have augmented or enhanced the assignment operator. Now in this particular case we are incremented a number using the augmented assignment operator, but we can also subtract or multiply a number by a given value for example, let's delete what we have on line 2, we can type subtract equals 3. So here we subtracted 3 from x. When we run this program we should see 7, ai está. Now let me ask you a question, I'm going to clear all this code here to define x and set it to 10 plus 3 times 2. What do you think is the result of this expression?
51:52
this is a very basic math question that unfortunately a lot of people fail to answer. The answer is 16. Because in math we have this concept called operator precedence which means the order of operações. So the multiplication operator has a higher precendence which means it's applied first which means 3 x 2 is executed first, the result is 6 and then its added to 10, that's why x showed up as 16 after we run this code, let's verify that. So, print x run the program, x is 16. So this is what we call operator precedence, it's just a basic math concept. It's not about python programming language. So all the other programming languages behave the same way, so here's the order, first we have the exponentiation which is the power, like 2 to the power of 3, then we have multiplication or division and finally we have addition or subtraction. This is the order of operations. Let me show you another example.
52:56
Here I'm going to add the exponentiation operator, so, 2 to the power of 2. Once again, what do you think is the result of this expression? Pause the video and think about it for a few seconds. The answer is 22. Because the exponentiation operator takes precedence, so first 2 to the power of 2 is executed, the result is 4, then 4 is multiplied by 3, that is 12, and finally 12 is added to 10. So x should be 22. So let's run this program and verify this. Então eu vou delete these lines here. Run the program, there you go. X is 22. Now let me bring back these rules here. We can also use parenthesis to change the order of operations so if we have parenthesis we always takes priority. In this case we can add parenthesis around 10 + 3, so this piece of 3 will be executed first, the result is 13, then the exponentiation
54:00
operator will be executed, so 2 to the power of 2 is 4, and finally 4 is multiplied by 13. Now here is a little exercise for you. I'm going to set x to parenthesis 2 + 3 x 10 minus 3. What is the result of this? Pause the video and think about it for a few seconds. So you learned that parenthesis always overrides the order, so this piece of code is executed first. O resultado of these 5. Then, between the multiplication and subtraction, you know that multiplication takes precedence. So next, 5 will be multiplied by 10, the result is 50 and finally we have subtraction. So 50 minus 3 will be 47. Let's verify this, print x, run the program there you go, I hope you guessed it right. So this is all bout operator precedence, it's a very important topic and I see it quite often in Python tests. So if you're preparing for a Python test make sure to watch his tutorial one more time.
55:12
In this tutorial, we're going to look at a few useful functions for working with numbers let's start by defining a variable like x and set it to 2 .9. Now to round this number we can use the built in round function, so we call the round function, give it x, and then print the result. Let's run this program so, we get 3, we have another useful built in function called abs which is short for absolute, and this is the absolute function we have in math, we give it a value and it always returns the positive representation of this value, even if the value is negative. Aqui está um exemplo. Let's call the abs function and give it negative 2.9 When we run this program we're gong to see 2.9 on the terminal. Então vamos em frente ai está. So absolute always returns a positive number. But technically in Python we have a handful of built in functions for performing mathematical operations, if you want to write a program that involves complex mathematical calculations, you need to import the math module.
56:16
A module in Python is a separate file with some reusable código. We use these modules to organize our code into different arquivos. As a metaphor think of a super market. When you go to a super market you see different sections for fruits and vegetables, cleaning products, junk food and so on. Each section in the super market is like a module in Python. So in Python we have this math module which contains a bunch of rustable functions for performing mathematical calculations. So, let me show you how to use this module. On the top we type import, math, all in lowercase with this we can import the math module. now math is an object like a string, so we can access it's functions or more accurately it's methods using the dot operator. So if you type matemática. look these are all the mathematical functions available in this module. For example you can call the seal method to get the sealing of a number. So if you pass 2.9 here and then print the result we should see 3.
57:20
Let me delete all this other code here. Alright, let's run this program ai está. So we get 3. Another useful method is the floor method, so let's give that a try, floor of 2. 9. What do you think we're going to get? Nós temos 2. Now there are so many functions built in this module and we don't really have time to go through all of them. But let me show you how we can learn about them on your own. Open up your browser and search for Python 3 math module. Make sure to add the version python 3. Because the math module in python 2 is slightly different from the math module in python 3. So python 3 math module, now here you can see the documentation of this kind of module let's go let's have a look, if you scroll down, we can see the list of all the functions and their explanation. So as an exercise I encourage you to have a quick look at this documentação. See what functions are there for you in case you need them. In this tutorial, I'm going to talk to you about if statements in Python
58:28
if statements are extremely important in programming and they allow us to build programs that can make decisions based on some condition. So if some conditions are true we're going to do certain things, otherwise we're going to do other coisas. Aqui está um exemplo. Over here I've got this text file with a bunch of rules for our program. If it's a hot day, perhaps we want to tell the user it's a hot day, so make sure to drink plenty of water. Otherwise, if it's cold, so here's another condition if this condition is true we're going to tell the user it's a cold day so where warm clothes. And otherwise if it's either hot or cold, we want to tell the user it's a lovely day. So let me show you how to write a program that simulates these rules. Assim, back to our program here, we start by defining a boolean variable is underline hot. We set this to true. Next, we add an if statement, so if, here we need to add a condition, in this case we're going to use our boolean variable. Assim, is underline hot. So if this values to true.
59:32
Then we're going to do certain things. In this case, we want to tell the user hey it's a hot day, drink plenty of water. So, back to our program after our condition we add a colon, now, note that when I press enter pycharm automatically indents our cursor. Now any code that we write here will be executed if this condition is true, otherwise it will be ignored. Aqui is an example. Let's write a print statement, here I'm going to use double quotes because I want to use an apostrophe in our string. Assim, it's a hot day. Now let's press enter you can see the cursor is still indented, that means we can write more code that we executed if this condition is true, in this case let's say we don't want to write any extra code, so to terminate this block we need to press shift and tab, now the cursor is at the beginning of the line so lets write a print statement with a message like enjoy your day. Now when we run this program, because this condition is true, you're doing to say this message followed by
01:00:36
this second message, take a look, so run, there you go, it's a hot day enjoy your day. But if I go over here and change this boolean value to false and run the program again, our first message disappears and we only see the second message, enjoy seu dia. So this is how if statements work. Now back here we can add another print statement let's say drink plenty of water. Now because this spirant statement is also indented it will be executed if this condition is true. So I'm going to revert is hot to true and run the program one more time. There you go, so it's a hot day, drink plenty of water, and enjoy your dia. Alright now let's add a second rule here, if it's hot we're going to execute these two lines, otherwise if it's not hot we want to print a different message. Então aqui we are moving an indentation and typing els colon. Now when we press enter once again our cursor
01:01:40
indented so the code that we write here will be executed if this condition is not true. So here we can print it's a cold day, print, where warm clothes. Now let's run our program one more time. So we get the message about a hot day followed by enjoy your day. You don't see any message about a cold day. Now if we go back here on the top. And change this boolean value to false and run our program we see different set of messages. It's a cold day wear warm clothes and enjoy your day. But there's a problem with our program. If it's not hot it doesn't necessarily mean that it's cold, it means it's a lovely day. So the absence of heat doesn't mean its cold. Back to our conditions, here on line 4 we have this rule that says if it's a cold day, then print these messages otherwise if it's neither hot or cold say it's a lovely day. So, to implement this rule we need to go back and put
01:02:44
py and define another variable. So let' say is underline cold we set this to verdade. Now here we need to add a second condition. So after our first if statement, we can use an el if statement to define a second condition. Então é assim que funciona. Assim, el if which is short for els if or otherwise if, now here we add another condition, so, is cold So if t's cold you want to execute these few lines. So let's cut these from here, and move them under our second condition and finally if none of these conditions are true, you want to print a different message. It's a lovely dia. So, right now, is hot is false, is cold is true, so when we run this program, python interpreter is going to execute the first if statement, in this case because our condition is false, these two
01:03:48
lines will be ignored, then Python interpreter will look at line 7, it will evaluate this condition, in this case is cold is true so we're going to see these two messages on the terminal. Now, in this case, because one of these conditions was true, this els statement will be ignored, so we are not going to see this message, and finally as before, we are always going too see this message. So let's run our program, there you go. it's a cold day, where warm clothes and and enjoy your day. Agora, back to the top, if we change is cold to false it's neither hot nor cold so it's going to be a lovely day. Let's run the program, and here you go, it's a lovely day enjoy your day. So these are the basics of using if afirmações. As you can see they are very useful in programming and with these we can build all kinds of rules into our programs. Okay here's an exercise or you. Imagine the price of a house is 1 million dollars. Now if the buyer has good credit, they will need to put down 10 percent
01:04:52
of the price of this property otherwise they need to put down 20 percent write a program with these rules an display the down payment card for a buyer with good credit. You will see my solution Próximo. Alright let's define a variable for the price of this house so price we set this to 1 million so 1 with 6 0s. Next we need a variable to tell if this buyer has good credit so has good credit, and we set this to true, now we need an if statement so if has good credit has true colon, here we need to calculate a down payment so the down_payment should be equal to 0.1 x the price. That is 10 percent of the price of this propriedade. Otherwise colon the down payment should be 0.2 times price. Now finally we remove the
01:05:56
indentation and print here we can use a form of valid string, first we add a label, down payment colon and right after that we add a placeholder or a hole for our down payment variable. So curly braces down payment. Let's run this program, so down payment for a buyer with good credit is 100,000 dollars. Now let's improve this by adding a dollar sign before this number. So back to our formatted string, just before the curly brace I'm going to add a dollar sign let's run this one more time, that is better. In this tutorial I'm going to talk to you about the logical operators within Python. We use these operators in situations where we have multiple condições. Here is an example. Let' say we're building an application for processing loans. If an applicant has high income and good credit, then they're eligible for a loan. So in this example we have two conditions, one is having
01:07:04
high income and the other is having good credit. So if both these conditions are true, then the applicant is eligible for a loan. So this is where we use the logical and operator. We use this operator to combine two conditions, and by the way this is not specific to python programming language, pretty much any programming language that supports if statements also supports the logical operators. So, back to our program, let's define two variables, has high income, we set this to true. And another one has good credit, we also set this to true, now our if statement if has high income has true, and has good credit is also true, then we're going to print eligible for null. So this is where we're using the and operator. So if both these conditions are true then this message will be printed. If one of them is false, we're not going to see
01:08:08
esta mensagem. Vamos tentar isso. So I'm going to run this program so we see it eligible for loan, but if we change either of these conditions to false, and run the program again look, the message disappears. So this is the logical and operator. We also have the logical or, and we want to use that in situations where we want to do certain things at least one of the conditions is true, for example let's change the rule for this program, such that if the applicant has high income, or good credit, then they're eligible for a loan, so if either or both these conditions are true then the candidate is eligible. Now back to our program we can implement this rule by using the logical or operator. So we simply replace and with or, now when we run this program we're going to see this message because at least one of our conditions is true, let's take a look. So the applicant is eligible for a loan for a loan because they have good credit. If you change this to false
01:09:12
but set the other condition to true, we still see the same result, but if both these conditions are false then we're not going to see this message anymore. So this is the difference between these operators. With the logical and operator both conditions should be true, with the logical or operator at least one condition should be true we also have another logical operator called not and that basically inverses any boolean value we give it, if we give it, we give it a true boolean value it converts it to false. Por exemplo let's make up a new room, if applicant has good credit and doesn't have a criminal record then they're eligible for a loan. Let me show you how to implement this. Assim, we go back to our program, in this example we don't need a first variable for let's delete that. Let's set this variable to true we also define another variable like has criminal
01:10:16
registro. We set this to false. Now, we want to check to see if this applicant has good credit and not a criminal record. This is where we use the not operator. So, if they have good credit, and not criminal registro. So, in this example, has criminal record is set to false, when we use the not operator this basically gets changed to true, so we have two conditions that are true. Here's ones and here's another one. So our applicant is eligible for a loan. And when we run this program we see this familiar message. Contudo if an applicant has a criminal record, so let's change this to true, now when we run this program we can see our applicant is not eligible because when we apply then operator on this variable, we'll get false. So true changes to false. And we'll end up with two conditions, one that's true
01:11:20
and the other is false. And that's why this message is not printed. So this is all about the logical operators in python. In this tutorial I'm going to talk to you guys about comparison operators in Python. We use comparison operators in situations where we want to compare a variable with a value, for example, if temperature is greater than 30, then we want to print it's a hot day. Otherwise, if it's less then 10, it's a cold day, otherwise it it's neither hot nor cold. And by the way I'm taking about celsius, not farenheit. So, to build these rules into our program, we need to use comparison operadores. Back to app.py, I define this temperature value, let's write an if statement, if temperature now we want to check to see if this is greater than 30, so we use the greater than operator. If this is greater than 30, we want to print it's a hot day
01:12:24
otherwise, let's just print it's not a hot day. Agora, when we run this program, we're going to see this second message because 30 is not greater than 30. So our first condition a value is to false. let's verify that. So run, it's not a hot day. Now if you change the temperature to 35 and run this again, we're going to see a different message, it's a hot day, so this is where we use comparison operators. Now what we have here as you know is an expression because it's a piece of code that produces a value. So more accurately this is a boolean expression. So this is the greater than operator, we also have greater than or equal to, we have less then, less then or equal to, here's the equality operator, so if the temperature equals to 30, then you can say it's a hot day. Note that this is different from the assignment operator that has only one equals sign. You can see that if we use only one equal sign
01:13:28
here we immediately get this red underline because this is simply an assignment statement. We're changing the value of the temperature. you are setting the value of algo mais. So we don't have a boolean expression, you are not producing a boolean value. OK? So, our equality operator has two equal signs and finally we have not equal which is an exclamation followed by an equal sign. Now here's an exercise for you. You have probably seen that when you fill out a form online, sometimes the input fields have validation messages, for example, let's say we have an input field for the user to enter their name. Now if the name is less then 3 characters wrong we want to display a validation error, like name must be at least three characters, otherwise, if the name is more then 50 characters long then we want to display a different validation error like name can be a maximum of 50 characters. Otherwise if the name is between 3 and 50 characters then we just want to tell the user that name looks good.
01:14:32
So go ahead, and write a plan to implement these rules. Alright let's define a variable called name and set it to let's say j. So we're assuming this is what the user types into an input field. Now, we want to get the number of characters in this string. So we use the len function, right? Len of name. When we print this we get 1, right you have seen this before. Now here we want to use an if statement so if len of name is less then 3, then we want to print name must be at least 3 characters now here we need a second condition to check the upper limit. So el if len of name is greater than 50, then we want to print a different message, name, must be a maximum of 50 characters.
01:15:40
OK? And otherwise if else none of these conditions are true that means the name looks good. Assim, print, name looks good. Vamos execute o nosso programa. So in this case we get this message because our name is too short. Now if you go back here and type something really really long. E depois we run our program we're going to see a different message name must be a maximum of 50 characters and finally if we type a proper name here like John Smith and run our program we get name parece bom. Here's another good exercise that combines many of the materials you have learned so far, so earlier you built a program to convert someone's weight from pounds to kilograms. Now we want to extend this program and allow the user to enter their weight in either kilograms or pounds and then we will convert it to the other unit. Here's how our program
01:16:44
is going to work. So I enter my weight in pounds so 100 and 60 now it's telling me if it's in pounds or quilogramas. So here I'm adding l to lbs or k for kilograms. And by the way, this program is not case sensitive so when I enter a capital l or lowercase l it takes it as pounds. Now it tells me ur set it to kilos. Let's run this program one more time, this time I'm going to enter my weight in kilo's, so send it to is the weight and the unit is kilograms so k, and it says you are 160 pounds. So go ahead and spend a few minutes on this exercise, you will see my solution next. Alright first let's ask the user their weight. So we use the input function, weight colon we get the return value and store it in the variable called weight. Now the second question, so one more time we use the input function el for pounds.
01:17:52
Or k for kilograms. Assim, let's get that too and store it in a variable called unit now we need an if statement. So if unit equals l then we need to convert this weight into kilograms. However, with this implementation we are only allowing the user to enter a capitol l, if they enter a lowercase l this code is not going to work. So this is where we use the upper method of string objects so this unit is a string because as I told you before, the input function always returns a string. So, we can use the dot operator to access all it's methods or functions, here we call the upper method, this will convert whatever the user enters to upper case and then we'll convert it to a capital l. Now, if this condition is true, then we need to get the weight and multiply it by 0, .45 However, as you know this weight is a string object, and we cannot multiply a string
01:18:56
by a floating point number, we talked about this earlier in this course. So first we need to convert this weight to a numerical value. assim right here, when we call the input function, we can get the return value and pass it to the int function. Assim, we call the int function and give it the return value of the input function. Now, the in function will return an integer so we can store it in this weight variável. So here's the converted weight, let's store it in a variable called converted, then we print here we can use a formatted string, so we prefix this string with f ur we add curly braces to dynamically insert the value of converted variable. And finally we add kilo. Otherwise, if the unit is kilograms. We need to divide the weight by 0.45. q So, weight divided by 0.45 and
01:20:04
just to refresh your memory, this division operator returns a floating point number but if we use double slashes we'll get an integer. In this case, we want to get a floating point number, finally let's print a formatted string, ur curly braces, converted libras. OK? Agora let's run this program and see what happens. So weight is 160 and lbs in and that equals to 72 kilos, perfect, if we run it one more time, and enter 72 kilos we get 160 pounds. In this tutorial I'm going to show you how to use y loops in python. Nós use y loops to execute a block of code multiple times and there are often useful in building interactive programs and games. In a future tutorial I'm going to show you how to build a simple game using ay loop. So, let's get started with the basics, we write ay statement
01:21:12
and right after that, we type a condition followed by a colon as long as this condition is true the quote that we write in this block will be repeatedly executed. Here is an example. We can define a variable like i, as in short for index and set it to 1. Now we set our condition to i less than or equal to 5, so as long as I is less then or equal to 5, we can print i, on the terminal. And then we need to increment i, by 1. So we set i to i plus 1. The reason we do this is that if we don't do this I will be 1 forever so we'll end up with an infinite loop. Because this condition will always be true. One is always less then 5, so in every iteration of this loop, we increment i by 1, so at some point, i is gonna be six and then that is when this condition will be false and then we'll jump out of this loop, okay? Now to demonstrate how everything works after this loop I'm going to add a print statement
01:22:16
say done. So note that these two lines are indented so they are part of the y block. Okay, now let's go ahead and run this program and see what happens. Assim, take a look, we get the numbers 1-5 followed by feito. So heres how this program gets executed first we set i to 1 now python interpreter executes line 2, this condition is true because i is less then 5, so i is printed on the terminal and then incremented by 1. Then the control moves back to the beginning of the y loop. So it doesn't go to the next statement. Assim, we come back here and now we are in the second iteration. In the second iteration i is 2, and because 2 is less then 5, our condition is still true, so i will be printed on the terminal, and once again it will be incremented by 1, so at some point i is going to be 6, and that's when this condition will be false so our look will be terminated and this done message will be printed on the terminal.
01:23:20
So this is the basics of y loops. Now let's make this program a little bit more interesting. Here we can write an expression like this. Nós add a string, and in this string we add an asterisk and then we multiply this string by i. assim with this expression, we can repeat a string, when we multiply a string by a number, that string will be repeated. For example, if i is two, this expression will produce a string with two asterisks. Now let's run the program and see what we get. So we see this little triangle shape here. Because in the first iteration i is 1, so, 1 times an asterisk produces 1 asterisk. In the second iteration i is 2, so when we multiply 2 by 1 asterisks, we'll get 2 asterisks. In this tutorial I'm going to show you how to use ay loop to build a guessing game like this. So we have this secret number which is currently set to 9. Now the computer is asking me to make a guess. Assim,
01:24:28
let's say 1 is not right because the secret number is 9, okay, try again, 2, no it's not right, let's try again, so I only have three chances to make a guess. If I can't guess the number the program tells me that I failed. let's run the program one more time, this time I'm going to guess the number, it's 9, there you go, it says you in. So let's go ahead and build this program using ay loop. Alright, let's start by defining a variable to store our secret number so, we call the secret underline number and set it to 9. Now we need a while loop to repeatedly ask a user to make a guess. So while condition colon What is our condition here? Well we want to give our user a maximum of three guesses. So similar to the last tutorial, we can define a variable like I, set it to 0, and assume this represents the number of guesses the user has made. And then we write our condition as i less then 3. Note that here I'm not using less then or equal to operator, because with this condition
01:25:32
our loop will be executed 4 times, while i is 0, one, two, and three, so here we should use the less then operator. Now if we give this code to someone else it's unclear what does i represent here, it's only in our head that i represents the number of guesses the user has made. Assim como a best practice, always use meaningful and descriptive names for your variables. So it's better to rename this variable to guess, count. Let me show you how to rename. So right click on i variable, and then go to refactor and rename it. Look at the shortcut. On a Mac computer it's shift and f 6. Now in this dialogue box we can easily rename your variable and pycharm will update all the references to that variable so we don't have to manually update each instance, okay? Vamos change this to guess_count enter, there you go, now that is better, also it's better to store 3 in a separate variable to make our code
01:26:36
more readable, because it's not quite clear what does 3 represent here. So, let's define a variable called guess limit say to 3, and then we can change 3 to guess underline limit, now our code is more readable while guess count is less then guess limit, see it reads like a story this is how you should write code. OK, então while this condition is true, we want toast the user to make a guess. Então aqui we use our input function, guess Now whatever the user enters comes out as a string so we need to convert it to an integer. So right here, we pass the result to the end function and then get it and store it in a separate variable called guess. So at this point the user made a guess, now we need to increment guess count so guess count we set it to plus equal 1 or okay, now we need to check to see if the user will make the right guess. So here we need an if statement. If what the user guessed
01:27:40
equals our secret number, again see our code is so readable. It's like a story you can read it like plain Inglês. So if this condition is true we want to tell the user they won. So print you won now lets go ahead and run our program up to this point. So okay it's asking me to make a guess, I'm going to make the wrong guess so one it asked me again, 2 one more time, 3, okay, what is missing in this implementation is the message that tells me that I failed. We're going to take care of it momentarily, but let's run the program one more time and make the right guess. So, 9 okay it says you won, but it's still asking me to make a guess, because our while loop is going to get executed 3 times. Veja 1 and 2. So we need to change our program such that if the user makes the right guess, we need to terminate our while loop, we need to jump out of it. Como fazemos isso? So, over here if the user makes the right guess, after
01:28:44
we print this message we can use the brick statement to terminate terminate a loop, when python interpreter sees this, it's going to immediately terminate our loop, it's not going to evaluate this condition again. Now let's run our program and see what happens. Então, eu vou guess the right number, you won and look, you are now asked to make two more guesses, beautiful. Now the last thing we need to add here is the message that tells the user that they failed if they could not guess the right number. Como fazemos isso? Well in Python our while loops can optionally have an else part. similar to the if statements. So earlier you learned that our if statements can optionally happen else part. Here, so if this condition is true, do this, otherwise do something else. In this case our if statement doesn't have an else part. Now, similar to the if statements Our while loops, our while statements can also have an else part. So, right at this level we can add
01:29:48
an else block, so else colon. And the code that we write here will get executed if this while loop completes successfully without an immediate pausa. Em outras palavras. If the user guesses the right number, you break this loop, you jump out of it so the code that we write in the else block will not get executed. But if the user cannot guess this number, you're never going to break out of this loop, so this loop will be executed to completion untill this condition become false. In that case, the code that we write in the else block will get executed, and this is the perfect opportunity for us to tell the user hey, you made three guesses but none of them were right. So, print, sorry you falhou. Now, let's test the program one more time. So, guess 1, 2, 3, sorry you failed, let's run it one more time. This time I'm going to make a wrong guess, and then the right guess,
01:30:52
we won and our loop terminated immediately. Alright, now it's time for you to practice what you have learned so far. So once again we're going to build a game this game is a simulation card game. Now our game doesn't have a graphical user interface or gooey and it doesn't really matter for now, our focus is entirely on building the engine for this game. Então vamos ver como isso funciona. When we run this, we get this little symbol here, and our program is waiting for us to enter a command. If you type help either a lower case or upper case we get the list of commands that our program or our game currently supports. So we can type the start command to start our car, we can type stop command to stop our car, and quit to terminate the game. Any other commands that we type our program is going to tell us hey I don't understand that. For example, if I type asd here, it's going to say I don't understand that.If you type start, we get this message, car started, ready to go, if you type stop it
01:32:00
says car stopped, and finally if we hit quit our program terminates, this is a fantastic exercise for you to practice wha you have learned, so pause the video and spend 5-10 minutes to build this program. Alright, we're going to start with a while loop with a condition What is our condition here? We want to run this loop until the user types quit. So we can define a variable or a story to command what the user enters, and then we can run this loop as long as the command does not equal to quit. So right before the loop, we define a variable, command, and initially we set it to an empty string. An empty string is a string that has no characters nisso. We only have the quotes. Então we type out our condition as while command does not equal to quit then do something. Now immediately we have a problem here because we're assuming that the user types the command in lower case, so if they type this in upper case they
01:33:04
our program is not going to behave properly, so to fix this problem, you need to call the lower method of the string object and then compare the results. With this quit. You could also call this upper and then type quit in upper case. It's about our personal preference in this demo I'm going to use lower case characters. So, okay, now in this loop we need to ask the user to enter a command. So once again we're going to use our input function, we're going to add a greater then symbol followed by a space, whatever the user enters, we get it and store it in our command variable. Now apart from quit command, there are three other commands that we need to support. Start, stop, and help. So here we need an if statement to compare what the user enters with one of the supported commands. So, if command.lower equals start then you want to print the message like the car started. So print the car started.
01:34:08
Ready to go, it doesn't matter, now the second condition. What if its not start, maybe it's stop? Assim, el if command.lower equals stop, there you go, then we print a different message car stopped. Now look at our code. We have repeated this lower lower lower multiple times. This is bad, in programming we have a term called dry, which is short for don't repeat yourself. So whenever you have duplicate your code that means you're doing something wrong. So how can we solve this problem. Well, instead of calling the lower method in each condition, we can call it right here when we get the input from the user, so this input function as you know returns a string, we can immediately call the lower method on this string, and with this command will always be in lowercase, so we don't need to call this method in every condition. Veja, we remove the duplication and also our conditions
01:35:12
are shorter and easier to read. There is also one more place we need to modify so, it's right here. Isso é melhor. Now, the third command. We need one more el if. If the command equals help, then, we want to show the commands that we support. Assim, here we're going to print a multi line string. Então nós use triple quotes like this, and give the user a guideline like this. So start to start the car stop to stop the car, and quit to quit. Now finally we need an else part, so if what the user enters is none of these commands, we're going to tell them, hey we don't understand these, else, colon print sorry I don't understand that. And by the way note that here becomes I'm using double
01:36:16
quotes, I can easily use a single quote as an apostrophe, okay? So let's run our program up to this point and see what happens. Alright, let's type start car is started, beautiful, stop, car is stopped, help, we get this guideline, but there's so much indentation before our commands, we'll fix that in a second. And finally let's test the quit command, oops, our program didn't work properly. Here is the reason. With these if statements, we're comparing the command with start stop, and Socorro. Anything else will end up here, so that's why our program says it doesn't understand that. So that's why our program says it doesn't understand that command. However, after this el statement the control will be moved to the beginning of the loop. At this point our command is quit, so our loop will complete and the program terminates. In other words when we run this program and type quit, our program actually quits but
01:37:20
we still see this message which shouldn't appear here. How can we solve this problem? Well, we can come back here and just before the else block, add another el if, something like isto. el if command equals quit then you can immediately break. This will solve our problem, but note that we have kind of repeated this expression in two places. The reality is that we don't really need this condition on the top, because with these if statements well more accurately with this el if we can jump out of this loop and terminate our program. So, we can simplify our condition to something like this. Verdade. So while true means this block of code is going to get executed repeatedly, until we explicitly break out of it, OK? Now let's test our program one more time. Assim, quit now our program terminates and we don't see that message lindo. So let's fix the last problem. You saw that when we
01:38:24
typed help, these guidelines appeared with so much in indentation, and here's the reason, look, right here in our code, they are already indented. So when we use triple quotes, what we type here will be printed exactly as is. So, because we have an indentation here, this indentation will also be printed on the terminal. So, let's delete these okay, run the program one more time, type help, the indentation is gone. Lindo. Now here's a challenge for you. eu quero que você take this program to the next level. So right now if we type start we get this message car started. And if we type start again we get the same message. It would be better if we got a message like car is already started so it doesn't make sense to start a car twice. Similarly, if we type stop it says car stopped, if we type it again we get the exact same message, it doesn't make sense to stop the car twice. So here's what I need you to do if the car is stopped and the user tries to stop it again,
01:39:28
the program should say hey, the car is already stopped, what are you doing? And similarly if the car is already started and the user tries to start it again, the program should yell at the user. So go ahead and make the necessary changes to implement this scenario. Alright to add this to our program, we need to know if the car is started or not. So there is one more piece of information we need to store in the memory. What is the kind of data we need to store here? Um booleano. Is the car started or not, it's a matter of yes ou não. True or false. So on the top, here we can define another variable like started and initially we set it to false. So the car is not started, right? Agora when the user types the start command, here we need to check to see if the car is already started. If not the we'll start it or otherwise we'll yell at the user. So in this block we'll write another if statement, if it's already started and we print car is already
01:40:32
começado. Otherwise, so if you add an el statement here. E neste momento, you set started to true. So we start the car and we print this message, okay? Now we need to make a similar change for the stop command. So if the car is already stopped we need to print a different message. E se not started, so here we're using the not operator to see if the car is stopped. So if it's not started that means it's stopped, okay? So if it stopped we print car is already stopped with double p's, otherwise so else we need to stop the car, how do we do that? Nós set started to false. And then we'll print this message. Tão fácil quanto isso. Let's go ahead and run our program. So, initially our car is stopped. So I'm going to type stop, it says the car is already stopped, so lets
01:41:36
start it, okay, now our car is started, let's start it one more time. The program is yelling at us. Então nós podemos not start the car twice. Lindo. Now let's stop it it says the car is stopped, let's stop it one more time, we get this message novamente. In this tutorial, I'm going to talk to you guys about for loops in python. In the last tutorial, you learned about while loops you learned that we use while loops to execute a block of code multiple times. In python we have another kind of loop, that is a for loop, and we use that and we use that to iterate over items of a collection, such as a string. Because a string is a sequence of characters, so it looks like a collection so we can use a for loop to iterate over each character in a string and then do something with it. Aqui está um exemplo. We type out for then we define a variable, this is what we call a loop variável. In each iteration, this variable will hold um item. So, let's call it item, in
01:42:40
here we type out a string like Python, and then colon. So with this for loop we can iterate over a string and in each iteration this item variable will hold one character at a time in the first iteration it will be set to p then in the second iteration it will be set to y, and in the third iteration it will be set to t and so on. So here we are inside our for block, because of the indentation here, so whatever we type here will be executed in each iteration, for now we can simply print this item now let's run this program and see what happens. So you can see each character in this string is printed on a new line. Let's look at another example. In Python we can define lists using square brackets, so let me remove this string from here, and define a list using square brackets, a list is simply a list of items, a list of numbers, a list of customers, a list of emails, products, blog posts, whatever. So here we can define a list of names like Mosh,
01:43:44
Jon, Sarah, and then go ahead and run our program so we can see in each iteration we get one name and print it on a new line. Nós também podemos loop over a list of numbers, for example, 1, 2, 3, 4, let's run it, again we see each number on a new line, but what if we want a list of numbers? We don't to explicitly type out a list with let's say 100 or 1000 numbers, we don't want to type, 5, 6 7 all the way to 100. That is when we use the range function. So, let me delete this, In Python we have a built in function called range, for creating range of numbers. So, we give it a number, let's say 10, let's run this program, now we can see here on the terminal we have 0 all the way to 9. So 10 is not included. So basically when we call the range function, this range creates
01:44:48
an object, it's not a list, it's a special kind of object we can iterate over, in each iteration this object will spit out a new number. We can also work with a range of numbers here, let's say you want to start from 5, and go all the way to 10. So, let's run our program, now we have the numbers 5, 6, 7, and 9. Also, this range function can optionally take a step, so we can pass two asa step to this function, and when we run our program, we can see our first number is 5, now we go two steps forward to get 7, once again we go to two steps forward we get 9 and that is the end of our range. So this is the basics of using for loops in python. Now here's an exercise for you. I want you to write a program to calculate the total cost of all the items in a shopping cart. So let's say we have a list of prices like 10, 20, and 30, I want you to use a for loop,
01:45:52
to calculate the total cost of all the items in our imaginary shopping cart, so calculate that, and then print it on the terminal. Isso é bonito fácil. And you should do it in a couple minutes. So as you learned we use for loops to iterate over all the items in a collection, a collection can be a string, it can be a list, it can be a range object that is returned from the range function. Anything, any kind of object that has multiple Unid. So in this example we're going to use a for loop to iterate over the list of prices. So for item in prices, colon, and by the way this loop variable we don't have to call this item, can call this anything. For example, in this case we can rename it to price. So for price, in prices. Now in each iteration this price will hold one value. In the first iteration it's going to hold 10, then it's gooing to be 20, and then it's going to be 30. So we need to define another variable to calculate the total so
01:46:56
we define that outside of our for loop, let's call it total and initially we set it to 0. Now in each iteration we get the current price and add it to the total so we write total equals total plus price or as you learned earlier we can use the augmented assignment operator to simplify this code. So, after our for loop. This total variable has a total of all the prices we can simply print it here, or we can use a formatted string, so a string prefix with f, the other label, like total, curly braces to dynamically include some value in our string, in this case our total variable. Então vamos em frente and run this program, there you go, so the total cost of all the items in our imaginary shopping cart is 60. In this tutorial I'm going to talk to you guys about nested loops in python. Using a nested loop basically means adding one loop
01:48:04
inside of another loop, and with this technique we can do some amazing things for example we can easily generate a list of coordinates. So, a acquired (?) as you know is a combination of x and y valor. Let's say 0 and 0. Now let's say you wan to generate a list of coordinates like this. So we have 0 and 0, then we'll have 0 and 1, then 0 and 2, next we're going to change x, so we're going to use 1 for x, and once again we're going to use these 3 values for the y coordinates so 1 and 0 then 1 and 1 and 1 and 2, you got the point. Podemos easily generate these coordinates using nested loops. Deixe-me te mostrar. So, we start with one loop, let's say for x in range 4. With this loop, we can generate value for the x coordinate. Let's print this on the terminal, Okay, so, we get the values, 0 to 3. Now for each x, like 0, we
01:49:08
should generate a few y values. So that is where we use a nested loop. So inside of this loop we're going to add another loop, so instead of just printing x first we want to add another loop, for y in range let's say 3, now we can print x and y together so, print, here, we use a formatted string. to display coordinates like this. So we add parenthesis inside of this parenthesis first we need to add x so curly braces x then a comma followed by another set of curly braces, and y, let's run this program and see what we get. Ai está. So, we have these coordinates 0 and 0, 0 and 1, 0 and 2, then you have 1 and 0 1 and 1 1 and 2 and so on. So let me explain exactly how this program gets executed. So in the first iteration, of our outer loop, x is 0. Now we are
01:50:12
on line 2, here we have a new loop which we call an inner loop. In this inner loop, in the first iteration y is going to be 0, so we print 0 and 0 on the terminal. Now the control goes back to line 2 or our inner loop. In this second iteration y will be set to 1, but we are still in the first iteration of our outer loop. assim x is still 0, but now y is incremented to 1. So that is why we see 0 and 1 on the terminal. Once again, the control goes back to line 2, we are in the third iteration of our inner loop, so this will continue until our inner loop completes. That is when y reaches 2 because this range function generates number 0 to 3 but not including 3. So we'll have 0 1 and 2. After this inner loop completes, then the control goes back to line 1, and at this point we're going to be in the second iteration of our outer loop. So x will be 1, then the control will be moved to line 2, or our inner
01:51:16
loop, at this point, this range function is going to generate the numbers 0 to 3 one more time. So this inner loop will be executed 3 times. And then we'll go back to our outer loop. So this is how nested loops get executed. Okay, here's an exercise for you, but this one is a little bit more challenging then the exercises you have done so far. Então eu realmente não expect you to do it, but if you do it, wow, I will be so proud of you, so see what I've done here? Using nested loops, I've written some code to draw this f shape, can you see that? Então eu let me give you a hint, first of all we have this list, called numbers, in this list we have these values, 5, 2, 5, 2, 5, 2. These values determine the number of x's we have in each line. Assim, for example, the first item in this list, this tells us that we should have 5 x's on the first line. There you go, so 1, 2, 3, 4, 5, on the second line we're going to have 2 x's,
01:52:20
on the third line we're going to have 5 x's like this. So I've written code to convert a simple list of numbers into a shape like this. Now here's a tip for you. Using your for loop you need to iterate over this list. Em each iteration you get one number, this determines the number of x's to be displayed on that particular line. So if you want to cheat, you can get this number and multiply by a string that contains x, so if you multiply x by 5, we'll get 5 x's, that's not what I want you to do. I want you to use an inner loop here to generate a string that contains 5 x's. So imagine in Python we cannot multiply a string by a number so to solve this problem we need a nested loop. So go ahead and spend five minutes on this exercise. And by the way, do your best to solve this. Isto é a little bit challenging, but it's not extremely difficult. It just requires a little bit of focus. You'll see my solution next. Alright so first we need to iterate over
01:53:24
all the items in this list. So for item in numbers, or, you could rename this variable to x_count. That is the number of x's on each line. OK? Now I told you that if you want to cheat you can write code como isso. Print x times x underline count. If you run this program we get the same saída. So this is the beauty of Python, with Python we can write expressions like this, we can multiply a string by a number to repita. A lot of other programming languages don't support this feature. Mas for this exercise, I wanted you to imagine that we don't have this feature in Python so you will have to use an inner loop to solve this problem. Veja como funciona. In the first iteration, x count is going to be 5. So we need to generate 5 x's. Como podemos fazer isso? Well, let's say we define a variable called output and initially set it to an empty string. Now we need to add 5 x's to this string. Assim, we can use another loop for count in range,
01:54:28
of x underline count. So we're using the range function to generate a sequence of numbers from 0 up to x count. So in our first iteration x count is going to be 5, so range of 5 would generate the numbers 1, 2, 3, 4. So this inner loop will be executed 5 times. That is exactly what this count represents. So now in each iteration we simply need to append an x to our output variable. So we set output, plus, equals x, and then after this inner loop we simply print the output. With his we'll print 5 x's on the first row. Then we go to the second iteration of our outer loop. At this point x count is going to be 2, now on line 3, we're going to reset our output variable to an empty string. So we start over. Then we go to our inner loop, this loop will be executed 2 times, so we'll append to x's
01:55:32
to the output variable and then print it, as simple as that. So see, it wasn't really that difficult, but it was slightly more difficult then the previous exercises. So let's run this program, there you go. Now if you're adventurous, I want you to modify the values that we have in our numbers list, to print and l here. Now in this tutorial we're going to take a closer look at lists. So, I'm going to define a list of names, let's send them to John Bob Mosh Sarah and Mary. Assim, if you print this list here, what we see on the terminal look exactly like how we define our lists we have square brackets, and in between these square brackets we have our item our items, so we have 5 strings in this list. So we can also access an individual element using an index just like how we can access an individual character in a string using an index.
01:56:40
So, here we type out square brackets, and specify an index. The index of the first item in this list is 0. So, let's run this program, there you go, we get Jon now if you want to print out the third element in this list it's index is 2, so names of 2, returns Mosh, now we can also pass a negative index here, so negative 1, refers to the last item in this list, that is Mary, let's run the program, there you go, we see Mary, if you pass negative 2, this returns the second item from the end of the list. So let's run the program, there you go, we get sarah, so this is exactly like accessing individual characters in a string. Nós também podemos use a colon to select a range of items, for example if you pass 2 colon. This will get all items starting from the index of 2, that is Mosh here all the way to the end of the string. So let's run this program
01:57:44
ai está. We get this list with 3 items, Mosh, Sarah, and Mary. We can also specify an end index, let's say 4, so this will return all the items up to this index, but it doesn't include the item at this index. So when we run this program we only see Mosh and Sarah, the item I've indexed 4which is the 5th element or 5th item in this list is not returned. So Mary is not returned. And also here we have default values, so if you leave out the end index this expression is going to return all the items starting from the index of 2, to the end of the list or if you leave out the start index, this expression asumes 0 as the default index, so it will return all the items from the beginning to the end of the list. E, aliás, just like strings, these square brackets here, don't modify our original list, they simply return a new list. For example, if we pass 2 here, you can see this returns a new list with 3 items.
01:58:48
So if you go back here and print our original list of names right after you can see it's not affected. So here we want to use square brackets with a colon to select a range of items, we get a new list, and by the way we can also modify any of the elements in this list. For example let's say we made a mistake and the first item shouldn't be john with an h, so we want to remove the h, that is very easy, so we access it, using an index that is names of 0, and we set it to a new value como isso. Now, let's print our list so, you can see the first item in this list is now data. So this is the basics of lists. And here's a exercise for you. I want you to write a program to find the largest number in your list. This is a fantastic exercise for beginners, so go ahead and spend a few minutes on this, then come back and continue watching. Alright, let's define a list of numbers, numbers, with a bunch of random numbers
01:59:52
3, 6, 2, 8, 4 and 10. Now to find the largest number in this list. We need to define another variable let's call it max, this variable will hold the largest number, now initially you want to assume the first item in this list is the largest number. So we set max to numbers of 0. We're only assuming that the first item is the largest number. Chances are our assumption is wrong. So we need to iterate over this list, we need to loop through it, get each item and compare it with max. If it's greater than Max, then we need to reset max to that number. So in the first iteration we get 3, and max is also 3. Is 3 greater than 3. No, so we move on, we get the second number, is 6, greater than 3? It is, so we need to reset max to 6. Once again, we continue, we get 2, these two greater than 6, no it's not, so we move on, then we get 8, is 8 greater than 6? It is, so we should reset max to 8.
02:00:56
That is pretty easy. So here we need a for loop, for number in numbers colon now we need too heck to see if this number is greater than max, so, if number is greater than max, max colon then we need to reset max, so max to this new number, that's all we had to do. So, let's print max, and run our program we can see the largest number in this list is 10. It doesn't matter whether this number is at the end of the list or the beginning. So if I move 10 and put it right at the beginning we should still see the same result. Let's run our program, we still see 10, if I put this somewhere in the middle, our program should still work. Let's put it right after 2. Run the program, we still get 10. In this tutorial I'm going to talk to you guys about two dimensional lists in python. Two dimensional lists are extremely powerfully and they have a lot
02:02:04
if applications in data science and machine learning. Aqui an example, In math we have a concept called matrix, which is like a rectangular array of numbers, let me show you. assim we have 1, 2, 3, 4, 5, 6, 7, 8, 9. So we have a rectangular array of numbers. You have rows, and columns. So this is a 3 x 3 matrix in math. Now we can model this in python using a 2 dimensional list. A 2 dimensional list is a list where each item in that list is another list. Assim, you want to define a matrix. We set it to a list, each item in this list, is going to be another list, and that list represents the items in each row. Então, o primeiro item in our list is going to be another list, and in this other list we're going to have the values 1, 2, and 3. Now the second item in our matrix list, once again, we have a list, this list represents the items in the second row. Assim,
02:03:08
4, 5, and 6, and finally 7, 8 9. So as you can see we have a 2 dimensional list Each item in our outer list is another list. OK? So, this is how we can implement a matrix in python, now to access an individual item in our matrix, once again we use square brackets, let me delete this stuff, alright, so how do we access 1 here, well, you start with our list then we add square brackets first we need to go and get the first item in this list. Certo? So we pass 0, now this expression returns another list. That is the inner list. In this list, let's say you want to access the second item, so, once again we add square brackets, and we pass 1, that is the index of 2 in this list, alright. So if we print this on the terminal we get 2. Okay? So using 2 square brackets
02:04:12
we can access individual items in our matrix, and also we can modify these values using this syntax, so, before printing this, let's change this to 20, so matrix of 0, and 1, let's change it to 20, and then print it, there you go, it's modified, now here you can also use nested loops to iterate over all the items in this matrix. Deixe-me te mostrar. Assim, we start with a rows for the rows in matrix, so with this loop, we are iterating over our Matrix list, in each iteration row will contain 1 list, 1 item, okay? Now, here we need to use an inner loop. So we need to loop over this row which is a list of items. We can type out 4 item in row colon and print item. OK? So, let's run this program, there you go, we get all the item
02:05:16
in our list. Hey, I just wanted to make a quick announcement. In case you haven't seen my website yet, head over to codewithmosh.com this is my coding school, where you can find plenty of courses on web and mobile application development. In fact recently I published a comprehensive python course that goes way beyond this beginners youtube. And if you're serious about learning python and getting a job, I highly encourage you to enroll in this course. Just like this tutorial you can watch it anytime, anywhere as many times as you want, and you will also receive a certificate of completion that you can add to your resume, and the course comes with a 30 day money back guarantee, so if you're not happy we'll give all your money back, no questions ask. The price for this course is 149 dollars, but the first 200 students can get it for only 15 dollars. Então, se você estiver interessado, the link is below this video, click the link, and get started. In this tutorial, I'm going to talk to you guys about the list methods, or list functions. Estes são os operations that we can perform in a list. So let's define
02:06:20
a list of numbers, here we pass a bunch of random numbers, like 5, 2, 1, 7, and 4. Now there are a number of things we can do with this list, we can add new items to it, we can remove existing items, we can check for the existence of an item these are the operations that we can perform on a list. Assim, the we type numbers, we can see all these functions or more accurately the methods that are available in our list objects. So we can call the append method to add a new item to this list. Digamos 13. Actually, no it's not a good number. I'm joking I'm not superstitious, so let's add 20, it doesn't really matter and then print our list when we run the program we can see 20 is added at the end of this list but what if you want to add a number somewhere in the middle, or at the beginning of our list? For that we use a different method, that is called insert. So, insert, now this method takes 2 values, let me show you. So when we open parenthesis
02:07:24
look at this little tool tip above the insert method. You see the first value that we need to pass here is an index, so this is the index at which we want to insert this new item. Vamos say we want to add an item at the beginning of our list, so we passed our index position of 0, and then the second value is the actual object we want to add to this list. Let's say we want to add the number 10, now when we print this list you can see that the number 10 is placed at the beginning of the list and all the other items are pushed to the right. We can also remove an item so we call remove and pass the item that we want to remove 5. Now we print our list so we see 5 is gone, and we have 2, 1, 7, 4. If you want to remove all the items in the list, you can call the clear method, so, clear this method doesn't take any values, so, we simply call it and it empties our list, all the items are removed.
02:08:28
We also have another useful method called hop, and with this we can remove the last item in a list. Deixe-me te mostrar. So, we run our program, you can see the number 4 is removed from the end of our list. Now if you want to check for the existence of an item in our list, you can call the index method. So, we call index and pass a value here, like 5 and this returns the index of the first occurrence of this item. So let's print this on the terminal. We don't need this line anymore. Então o index of 5 is 0. What if we pass a number that doesn't exist in this list? Let's say 50? Run the program, we get an error. We get a value error. 50 is not na lista. There is also another way to check for the existence of an item, we can use the in operator. So, let me show you we type our 15 in numbers, earlier we used the in operator with a string, we
02:09:32
check for the existence of a character or a sequence of a character in a string, now here we're checking for the existence of 50 in the list of numbers, so let's print this, we get a boolean value, false, so unlike the index method, this expression, doesn't generate an error, so it's safer to use this. We also have another method for counting the occurances of an item, let's say we have another 5 over here. Now we can call numbers.count and pass 5 and this should return 2 because we have 2 5s in this list. Dê uma olhada. Ai está. That is pretty useful now if you want to sort your lists you can call sort method. Assim, we call the sort method here, this method doesn't take any values so, look at he return value, that is none, none is an object in python that represents the absence of a value. So this sort method doesn't really return any values it simply sorts this list, in place, so instead of printing the return value
02:10:36
oft his method, we simply call it to sort our list and then print our list. Dê uma olhada. Now, all the items are assorted in ascending order. Nós também podemos sort the items in descending order, so after we sort the list we can call the reverse method. We can simply reverse our list. Now let's go ahead and run our program, take a look. Our numbers are sorted in descending order. And one last method I want to show you here that is pretty useful is the copy método. So copy, with this method you can get a copy of our list. So let's define another variable called numbers 2, now numbers 2, is a copy of our original list. Então se you make any changes to our original list, if you add new items to it, if you remove existing items, these operations are not going to impact our second list. Deixe-me te mostrar. So after we show you a copy of our numbers list let's add a new item to this list, so numbers.apphend dez. So the first list is updated, so now we have a
02:11:40
new item in our first list, then lets print the second list. Take a look, we don't have the number 10 here, because these are 2 independent lists. So these are all the operations that we can perform on lists. We can add new items to a list, we can remove exxisitn items, we can check for the existence of an item, we can sort our list, and copy them. Now here's an exercise for this tutorial, I want you to write a program, to remove the duplicates on our list. Again, this is a fantastic exercise. So spend a few minutes on this and then come back and continue watching. Alright let's say we have a list of numbers with a bunch of duplicates. So 2, 2, 4, 6, 6, 3, 4, 6, 1. We want to remove the duplicates. So we need to define another list let's call that new list. Initially we set it to an empty list. Then we need to iterate over our first list, get each item, and if we don't have that number
02:12:44
in this unix list, then we'll add it to this second list. Tão simples como isso. So, for number in numbers, now we need to check to see if we have this number in the second list. So we use the in operador. If number not in units so if we don't have an operator in this units list, then we'll need to add it, so units. apphend number, that's all we have to do. So, let's go ahead and print the units list ai está. So you have 2, 4, 6, 3,and 1. The duplicates are removed. In this tutorial I'm going to talk to you guys about another important structure. in Python called tuple. Tuples are similar to lists so we can use them to store a list of items. But unlike lists we can not modify them, we cannot add new items, we cannot remove existing items, we
02:13:52
tuples are immutable. We cannot mutate or change them. assim deixe-me te mostrar. So I'm going to start by defining a list of numbers, 1, 2, 3, 4, so we use square brackets to define lists and parenthesis to define tuples, so if we change this to parenthesis, 1, 2, 3. Now we have a tuple. So if we type numbers. look here we don't have the append or insert methods, so we cannot add new items to this tuple. We also don't have remove clear and pop, we cannot remove any of these items here. We only have two methods, count, and index. We use count to count the number of occurrences in an item, and index, to find the index of the first occurrence, of an item. So we can only get information about a tuple, we can't change it. And by the way, these other methods that you see here, they start with two underscores, we refer to these as magic methods, they're more of an advanced topic, so they go beyond the scope of this tutorial. If you're interested to learn bout them. You can get my python course, I've covered them in detail.
02:14:56
So similar to lists you can address individual items using squre bracketts,so we can get the first item like this and then print another terminal, there you go, the first item is 1, but if you try to change the first item we'll get an error, so, numbers of 0, we set it to 10 and run our program ai está. We get this type error, because the tuple object does not support item assignment. So we cannot mutate or change tuples, they are immutable. Now practically speaking, most of the time you'll be using lists, but tuples are also útil. If you want to create a list of items and make sure no where in your program you accidentally modify that list, then it's better to use a tuple, In this tutorial I'm going to show you a powerful feature we have in python called unpacking. So lets find a tuple called coordinates and here we pass 3 values, 1, 2, 3. So you imagine these are
02:16:00
the coordinates for xy and z. Now let's say we want to get these values and use them in a few expressions, a few complex expressions in our program. Maybe we want to include them as part of a large complex formula. So together we'll have to write code like this, coordinates of 0, then let's say we want to multiply this by coordinates of 1, and then multiply it by coordinates of 2, our code is getting a little bit too long, this is just a very simple example. But let's say we want to use these values in quite a few places in our program, a better approach is to get these values and store them in separate variables like we can get coordinates of 0, and store it in x, then you can get coordinates of 1 and store it in y. And similarly we get coordinates of 2, and then store it in z. Now we started repeating coordinates of 2 or coordinates of 0 multiple times, we can simply work with these variables, x times y times z, that is better.
02:17:04
Certo? So nothing new so far. But in Python we have a powerful feature called unpacking and with that we can achieve the same result with far less code. So we can define our variables x, y, and z. And set them to our tuple. What we have on line 6 is exactly identical to what we have on lines 2-4. So this is a shorthand to achieve the same result. So let me delete this and explain how this code works. When Python interpreter sees this statement, it will get the first item in this tuple and assign it to the variável. Then it will get the second item in this tuple, then similarly we get the third item in this tuple and assign it to the third variable we have here, so we are unpacking this tuple into 3 variables. Now if we print x you can see x is 1, similarly y is 2, there you go.
02:18:08
So this is unpacking. And by the way this is not limited to tuples, we can use this feature for lists as well. Assim, if I change parenthesis to square brackets, now coordinates is a list, so we can unpack our list into 3 variables now we run our program we can see y is 2. In this tutorial I'm going to talk to you about dictionary in python. We use dictionaries in situations where we want to store information that comes as key value pairs. Aqui um exemplo. Think of a customer. A customer has a bunch of attributes like name, email, phone number, address e assim por diante. Now each of these attributes has a value. For example the name can be jon smith the email can be jon@ gmail.com the phone can be whatevr so what we have ere is a bunch of key value pairs. Então, nesse example, our keys are name, email, and phone, and each key is associated with a value. So this is where we use
02:19:16
a dictionary. With a dictionary, we can store a bunch of key value pairs. So let me show you how to define a dictionary in python. Back to our program, I'm going to define a variable, customer, and here we set it to curly braces. With these curly braces we can define dictionary. In this example we have an empty dictionary that doesn't have any key value pairs. Now we can add one or more key value pairs in between the braces. Então vamos add a key value pair here, I'm going to set the key to a name, and the value to John Smith, then we add a comma, to add another key value pair. So let's set age to 30 let's add another key value pair is underline verified and we set this to a boolean. Now what matters here is that these keys should be unique. So if I add another key value pair here, set age to 40, now look pycharm has highlighted the age key, because we have duplicated that and
02:20:20
isso não é permitido. So each key should be unique in a dictionary, just like, the dictionaries we have in the real world, in a real dictionary we have a bunch of words and they're definition each word is only listed once in a dictionary. We don't have the word book twice. So let's delete the second duplicate key value pair, so the keys should be unique, and in this example, I'm using strings, but they can also be numbers, we're going to look at that later, but the value can be anything, it can be a string, a number, a boolean, a list, literally anything. Now we can access each item in this dictionary using square brackets. So, we type customer, square brackets and then specify key like name and this will return the value associated with the name key. Let's print it on the terminal, have a look, there you go, so, the name is John Smith, now what if we pass a key that doesn't exist, lets say first date. You run the program, you get a key error because we don't have
02:21:24
a key called birth date. Also, if we spell name with let's say a capital N, we get the same error because we don't have a key with the exact same sequence of characters in this dictionary. Now to get around this we can use the get method, so instead of using the square brackets we call the get method and specify the key Now if you use a key that doesn't exist here, it doesn't yell at us. Por exemplo, if you pass birth date it simply returns the non value. Earlier I told you that none is an object that represents the absence of a value. assim instead of getting a key error we get none and we can also option supply a default value, for example, if this dictionary doesn't have this key, we can supply the default value, let's say January 1st 1980. Let's run the program now instead of getting none we get this default value. So, this is how we can access the value associated with the key
02:22:28
in a dictionary. We can also update these values for example before a print statement we can write code like this, customer of name, let's update the name to jack smith, now this little warning is telling us here we can put jac smith here instead of defining it once, and then update isto. Don't worry about them, it doesn't really matter. Now with this line if we print the name of this customer, we should see jack smith, let me show you. So, I'm going to use the square bracket notation again, let's print the name of the customer you can see that is updated here, we can also add a new key here, let's set the birthdate to some value like january first 1980. And then we can print it here, so as you see we can easily add new key value pairs to a dictionary. So this is the basics of using dictionaries in python. They're extremely important and they have a lot of applications in the real mundo. Okay, here's an exercise for you. Então aqui nós temos
02:23:32
this program that asks our phone number. Let's type 1 234. We type it in digits and then this will translate it, to words, take a look. Enter, it prints, 1, 2, 3, 4. That's a pretty cool program, so go ahead and spend a few minutes on this exercise, it's pretty easy, I will see you Próximo. Alright, so first we need to get the users phone number, we call the input function with the label phone, we get the result and store it in this variable, now let's say the user enters 123 4. So we need to look through this string, get each character and translate it to a world, so what we need to implement this scenario. is a dictionary, because a dictionary is a structure that allows us to a key to a value. So we can have a dictionary with keys like 1234. And we map each of these keys to a word. So we cannot put digit 1 to the word 1 we can map 2
02:24:36
to two you get the point. So let's define a dictionary, you can call it digits, underline mapping now this dictionary I'm going to add a few key value pairs. One, we map it to 1, 2, we to 2, 3, to 3, and finally, 4 to 4. Now technically we should add all the digits from 0 to 9, but I don't want to waste all your time typing repetitive things here, you got the point. So lets move on, now we need to look through the phone string. assim 4 character in phone, we get each character and then use it to access a key value pair in dicionário. So, digits underline mapping we can use square brackets or call the get method, I would prefer to use the get method, so in case the user enters some character that is not part of our dictionary, our program is not going to yell at them. So, we call the gt method and pass this character
02:25:40
a the key, and if we don't have this key, we can supply a default value like exclamation mark, so with this we get a word now we need to add this word to an output string, so we can define an output string, initially we set it to an empty string, in each iteration we get this and add it to our output string. So, we type output, plus equals. This and we should also add a space at get. So the words are not close to each other, okay? That's all we have to do. Now finally let's print this output, run our program, so I want to type 1, 3,4, 5, lets veja o que temos. We get 1, 3, 4 with an exlamantion marca. In this tutorial I'm going to show you something really cool that you can do with dictionaries, so here in this program you can type a message like good morning followed by a smiley face,
02:26:44
when we press enter, we get this beautiful smiley face, or we can type i am sad, with a sad smiley face and it gets translated to this beautiful emoji. So this is another application if using dictionaries, we have a dictionary that maps these characters into smiley faces. So lets go ahead and build this program together, we start by calling the input function, here we pass a greater than symbol as an indicator for the user to type a message, we give that message, store it here, as you know that is a string, now we need to split this string by a space, so if the user types good morning with a smiley face, we want to break this down into 3 words, good morning, and smiley face. To do that we can call the split method. So we call message.split and pass a string with one space as a separator. What this method does is basically it goes through this string and anywhere it finds this
02:27:48
character, in this case a space, it uses it as a boundary to separate this string into multiple words. And then it will return a list. Deixe-me te mostrar. So let's store that here, words, and then Then print it on the terminal, let's go ahead and run our program. So if you type good morning sunshine, enter, we get a list with three items each item is a string, okay? Agora, back to our program, we need to define a dictionary for mapping special characters like these 2 into a smiley face, so, we can call that emojis set it to curly braces, here we add a key value pair, a smiley face, and we map that to a string, in this string we want to add an emoji, if you're on a mac keyboard you can press control command and space and this should bring up this emoji box, if you're on Windows honestly I really don't know how you can do this, but there must be applications who do this for you. So lets go
02:28:52
ahead and pick this happy smiley face, good, now lets add another key value pair, or sad face we map this to, this face here, good. So, we have a list of words now we need to look through this list, get each word and potentially map it to an emoji. So we can write a for loop for word in words, now we want to go to our dictionary, and see if you have an item with this word as the key. If you have an item with that key, we get it's value, otherwise we want to use the same word. So if a user types good morning, we don't want to translate those words, we just want to return those. So that is the case, where we use the get method to supply a default value, so we wan to get an item with a key word, and if we don't have an item with that key, we simply use that word as the default value. Now similar to the exercise that we did in the last tutorial we need an output variable. So let's define that here,
02:29:56
output set it to an empty string, now back to line 9, we get the return value of the get method, and add it to our output variable. So output plus equals whatever we get from the get method, and finally we need to append a space at the end. É isso, terminamos. So let's print the output and run our program and I'm going to type good morning sunshine with a smiley face, we get that beautiful, let's try the sad face as well, I am sad. Que pena. Lindo! Então, como você pode ver dictionaries have a lot of use cases in real applications. Here's a solution from the last tutorial where we created an emoji conversor. Now so far we have been writing all our code right here, in app,py, but as our programs grow we need a better way to organize our code. We need to break up our code into smaller, more manageable and more maintainable chunks which we call functions. So function
02:31:04
is a container for a few lines of code that perform a specific task for example you have learned about a few of the built in functions in python like print, and input, each of these functions have a purpose, they know how to perform a specific task. Então, quando nós build large complex programs, we should break up our code into smaller reusable chunks which we call functions to better organize our code. And that's what I'm going to show you in this tutorial. So let's write this simple program, for printing a greeting message. So we're going to do a print, hi there, and lets add another message welcome aboard. So here we have a simple program with only two lines of code. Now let's say these two lines potentially we're going to need them in other programs so we can put them in a function that we can reuse. Let me show you how to do that, so, we start typing out death, that is a reserve keyword in Python, and it's short for define. When Python interpreter sees this it knows that we're defining a function, next we need to give our function
02:32:08
a name, lets say greet_user. So all the best practices you learned about naming your variables also apply here, which means we should name our functions with lower case characters if there are multiple words, we need to separate them using an underscore and you should always, always, always use meaningful descriptive names for your functions. So, here we define a function called greet user, after that we'll need to add parenthesis followed by a colon. Now you know that whenever we add a colon at the end of a line we're telling python that we're defining a block of code. Então, quando nós press enter, the next line is indented. Now any code that we write here will belong to this function. So I'm going to move these two lines these two print statements inside of our function. You can simply press tab to indent them, beautiful, also lets remove this extra line break, that is better, so these two lines now are part of our greet user function, so whenever we call this function, these two lines will be executed. OK? Agora,
02:33:12
let's remove indentation so here we are outside of our function, let's do a print statement and print start after that let's call our function, so greet user. And finally let's do another create statement and print terminar. Now we have this little warning here, this underline, if you hover your mouse over this line, this tool was telling you that we should add two blank lines after a function definition. This is coming from pep8 which is a document that defines the best practices for formatting our code. We'll look at that in the future. So for now to make pycharm happy, lets add an extra line break to this function so whenever we define a function we need to add two lines breaks after. OK? so, now let's run our program and see what happens. Alright, so we have 4 messages on the terminal first we get the start message then we get the messages coming from our create function, so either and welcome aboard, and finally we see the finished message. So let me explain the flow of our program
02:34:16
when python runs this code it doesn't actually print these two messages on the terminal because these two lines of code are inside of this function, so they would only get executed if we call this function. If we don't call this function, these lines don't get executed. OK? So the execution of our program actually starts here, the first message that we see on the terminal is the start message. Depois de that, Python sees that we are calling the greet function, so it will jump over here and then execute these two lines. Then, it will jump out of this function and continue the normal execution of our program so it will print the finish message on the terminal. So this is how functions work. Also note that the order of this code matters, so here we're calling the greet function after after we have defined it. If you try and call it before you define it you will see an error. For example, if we call the greet user function right here, see we immediately get this red underline which says unresolved reference, greet user which basically
02:35:20
means python doesn't know what is this greet user, it's not defined anywhere. So we always define our functions first, and then call them. Here's a function we created in the last tutorial now I got a question for you, what is the difference between calling this functions nd the print function of python? A diferença is that the print function takes some information, in this case the message that we want to print, but our greet function doesn't take any information. Wouldn't it be nicer if you could pass the name of the user here and then instead of saying hi there, you could print the name of the user. Assim, in this tutorial, I'm going to show you how to pass information to your functions, and that is pretty easy, so back to the definition of our greet user function, inside of these parenthesis, we can add parameters these parameters are pale holders for receiving information. For example, you can add a name parameter, and we can pass the name of the user when calling this function. So let's pass Jon
02:36:24
here, now when we call this function and pass this value this name parameter will be set to Jon. Então isso will act like a local variable that we defined inside of this function. Just imagine, we didn't have this parameter, and instead we had a variable like name that was set to jump. Now here we could simply print the name of this user, so we could use a formatted string, and print the value of the name variable, right? Agora, we don't really have this local variable defined in this function we have a parameter, it's exactly the same thing. assim with these parameters we can receive information in our functions. Now let's go ahead and run this program, so take a look. We get Hi John welcome aboard, we can take this to the next nível. Now we can call this function one more time. assim greet user, and this time supply a different name. Let's say Mary. So we are reusing our greet function and passing it a different valor. Imagine if we didn't have this function you would have to
02:37:28
repeat this line twice , once for hi jon and another time for hi mary. So this is the benefit of defining functions, we can take a few lines of code that have a specific purpose and put them inside of a function, so now let's run our program one more time ai está. So you get hi job, welcome aboard, then you get hi mary welcome aboard. Now note that when a function has a parameter we are obligated to pass a value for that parameter. So if you remove jon from here and run our program, we get this type error, greet user, missing one required positional argument. Argument in programming is the value that we supply to a function, so back to this example, marrying this case is an argument that we pass to the name parameter. And lot of programmers don't know the difference between parameters and arguments and think they are the same. But they are not, parameters are the holes or placeholders that we define in our function for receiving information,
02:38:32
arguments are the actual pieces of information that we supply to these functions. OK? So, let's bring back this jon string, now we can also define multiple parameters, for example, let's rename this parameter to first name as I told you before, you can right click here, go to refactor and then rename, or preferably you can use a short cut. So the shortcut for this on Mac is shift and f6. And this brings up the renamed dial up box, here we can change this to first underline name. Now we can add a second parameter so comma followed by last underline name so back to our formatted string, let's also print the last name, beautiful, so here when calling this function, then we can supply another argument so jon smith and lets delete this line we don't really need it anymore run our program, take a look, hi jon smith, so in the last tutorial you learned that whenever
02:39:40
we define parameters for our functions we should always supply values otherwise we'll get an error. Let's look at that error one more time. So In going to delete this second argument and only pass jon. Run our program, we get this message, greet user missing one required, position argumento. So these arguments that you have here like jon and smith you refer to these as positional arguments. Which means their position or argument matters. Em outro words, the first argument we add here is the value or the first parameter and the second argument is the value for the second parameter. So if you change their position or order, we'll get different results. Vamos dar uma olhada. Let's pass smith first and then jon. Okay, good, delete, now let's go with this, so instead of getting Hi Jon Smith, we get hi smith jon. So that is the reason we refer to these arguments as positional arguments, they're positioned or
02:40:44
order matters. But in python we also have keyword arguments, and with those the position doesn't matter. Let me show you how they work. Assim, let's say here you want to pass Jon as the value for the first name parameter. We can simply specify that here. So first name equals jon. Now what we have here is a keyword argument. the key word argument. So this combination of having the parameter name, followed by it's value is what we call a keyword argument, and what we get with this keyword argument the position doesn't really matter. So here we're supplying Jon as an argument fort he first parameter. Now similarly, we can use a keyword argument for smith, so last name equals smith, so that we have 2 keyword arguments. So with these keyword arguments we don't have to worry about the order of the parameters. Now that doesn't mean we should always use keyword arguments. Na verdade não. Most of the time we use positional arguments, but in certain situations these keyword arguments helming us improve the readability of our code. So on line 7 it's quite clear
02:41:48
that we are supplying smith as the last name and jon as the first name. Now in this particular example, even if we didn't have the keyword arguments, just passing two positional arguments like jon and smith, would be sufficient, because it's easy to guess what is the purpose of these arguments. But sometimes you're dealing with functions and you're passing numerical values to them, in those situations it may not be quite clear what those values represent. Let me show you an example. Let's say we have a function for calculating the total cost of an order, so we still call that calculate, underline cost, so when calling this function, you need to supply three pieces of information. One is the total cost of all the order items lets say 50 dólares. The other is the shipping cost, let's say 5 dollars, and the last piece is discount, let's say 0, .1. Someone reading this code, may not be sure what these three values represent, in this case, we can improve the readability of this code, by using keyword arguments. Então nós podemos
02:42:52
prefix each value with the name of parameter they target, for example, we can set total to 50 and then shipping to 5, and then discount to 0.1. Now if you give this code to someone else, they can immediately tell what these values represent. So that is the power of keyword arguments. So here's what I want you to take away. For the most part, use positional arguments, but if you're dealing with functions that take numerical values, see if you can improve the readability of your code by using keyword arguments. You simply prefix the arguments that you pass with the name of their parameters and this will increase the readability of your code. Now there is one more thing you need to know about keyword arguments. These keyword arguments should always come after positional arguments. Deixe-me mostrar o que quero dizer. Assim, back to our simple greet user function, let's use a keyword argument for the first thing. So, let's set first name to jon and see what happens. So we immediately get this error and
02:43:56
positional argument after keyword argument. So when calling this function we're supplying one keyword argument and one positional argument, and python doesn't like this. Assim, if you're mixing positional and keyword arguments, you should always use and then the keyword arguments. In other words, lets remove this keyword argument here, so jon is now a positional argument, is targeting the first parameter. Now after this positional argument we can supply any number of keyword arguments, so if you set last name to smith look, python doesn't have any problem with this because we are adding a keyword argument after a positional argument. So let's quickly recap, for the most part use positional arguments if you're dealing with functions that take multiple numerical values and it's not quite clear what those values represent, use keyword arguments to improve the readability of your code, and finally if your passing both positional and keyword arguments, use the
02:45:00
keyword arguments after the positional arguments. So far you have learned how to create functions and send them information using their parameters in this tutorial I'm going to show you how to create functions that return values, this is particularly useful if you're doing some kind of calculation your function and you want to return the result to whoever is using your função. deixe-me te mostrar. So let's start by defining a function, called square, this function simply calculates the square of a number. So we need to add one parameter here, that is is our number, now here we want to calculate number times number, that is the square of a number. Now to return this color outside of this function we simply use the return statement. So return. Agora, our square function is very simple, it only had one line of code. But in a real program, you might have a function that has ten lines of code to calculate alguma coisa. So, this return statement is very valioso. So now we can return values to the caller of our function.
02:46:08
So, with this, when we call the square function, let's say we give it 3, now this function returns a value, just like an input function of python, this input function waits for the user to type something and press enter and then it will return the user's input as a string so we can get it and store it in a variable like this, right? We have the same story with our story, with our square function. So our square function returns the value we can simply get it and store it in a variable. Let's call that resultado. Now, we can print result on the terminal, there you go, so result is 9, we could also pass this function called directly inside of the print function without defining a separate variable. Sometimes this is useful for writing shorter code, so in this case. So, in this case, we don't really need this result variable. We simply want to print the square of 3. So, we could simply pass this function call right here, as an argument for the print
02:47:12
função. So let's delete this variable now our code is shorter so with this we're calling the square function, this returns a value and we'll pass that value as an argument to the print function. OK? When we run this program, we get the exact same resultado. Ai está. Now what happens if we don't use a return statement in our function. So in the last example we simply used a print statement. Let's temporarily remove this return statement and print the result on the terminal. Como isso. So let's run our program one more time and see what we get. We see two things, the number 9, and none. O que esta acontecendo aqui? Bem when Python interpreter executes this code, first it will call the square function. So the control moves to the square function here we calculate the square of this given number and then print it on the terminal. That is the reason we see 9 right here, now, by default, all functions return the value
02:48:16
none. So if we don't have a return statement here, by default python returns none. Nenhum is an object that represents the absence of a value, it's like nothing or null ic, c++ java and Javascript. So, in this example, we didn't have a return statement, and by default python returned none from this function. So, after this square function is executed, the value none is returned and passed as an argument to the print function, that is the reason we see none on the second line. So here are the two things you need to take away from this tutorial. By default all functions in Python return none. You can change that, so if you have a function that calculates something, you can return the result using the return statement. Here's the code for our emoji converter program that we wrote earlier. If you missed that tutorial, make sure to go back and watch it, as I told you before, there is a table of content right below this video in the descrição. So we can simply click on the emoji converter tutorial to watch it.
02:49:24
Now, your exercise is to reorganize this code using a function. So I want you to extract a function in this code, because this algorithm for converting these smiley faces into emoji's is something that we probably want to use in a couple different applications. We can use it in a chat application in an email application and so on. We don't want to write all this code every time we want to convert these characters into smiley faces. So, out of all these lines of code that we have from line 1 to line 10, the lines 10-2 belong to our algorithm, all these lines together implement this feature. So, you should put these lines in a separate function, Now, why don't we have the input in this function? Porque the input will can come in different forms, currently we're using the import function to receive the input from the terminal, but in other applications we might receive the input from a graphical user interface, so the input can come in different forms. We don't want to put that in our function, because this line will not be reuseable. You want to give our function the actual message,
02:50:28
as a string. We don't care how we got that message. Em um program you might get it from the terminal, in another program you might get it from a graphical user interface. So that is the reason this line up code should not be in that function. By the same function, you shouldn't include the last line in that function because what we do with the output is different from one program to another. In this program, we are printing the output in another program, you might send an output as an email, or as a response in a chat application, so as a general rule of thumb you're function should not worry about receiving input and printing it. These lines of code should not belong to your functions. So go ahead and reorganize this code by extracting a function. Alright, on the top, first we need to define our function. So first we type def, give our function a name like emoji_ converter, so the name of this function clearly tells me what isso acontece. Each function should be responsible for one and only one task, and that task should be clearly explained in the name of the function.
02:51:36
So, our emoji converter function should take a parameter, we call that message, that is a string, right? Colon now we need to move the lines 5 all the way to the end of our for block into the function, so let's select all these lines, you can cut them from here, by pressing command and x on Mac, or control and x on Windows, then we paste it here, as you can see these lines are automatically indented so, they are part of the emoji converter function, if this didn't happen on your computer, make sure to select these lines and use the tab to indent them. Alright, so here's our emoji converter function lindo. Now after that in the main flow of our program, first we get the input from the user we store it in this variable message and then we call emoji converter and pass this message, this function should return a value, that is what we use to calculate
02:52:40
the end of this function, so right after this for block we need to add a return statement, return output, now that our function returns a value, we can get it and store it in a separate variable, let's call that result and then we can simply print that here, or we can make this code shorter, we don't really need this code here so we can simply call the emoji converter, and print the result. Como isso. Now here we have an underline because as I told you before we need to blank lines after our function definitions. So currently we have only one blank line we need to add another black line, good, let's go ahead, and run this program, and make sure everything works as before so I'm going to type a message like good morning with a smiley face good, let's run it one more time, times that, to add okay beautiful, so, here's the final result, we defined this function called
02:53:44
emoji converter, this function takes a parameter called message. And finally returns the output. In this tutorial I'm going to teach you how to handle errors in your python programs, so let's start by writing a small program to get the user age from the terminal. So we call the input variable input, and a label here, like age, this returns a string, so we need to pass it to the end funciton and store the result in a variable called age, now let's print age to make sure you have implemented everything properly we run our program, we type 20, 20 is printed here, beautiful, now look at the exit code of this program, exit code 0 means our program terminated successfully, there were no errors, but what if we run this program one more time and instead of entering a numerical value, we enter something like asd. We get a value error with his message invalid literal
02:54:52
for int with base 10. Basically what this message is telling us is that this string asd does not contain a valid home number that can be converted to an integer. Now look at the exit code of this program, exit code 1 means our exit code crashed, so 0 always means success and anything but 0 means crash now as a good python programmer you should anticipate this situation. You don't want to let your entire program crash just because the user entered an invalid value. So instead of letting the program crash you should handle the situation and print a proper error message, and that's what I'm going to show you in this tutorial, now before we get any further look at the type of error we get here, value error, so remember this, we're going to get back to this shortly now how can we handle these errors, in python we have a construct called try accept we use that to handle errors. Deixe-me mostrar como isso funciona. So on the top we type try: now as you know we are defining
02:55:56
a code block so, I'm going to move these two lines, inside of our try block so press tab here. And remove this black line, now these two lines are part of our try block, right? So after try we type accept, and then we add the type of the error that our program may encounter, that is value error OK? Then, we add a colon and in this block we can define what should happen if our program encounters an error of type value error. In this case we want to print a proper error message, so print, invalid value. So with this try and accept we are telling python hey, go ahead and try running one or these two lines of code, if you encounter, an error of type. Value error then instead of crashing the program, try this error message on the terminal so this is how this works. Now more accurately in programming we reefer to this kind of error as an exception. So an exception
02:57:00
is a kind of error that crashes our program. So our user enters an invalid value, this line of code in line 2 will raise an exception, and on line 4 will catch it and print this error message, so our program will no longer crash. Deixe-me te mostrar. So let's go ahead and run this age 20, everything works just like before and the exit code is 0, let's rerun this program, and enter asd, so we get this proper error message invalid error menu and once again the exit code is 0, so that means our program completed successfully. Didn't crash, now, we can also handle different kinds of errors or exceptions, for example right when we get the age let's define a variable income and set it to 20,000. And then define another variable called risk and set it to income divided by age. Let's run this program and enter 0 as the game to see what happened.
02:58:04
So 0 is obviously a numerical value so when we enter this value, technically we shouldn't get any exceptions. Dê uma olhada. Our program crashed, we did a 0 division error, because we cannot divide a number by 0. Once again look at the exit code, so we couldn't catch this kind of error or this kind of exception with this accept block. Accept block is only cashing exceptions of type value erro. And this happens when we try to convert a nonnumerical value, to an integer. So in a situation like this. We should handle different kinds of exceptions, we can add another except statement for an exception of type 0 division error. Now in this block we can print a different kind of message, like age cannot be 0. Let's run our program one more time. Agora, I'm going to enter 0 as the age so we get this error message age cannot be 0 and look at the exit code.
02:59:08
It's 0, so our program didn't crash, so to recap, we `used try accept blocks to handle exceptions that are raised in our programs, as a good programmer you should always anticipate these kind of exceptions and handle them properly. In this tutorial I'm going to talk to you guys about comments in python. We use comments to add notes or comments to our programs. For example, here I'm going to make a print statement, sky is blue. Now, before that, I can add a comment using a hi sign and then whatever we type here is going to get ignored it's not going to get executed. Let me show you so let's run this program, look we only see this mensagem. Sky is blue. So with this comment we can explain something about our code, we can use it as reminders to fix things or clear things up, or we can use it to communicate things with other developers reading our code, why we have written this code in a certain way. These are good use cases for using comments, we can also
03:00:16
have comments over multiple lines, so we can simply add more comments, each line should start with a new hi sign. Agora one thing you need to avoid when using comments is explaining what the code does. So here's an example of a bad comment. Let me just delete these two lines, and with this comment I'm going to say print sky is blue. Por quê is this a bad comment, because it's telling me the obvious, it's telling me this slide is going to print sky is blue. Now the problem with this comment is that apart from being verbose and repetitive, if you come here, and change sky to ocean, now this comment gets outdated. So overtime we change this code, then we have to come back and modify the corresponding comment. So I've seen some developers add comments in front of their functions, for example, they define a function let's say a square that takes a number and simply returns number times number. But it is obvious that this function calculates and returns the
03:01:20
square of the given number. So there is really no need to add a comment and explique isso. Calculates and returns the square of a number. This is very repetitive and it creates noiser code. Someone else reading your code they get distracted with all these unnecessary comments, so use comments to explain whys and hows. Not why's if you have made certain assumptions, we can use comments to explain those assumptions. Or we can use them to add notes to remind yourself or other developers to do something in the code. So comments are good, but too much of a good thing is a bad thing. In this tutorial I'm going to talk to you guys about classes in python. Classes are extremely important in programming and they're not specific to python, in fact, a lot of other programming languages do support the notion of classes. We use classes to define new types. For example, so far you have learned about the basic types in Python like numbers, strings, and booleans, these are the basic or simple types in python, you also learn
03:02:28
about a couple of complex types like lists and dictionaries. While these types are extremely useful, they cannot always be used to model complex concepts, for example, think about the concept of a point, or a shopping cart. A shopping cart is not a boolean, it's not a list, it's not a dictionary, it's a different kind of coisa. So we can use classes to define new types to model real concepts. Now in this new model I'm going to show you how to define a new type called point, and this new type is going to have methods for working with points. For example, back to our main program. Vamos create a list, numbers, 1, 2, 3, you know that here, when we type that dot, functions or methods available in list objects, now similar to this, we're going to create a new type called point, this point is going to have metas like move, draw, get, distance from another point, these are the operations that we can perform on points. So let me show you how to do this.
03:03:32
We start by defining a class by using the class keyword, and right after that we give our class a name. Now look at the naming convention I've used here. I've capitalized the first letter here, this is what we call a pascal naming convention. So the naming convention we used for naming our classes is different from the convention we use for naming our variables and functions. For variables and functions we always use lower case letters and we separate multiple words using an underscore. But when naming classes, we don't use an underscore to separate multiple words, instead we capitalize the first letter of every word. So in this case our class has only a single word, if you had multiple words, let's say email client look I've capitalized the first letter of every word. Once again, this is called pascal naming convention and it comes from the old pascal language that you might have heard of. So, back to our point class. Here we add a colon which means we're going to define a block, now
03:04:36
in this block we can define all the functions or methods that belong to points, for example, we can define a function called move for moving a port, now note that as soon as we type open parenthesis, pycharm automatically adds self here, this is a special keyword and we're going to get back to this shortly. So, for now, in this method, let's print move on the terminal, now let's define another method like draw, so define draw and in this method, let's print draw on the terminal, now let's remove the indentation, we're done with the definition of our point class, so we need to add two line breaks okay, so with this class we defined a new type with this new type we can create new objects, so an object is an instance of a class, a class simply defines the blueprint or the template for creating objects, and objects are the actual instances based on that blue print.
03:05:40
So we can have tens of hundreds of points on the screen, these are the objects or the instances. So to create an object, we type out the name of our class and then call it like a function this creates a new object and then returns it. So then we can store that object in a variable, let's call that point 1, there you go, now when we use the dot operator. Look, we have these two methods that we defined, draw and move, we also have a bunch of other methods that we start with two underscores, these are called magic methods we'll look at them later in the course. Now, let's call the draw method of our point object, and run our program so you can see draw is printed on the terminal. Agora apart from methods these objects can also have attributes and these attributes are like variables that belong to a particular object. Por exemplo, here, after we've defined .1. We can set .1.x to
03:06:44
10. And .1.1 to 20. Now we can easily print out these attributes, let's print .1.x and run our program one more time take a look, so the x coordinate of .1 is 10. Now we can create another object, let's call that.2 so .2 once again we type out the name of our class and then call it like a function. Now this object is completely different then the first object. So if you print .2.x look we get this attribute error, because this point object doesn't have an attribute called, so each object is a different instance of our points class. Lugar algum we can assign a value to .2.x. Vamos send that to 1, and then run our program so we can see the x coordinates of .2 is 1. So to recap we use classes to define new types, these types can have
03:07:48
methods that we define in the body of the class and they can also have attributes that we can set anywhere in our programs. You have learned how to create new types using classes now therein a tiny problem in this implementation. We can create a pooint object without an x or y coordinate deixe-me te mostrar. So point we create this object here, and before we set point.x let's print point .x run our program we get this attribute error which you saw in the last tutorial, so point object has no attribute called x This is the problem we have here, it is possible, to have a point object without an x or y coordinates. And that doesn't really make sense, because whenever we talk about a point, we ned to know where that point is located. To solve this problem, we use a constructor. A constructor is a function that gets called at the time of creating an object. So here on line 9, when creating this
03:08:56
point object, we want to pass values for x or y coordinates, let's say 10 and 20, and with this, this point object that we get here, will have it's x and y coordinates initialized. Então, como fazemos isso? We need to add a special method in this class called constructor. So, on the top, I define a new function, look at the name of this function, double underscore init, double under score. So init is short for initialized, and this is the function or the method that gets called when we create a new point object. Now, press enter, so this automatically adds, self in parenthesis, we're going to come back to this shortly. Now, right after self, we want to add 2 extra parameters, x and y, so let's type out x and y, and then in the body of this method, we should read the values past here, and use them to initialize our object, so when we pass 10 and 20, these arguments will be used for
03:10:00
x and y parameters. Now to initialize our object, we type our code like this. Self.x equals x. And then self.y equals y. What is going on here, this self that you see here is a reference to the current objeto. So, back to line 13, when we create a new point object, self references that object in memory, the same object, that we're referencing using this cariable. So earlier we typed point.x equals 10, with this code we set the x attribute of this point object. Now what we have in the constructor is exactly the same, we use the self to reference the current object and then we set the x attribute to the x argument passed to this function. Assim, using this init method, we can initialize our objects and we refer to this method as a constructor, this method is used to construct or create an object, okay? assim, Now, let's remove line 14, so we created
03:11:04
point object with these values and then print point.x let's run our program there you go, x is 10, we can also change these values later, so just before printing point.x we can set point.x to 11 and then run our program so x is updated, beautiful, alright, here's a exercise for you. I want you to define a new type called person these person objects should have a name attribute as well as a talk método. This is a very easy exercise so, you can tackle it in probably a couple of minutes. Tudo bem, então first we start with a class keyboard, we define this person class once again look at the naming convention I have used here, the first letter of the first word in this case the only word is uppercase. Now, in this class we define all the methods we need, currently we only have method that is the talk method, so define talk, pycharm automatically adds self, we come back to this shortly,
03:12:08
for now let's just print talk. So this is the body of our person class. We remove the indentation and add two line breaks after defining our classes. Now we can create the personal object, let's call that jon, we set it to person, we can call jon. talk, let's run the program so we get this message, beautiful, but our person objects should also have a name attribute, it doesn't make sense to have a person without the name. So that is when we use the constructor function. So on the top, we add a new method, at the name of this method is double underscore, init double underscore. Então nós call this method a constructor. Now in this method we need to add another parameter which is name, so we simply set self.name to name. Uma vez again, self references the current object, we're setting the name attribute of the current object, to the name argument passed to this method.
03:13:12
With this we can go back to line 9, and when creating a person object we pass the name, let's see jon smith now let's print jon.name and run our program ai está. So jon Smith is printed on the terminal, beautiful, so this is all you had to do as part of this exercise. Mas let's make this program a little more interesting. Instead of printing this boring message here, let's print hi, I am Jon Smith. So, we can use a formatted string with a message like Hi, I am, now we want to dynamically add the name of this person. Como vamos fazer isso? Well, look at the parameter of this talk method. Como eu te disse antes, every method in our class should have this parameter, self. And they should be the very first parameter of each method, okay? Assim, with this self we can get reference to the current object, so we can add curly braces and type out self .name. Thsi returns the name attribute of the current
03:14:16
person object. With this we can remove line 10, where we print jon.name and simply call jon.talk. Lets run our program. Hi, I am Jon Smith. There we go, beautiful. Now we can build another person object, let's say Bob, is a new person called Bob Smith, when we say Bob.talk. And run our program we get a different message, hi I'm Bob Smith, so each object is a different instance of a person class. In this tutorial Im going to talk to you about inheritance in Python, inheritance is a mechanism for using code and once again it's no limited to python, most languages that support classes also support inherence. So let ms how you how this works. Digamos we have this dog class with a simple walk method, in this method we're simply printing the walk message on the terminal, now let's say in real program, instead of just one line of code here we're going to have 10 lines of
03:15:24
código. Now, what if in the future we want to define a another class let's say cat and we want to add this walk method there as well. Sow e'll have to repeat all that code, in this new class, walk. Isto é mau. because you have repeated or duplicated our código. In programming we have a principle called dry which is short for don't repeat yourself. Let's say sometime in the future, we discover a problem with our walk method. Se vocês have repeated or duplicated this method in many other places, then we'll have to come back and fix that problem in every single place we have duplicated this code. So that's why in programming we should not define something duas vezes. So how can we solve this problem. There are different approaches, one approach that is easier to understand for beginners is inherence Now here's how it works. We define a new class called maml and move the walk method right there. Then we'll have the dog and cat classes inherit that method
03:16:28
from their parent just like how humans inherit certain attributes or behaviors form their parents. That' exactly the same, so on the top, we define a new class, let's call it mammal then we need to move the walk method there. Assim, we select it, cut it, using command and x on Mac, or control x on Windows and then paste it here, beautiful, now we want our dog class to inherit this class from the mammal class so right after the class name we add parenthesis and then type out the name of the parent class. In this case, mammal. That's all we have to do. So with his the dog class will inherit all he methods defined in the mammal class. Now there is a tiny problem here, if you look at line 9, there is a red underline here. A razão pela qual isso está acontecendo é porque python doesn't like an empty class, so right now our dog class is empty, it doesn't have anything, we either need to add methods specific to dogs or just to make Python happy,
03:17:32
we can use the path statement, and that basically means nothing. We're telling python interpreter, hey, pass this line, don't worry about it. But with this, we don't have an empty class, okay? Now as I told you before after each class I should have two line breaks so right now we only have one line break and that is the reason we have this little warning here, so let's add another black line, beautiful, so our dog class is inheriting the walk method from the mammal, you need to apply the same change to the cat class. So we'll have cat inherit from mammal, and then, use the path statement here. With these changes, now we can create either a dog or cat object, let's say dog, one, we set it to a dog object, and when we type dot look we have the walk method that is defined in the mamall class. We can easily call it, let's run our program there you go, you see the walk message, so both the dog and cat classes are inheriting all the classes
03:18:36
methods defined in their parent class. Now here we can add methods specific to dogs, for example, we can define a method called bark, and then print bark. Now, we don't need the path statement because we already defined one method in our dog class. So now when we type out dog1. look we have two methods one is the walk method that we inherited and the bark method that we just defined in the dog class. Similarly, we can add a method specific to a cat, for example, we can define a method called be annoying, I hate cats, so let's print annoying , now when we create the cat object, let's remove that, cat1 and type out cat1. you have these two methods dog and be annoying. So these are the basics of inheritance in python Now there is more to this that really goes beyond the scope of this beginners tutorial. If you're interested to learn more about inheritance and other mechanisms
03:19:40
for reusing code, I encourage you to get my complete Python course. In this tutorial, I'm going to talk to you about modules in python. A module in python is basically a file with some python code. And we use modules to organize our code into files. Just like sections in a super market. When you go to a super market there are different sections for fruits, vegetables, cleaning products, and so on. Nós não temos one section with all the products in the super market. We have the same concept in programming. So instead of writing all our code, instead of writing all the functions and classes in app.py we want to break up our code into multiple files. We refer to each file as a module. With this, not only is our code better organized and structured, but we'll also have the ability to reuse our code. Por exemplo, over here in app.py, I've defined two functions for converting weight from pounds to kilograms and vice versa. Now we can take these two functions and put them in a separate module called converters, and then we can import that module into any
03:20:48
program that needs these converter functions. Let me show you how to do this. So, let's open up our project panel and right click the project, go to new, and add the new file, we're going to call this file, converters.py. Then, we go back to app.py select all this code, cut it and then paste it into our new module. converters.py. With this we have cleaned up our app module it's not bloated with different functions, so as we write more functions with classes, we put them in their corresponding modules, a module should contain all the related functions and classes, okay? Now you want to import the converters module into our app module, and that is really easy, on the top we write import converters without extension, so we don't add .py we only type out the name of o arquivo. Let me close that project panel. Agora, this converter is an object so we can use the dot operator
03:21:52
to access it's members. So currently we have defined these two functions inside of our module, kilogram to pound, and pounds to kilograms. So we can easily call one of these functions let's pass 70 kilos get the result and print it out. Run our program, so, that is under 55 pounds. Now there is also another syntax for importing modules, let me show you, so instead of importing the entire module we can import specific functions from that módulo. Veja como isso funciona. We type out from then we add the name of our module, so converters import, now here if you press control and space we can see the list of all the functions defined in this module. So here we can grab one of these functions let's say kilogram to pound, and with this we can directly call this function just like the function defined in this file. App.py. Comparar what we have on line 4 to what we have on line 6. On line 6
03:22:56
we'll have to prefix this function with the name of an object converters. So we have to type converters. and then we'll be able to access this function. In contrast. When we import a specific function from our module, then we can easily call that function without prefixing it with the module name. Então aqui está o que you need to take away. We use modules to better organize our code. Ao invés de writing all the code, instead of writing all the functions in one file, you break up our code across multiple files. Each file is called a module and it should contain all the related functions and classes then we can import a module into another module, in this case, we are importing the converters module into our app module. And as you saw, there are two ways to import this module, we can import the entire module, and then we'll get an object with the same name as the module so we can type converters . and then we'll be able to access all the functions and classes defined in this module. The other appraoch is to impot a specific function or class from a module using the
03:24:00
from import statement. Lugar algum is your exercise. Earlier in the course you had an exercise for finding the largest number in the list. So here on the top we have a list of numbers, initially we set max to the first number in this list then, we look through this list, get each number, if the current number is grater than max, then we reset max. And finally when we are done with our loop we print max on the terminal. Now here's what I want you to do. This code currently has no organization. We don't have any functions, we don't have any modules, we wrote all the code in app.py, that is okay for small programs, but as your programs grow, you need to properly organize your code into classes and modules. So, as part of this exercise, I want you to write a function, call it find max. This function should take a list, and return the largest number in that list. Now after you do this, go ahead and put this function in a separate module. So extract it from here, and put it in a module,
03:25:04
called utils. So in this module we're going to have a bunch of utility functions, oaky? Then import the utility module into the current module and call this function. Finally, get the result and print it on the terminal, this is a fantastic exercise to teach you how to properly organize your code. Assim, go ahead and spend a couple minutes on this exercise. Então o primeiro step is to define a function called find max. Então no top, I'm going to define function, find max this function should take a list of numbers, so we add a parameter called numbers. Now inside of this function you want to have these few lines, this is the algorithm for finding the largest number in a list, we don't want to bring the first line, because this is where we create a list. So somewhere in our program we're going to create this list, and tehen pass it as an argument to pass max função. OK? So, let's go ahead and grab
03:26:08
these few lines, cut them, and put them inside of find max function. Alright, so we find the largest number in this list, finally we need to return it, so, return max. So here's our function. Agora nós need to move this into a separate module. So let's go to the panel right click the project and add a new file, we can also add a new python file that's the same, let's call that utils so if you add a new python file pycharm automatically adds .py extension, but if you go to new file we'll have to explicitly type out .py. So make sure to get the extension right. Now, back to app.py, let's cut this code and paste it into this new module, okay beautiful. Now I'm going o go back to app.py and import our new module. We can either import the entire module, so import utils and then access individual functions so we can call utils
03:27:12
.find max or we can explicitly import this function from the utils module. It doesn't really make a difference. So, we could type from utils import find max. And then we don't need to prefix this with the name of it's object, so we simply call find max. Now we need to call this after we initialize our list. So first we need to define the list of numbers. Then, we pass that list as an argument to find max we get the result which is max and finally we print it on the terminal. let's go ahead and run our program, so the largest number is 10, beautiful, now one last thing before we finish this tutorial, here we have this little warning under max and the tool tip says shadows built in name max. The reason we see this is because we actually have a function called max. And it does the exact same job as our find max function. So this is actually built into python.
03:28:16
But I ask you to do it as an exercise because it's a great exercise for beginners. Now, back to the warning, this warning is basically telling us that we are overwriting the built in max function in python so we are changing the meaning of this function, and this is considered a bad practice, let me show you what I mean. So let's comment out what we have on line 4, by putting a hash sign here, we can also use, a short cut command and slash on Mac, or control on slash on Windows. So now this line is commented out. Olhe para a color of max here, it's purple, it's the same color as print. And this is the color used to identify the built in functions. So now we can call this function and give it a list of numbers run our program we get the same exact result however, if we bring this line back, once again we can use the same shortcut that is command and slash on Mac or control slash on Windows. Now, we are redefining max, so up to this line, max used to be a function, but after line 4 is executed
03:29:20
max is set to an integer, that is the largest number in this list. So, we'll no longer be able to call it on line 5, let's run our program and see what happens. So there you go, we get this type error, int object is not callable, because max is now an integer, it's not a function, so we cannot call it. So to solve this problem, we can rename this variable to something else. So right click here. Go to refactor and rename, and rename this to maximum. So you can see the warning is gone. As you can see we have the same warning in our utils module. So here we're redefining max and as I told you before this is a bad practice. We're changing the meaning of built in functions in python. Assim, let's rename these as well, I'm going to use the short cut that is shift and f6 there you go and here we can change this to máximo. Enter, done.
03:30:28
In this tutorial we're going to talk about packages in python, packages are basically another way to organize our code, so currently we have only 3 files for modules in our project but a real project can contain hundreds or even thousands of modules. We don't want to add all those modules here, because over time this directory will get bloated with so many files, so a better approach is to organize related modules, inside of a package, so a package is a container for multiple modules In file system terms a package is a directory or folder. So in our project we can add a new directory and in that directory we can add all the directed modules, as a metaphor think of a mall. When you go to a mall or a shopping center there are different sections for mens women and kids clothing, so that is ilke a package, now when you go to the mens section, there are different areas fior different kinds of products, we have a section for shoes, t shirts, jackets, and so on, so each of these is like a module, so, in this tutorial, I'm going to show you how to create and use packages in Python,
03:31:32
here in our project panel, right click the panel and add a new directory. Let's call this directory e commerce. So we're going to create a package called e-commerce and in this package we're going to have all the modules related for an ecommerce application. Por exemplo, we can have modules for sales, shipping, customer service e assim por diante. Então vamos em frente Now here we have an empty directory, in order to convert this to a package we need to add a special file in it. So, right click this directory and add a new python file, call that file double underscore in it, double underscore this is a special convention in Python. When Python interpreter sees a file with this name and name in a directory, it treats this directory as a package, we also have a shortcut for that in pycharm so let me delete this directory and start again. So delete, once again right click
03:32:36
the project, and go to new but instead of creating a new directory we can create a new python package, let's call our package ecommerce as you can see pycharm automatically creates this file for us so we don't have to manually create isto. OK? Now, in this package, let's add a new module, so a new python file, let's call it shipping okay? Now in this module we want to have a function for calculating the shipping costs. So define calculate, underline, shipping. Now don't worry about parameters or implementation, we simply print calculate underline shipping. Now lets say you want to import this shipping module into our app module, with this new structure this shipping module is now part of the ecommerce package, so we cannot import a direct you have to start from the ecommerce package. Assim, bak to app,py once again there are two ways to import this module.
03:33:40
We can import the entire module or we can import one of it's functions or classes. So let me show you both approaches. First, we're going to import the entire module. Now what is the name of our package? it is ecommerce, right? So ecommerce. shipping. So instead of typing import shipping we type import ecommerce .shipping. we have to prefix it with the name of it's package. Now to access any of the functions or classes in this module we'll have to type out ecommerce.shipping. e ai você vai. Now we can access the calculate shipping função. So let's go ahead and run our program, we see this message printed on the terminal, beautiful. Contudo with this approach, every time you want to call one of the functions to this module, we'll have to prefix it with ecommerce. shipping. that is very verbose. So when working with packages we often use the second approach, using the
03:34:44
from statement. So we can type from ecommerce .shipping import calculate shipping. Now we don't have to prefix this function with ecommerce.shipping, and we can call it multiple times in this module, so our code is a little bit shorter. Mas e se you want to use multiple functions in this shipping module. We can either import them here, so calculate shipping, comma, let's say calculate_ tax. Or we can import the entire module and then access all he functions or classes in that module. Assim, let me revert this back. To import the entire module we type from ecommerce so we remove.shipping so from this package, import the shipping module. Now the shipping module, is an object so we can access all the functions and classes defined here, using the dot operator, so shipping. there you go, calculate shipping. Então para
03:35:48
recap, when using the from statement we can either start from the package and import a specific module, or we can start from package.module and then import a specific function. Like calculate shipping. So, this was the basics of using packages in python. As I told you before, packages are extremely important, especially when you want to work with a framework like django, we use django for building web applications with python, and I'm going to show you that later in this course. So in Django we have quite a few packages and each package contains several modules. So make sure to watch the tutorials, about modules and packages one more time, otherwise you're going to get confused later when we get to Django. In this tutorial I'm going to talk to you guys about the built in modules in python, so python comes with a standard library that contains several modules for common tasks such as sending emails, working with date and time,
03:36:52
generating random values and passwords and so on. There are so many modules already built into Python and that means there is already lots of functionality that we can reuse. Let me show you where you can find this standard library. So open up this browser and search for python 3, module index, make sure to add the version number, because the modules in python 2 are different from modules in python3. So here we search for python 3 module index, and the first page here, you can see is python module index, or python 3, let's go ahead, so these are all the modules built into python, for example we have modules for working with date and time, we have modules for sending emails for encoding values, there are so many modules here. Now the explanation of all these is beyond the scope of this course, that really requires it's own course. Because we have so many modules here, but don't let this list intimidate you. This is not something that you need to learn right now, as you learn python
03:37:56
as you build more applications, gradually you will get familiar with more modules here, in fact nobody knows all the modules in python standard library. Everybody knows some modules based on the applications they have built. So in this tutorial, I'm going to show you how to use one of the built in modules, for generating random values. So on the top, we import the random module, now because random is a built in module, we don't need to have a file here called random.py. So python interpreter knows that random is a built in module as long as it knows where to find it. Now if you're curious where this random module is stored on the disk, let me show you, so here in the project panel, expand external libraries, then expand python 3, and then one more time python 3.7 library route. So this is a folder somewhere on your computer, in this folder, we have all the built in modules in python. Assim, if you scroll down, you should be able to find.
03:39:00
The random module. Ai está. Está bem aqui. So random. py. You can open this and this shows you the source code of this module. ai está. Now in this tutorial, we don't want to worry about hat, so let's go back to our app.py, and use this module to generate random values. So when we import this module, now we have this object, random, so we can use the dot operator to acces it's methods. One method that is useful here is the random method, and every time we call it it generates a random value between 0 and 1. So here we can do a for loop, let's say for I in, range 3. So just to refresh your memory we are using the range function to create a range object. We can look through this range object and in each iteration this object will spit out a value. So with this for loop, we can execute this code 3 times. Agora vamos indent this. Okay, and finally, let's print the result, Ai está. So we can see
03:40:04
that in each iteration we get a new random value between 0 and 1. Now what if we want a random value for a particular age? Let's say random values between 10 and 20, well, there is another method here, rand int, we use 2 arguments here to specify our range, let's say 10 and 20. Run our program one more time. Now we have the numbers 20 13 and 18. If we run our program one more time, We get different values, so 20, 19, 11, one more time. Look, you also have another powerful method for randomly picking an item from a list. Let's say we have a list of team members and you want to randomly pick someone as the leader. Let me show you how to do that. So, we define the list of team members, we set it to jon, mary, bob, and mosh. Now we can call random .choice and pass our members list this method randomly picks a method from this list and returns it. ASSIM,
03:41:08
we can store the result in leader and then print it on the terminal. let's run our program, so now the leader is mary, if you run our program one more time this line is mosh now it's mosh again one more time, it really likes mosh, you get the point. assim the random module is very powerful, and it has a lot of applications. Now here's a very cool exercise. I want you to write this program to roll a dice. So every time we run this program we get a different value. Now we have 3 in 1, next time we get 3 and 6, one more time 5 and 6, 4 and 3, double one, that's a very cool exercise. So before we get started, I want you to pay attention to a few things. I want you to define a class called dice in this class we're going to have a method called rope so every time we call this method, we get a tuple, a tuple remember is a list of values but values cannot be changed, you cannot add a new item to it, we cannot remove it. So it's like a read only list. So every time,
03:42:12
we call the row method, we should get the tuple of two random values. So go ahead, and do this exercise, You'll see my solution next. Alright, we start by importing the random module on the top, then we define a class called dice: this class we want to have a method called row. So define row parenthesis, this automatically adds self, now in this method, you want to generate two random values between 1 to 6. So we call random.randint. And pass 1 and 6. So this generates the first number, we can ut that here, now let's call this one more time, so I'm going to copy what we have on line 5, put it here, and change this variable to second. So we have two variables first and second. With two random values, finally we need to return them, in a tuple, so return parenthesis instead of square brackets, first and second, now in python when you want to return a python from a function, you don't have to add
03:43:20
this parenthesis, so you can simplify your code and python will automatically interpret this as a tuple. So we are done with a definition of our class, we remove the indentation and add two line breaks. Now we create an object of this type so you set dice to dice next we roll the dice, so dice.roll and print the result on the terminal, that's all you have to do. Let's run this program, so now we get 2 and 5, lets run it one more time, 3 and 2, 1 and 1, beautiful. Now we have this little warning here, that says expected 2 black lines found 1. Once again this is coming from pep 8, pep is short for python and proposal. We have so many python enhancement proposals or peps. Pep 8 is a very famous 1, and in this document we have all the best practices for formatting our code. So pep 8 says, that after we define our classes we should have 2 lines breaks, we've already done that
03:44:24
so the reason this is complaining is because we had 1 line break before the class, so let's add one more line break, now pycharm is happy. So basically pycharm is following all the best practices defined in pep8. Now you don't have to memorize any of these best practices, as you code in pycharm, pycharm gives you a little more warning, and gradually you will learn how to properly format your code, so it's readable by other people. In this tutorial, I'm going to show you how to work with directories in python. So here in python3, module index, you can see we have a module called path lib which provides an object oriented file system pact. That basically means it provides classes that we can use to create objects to work with directories and arquivos. So, if you click here, you can see how this module works, we can see all kinds of examples. For example, here on there basic useage, you can see this is how we import the path class from the path lib module. Let me zooming so you can see
03:45:28
claramente. Okay, so look, from path lib, that's our module, import path, note the naming convention. P is capitalized, that means path is a class, so we need to create an instance of this class as you can see, right here, now there's so much documentation here, you can read this on your own, but let me quickly show you a few examples to help you get started. So after pycharm on the top, from the path led module, that's import the path class. Now we need to create, a path object to reference a file or directory on our computer. So there are basically to ways to do this we can use an absolute path, or a relative path which basically means a path starting from the current directory. Por exemplo, if you wanna reference this ecommerce directory in our project, we can use the relative path. So we start from the current directory and then go somewhere else. With absolute paths we start from the root of our hard disk. For example, if you're on Windows you might have
03:46:32
an absolute path like this, c drive, backslash, program, files, backslash microsoft, so these are directories in c drive. On Windows we use a backslash to build a path. If you're on Mac or Linux, your paths will look a little bit different, so instead of backslash we have a forward slash lets say user/local /bin. So these are examples of absolute paths. Em this tutorial we're going to work with he relative path to work with this ecommerce directory that we have in our project. Now if you didn't create this directory earlier, simply right click on the project and then go to new diretório. oaky? So, let's close this panel, we create a path object, now, if you don't pas an argument here, this will reference the current directory alternatively, we can pass string, in this string we can add a file or a directory. let's say the ecommerce diretório. Now this runs a path object, so we store it here,
03:47:36
now this path object has a few interesting methods for example, we can check to see if a path exists by calling the exist method. This simply returns a boolean so let's print it on the terminal, ai está. So this path exists, what if it changes to ecommerce 1, and run our program and get false, we can also create a new directory for example, let's change our path to email, now when we run this program, obviously we don't have this directory but we can create it by calling the mk dir method so make directory. Let's run our program alright, this method returns none which basically means it doesn't return any values. Now if you look at the project panel you can see here we have a new directory called emails, we can also delete this directory so, instead of mk dir we call rmdir which is short for remove directory, but let's go ahead, now we can see that directory is gone. We can also see
03:48:40
all the files and directories in a given path, that is, very useful if you want to write a little program to automate something. Por exemplo, you can iterate over all the spreadsheets in a directory one them and process them. Deixe-me te mostrar. First we change the path to the current directory and then we call the glob método. With his method we cans each for files and directories in the current path. So as the first argument we need to pass a string that defines a search pattern. We can type an asterisk and that means everything, all files and all directories. We can optionally add an extension, so to get all the files, you need the files you use star.star. Com isso pattern, we'll only get the files in the current directory. But not the directories. We can also search for all the py files, or all the excel spreadsheets. Qualquer coisa. So let's search for all the py files in the current directory, now when we run our program we get this generator object. Generator object
03:49:44
are kind of an advanced topic, and they are beyond the scope of this beginners python course. But for now all you need to know is we can iterate or loop through these generator objects. So instead of printing this generator object, let's just iterate over it using a for loop, so, for, file in, the generator object that is returned from the glob method. q Let's print file. We run our program, there you go. So these are all the py files in my current directory, this could be different on your machine if you didn't follow the exercises I gave you earlier. For example, this utils.py, we created this as part of one of the exercises earlier in this course. So don't worry if the files you see here are different on your machine. So, you can use the glob method to search for files using a pattern, we can also get all the files and directories in the current path, so, we just use one asterisk, then run our program, take a look, so we have this
03:50:48
ecommerce directory, we have notes.txt, this is a file I added earlier just to write notes as part of my presentation so you're not going to have this file. We also have a bunch of directories and files. Even though python's standard library is comprehensive and has so many modules for common tasks, it's not complete by any means. That's why we have this directory called python package index. Or pypi. And in this directory you can find hundreds of packages for doing awesome things. These are packages that people like you and I have built as part of our projects, and then they have published it as part of this directory. For other people to use. So that's why we have a fantastic community in python, there are so many python developers out there and there are so many packages right in front of us to reuse in our programs, let's say you want to send text messages in your programs, you don't have to build this functionality from scratch, we can simply come to pypi.org and search for sms aas you can see there are so many projects or apckages that give you this functionality. Of course not every
03:51:56
package, not every project is complete or bug free, some of them are still in development or they have bugs, but if you look around I'm pretty sure for any kind of function you can imagine there is a good reliable and well documented package for you. In my complete python course, I will show you some of those most useful packages on pypi. Por exemplo you will learn how to access the information on yelp.com in your programas. So you can write a program and search for businesses registered on Yelp. Let's say you want to search for the best barber Na cidade de Nova York. I will show you how to do that. You will also learn how to use a technique called web scraping, which means you can build an engine and have that engine browse a website, and extract information from HDML files. This is the same technique that Google does to index various websites. So they have several engines, or web crawlers, these web crawlers are continuously looking at various websites and extracting information from their pages. When you publish a blog post Google's web crawler finds the title of your post, its keywords and so on. Assim,
03:53:00
I'm going to show you how to do that with Python, we'll also look at browser automation, and this is extremely powerful, because you can automate testing of your web aplicações. So you might get a job as a test engineer, and your daily job is to browse a website, click here and there, fill out this form, that form, and ensure that this website is functioning properly. You can automate all that with a powerful python package called selenium, as I have shown in my complete, as I show in my complete python course. Now in this tutorial, I'm going to show you how to install packages, from pypi.org. Assim, here on pypi.org let's search for open py xl. This is a package that we use for working with excel spreadsheets. So let's search for this package, there you go, so currently it's at version 2.5. On the top you can see, this instruction pip install open pyexcel. this is the command that we need to type in the terminal window to install this package into our program, so back to pycharm, here on the status bar. You can open up a terminal window for executing
03:54:04
various commands. So let's open it, now if you're on Windows you're probably going to see something different instead of this dollar sign, don't worry about that just execute this command I'm going to show you. So pip install open py xl Make sure to spell everything properly. So pip is the tool, that comes with a python installation, and we use it to install or uninstall packages registered on pypi.org. So here, we're using pip to install this package. open py xl. Enter, let's go ahead with that, it's going to take a few seconds, oaky done, now we can import this package and it's modules just like the built in modules in python, or the modules that we have in our project. Now if you're curious where this package is stored on disc let me show you. So open up the project panel, and then expand external libraries, next expand python 3, and then expand sight packages. This is where all these packages that we installed with pip are stored.
03:55:08
So here we have open py xl, you can open this, in this folder we have another folder called cell, now Now, look what we have here you have this init type, earlier I told you that whenever we add this file to a folder, python treats that folder as a package, so sell is a package, and this package we have is modules. Sell, interface, read only and text. So as you can see, this package openpyxl has several subpackages like cell, start, chart sheet and so on. And in each package we have several modules, in the next tutorial I will show you how to work with excel files. So we have covered all the core concepts in Python, I hope you have learned a lot. please support my hard work by liking this video and sharing it with others. And be sure to subscribe to my channel for more tutorials like this. Next we're going to work on our first python project that involves automation. You're going to write a python program that can process thousands of spreadsheets in under a second. Você está animado? Vamos começar.
03:56:16
In this tutorial I'm going to show you something really awesome you can do with python. Você vai learn how to process spreadsheets, and this is extremely valuable in situation where you have hundreds or thousands of spreadsheets that need to be updated. If you want to do this by hand it may take hours or days weeks, or even months, you can simply build a python program in less then half an hour. And have that python program, automatically process thousands of spreadsheets in under one second. So, here we're going to work on this excel spreadsheet. You can download this below this video. In this spreadsheet we have three columns, transaction ID, product ID, and press. Now don't worry about the fourth column yet. So in this spreadsheet we're going to record all kinds of transactions, but let's say due to an error, it could be a human error or a system error. The price that we have here is wrong. Let's say we need to decrease this by 10 percent. If you want to do this manually, we'll have to come back here and add a formula, so we typed out equal sign, let's say you want to recalculate say you want to recalculate the value of this cell.
03:57:20
have to get that and then multiply it by 0.9 and that is like 90% of the original price, we are reducing the original reducing the price by 10%. Now when you hit enter you can see the updated price. Next we'll have to come back here, select this cell and apply the same formula to all the other rows. Now what if you have thousands of rows Aqui? You'll have to scroll up and down, this is going to be very tedious. So we're going to write a python program that will do this for us. Vai auotmate this process and not only that it will also add this beautiful chart right here, once again if you want to open up hundreds or thousands of spreadsheets and add a chart to each one, this is going to take at least a week or two Our python program is going to do all of this in a matter of seconds. Então vamos começar. Alright the first thing I want you to do is to download this transactions file and add it to your project. I put the link below this video for you to download. So if you're wondering how to put this in this project, you can simply right click the project,
03:58:24
and if you're on Mac you have this item where reveal in finder, if you're on Windows you should see something like reveal in explorer, or file explorer, or whatever it's called when you click this, this opens up the direct on your machine where this is stored. So simply copy paste the transactions file right here. Agora, here on the top, first we need to import the open py excel package. So import open py excel, we can give it a an alias to make our code shorter. So asxl. This is not required but it just makes our code a little bit cleaner. Deixe-me te mostrar. So now instead of typing open pyxl. we type xl. okay so that's an alias for this package. Now in this package we have a function for loading an xl workbook. So let's call load workbook, and as the argument we pass transactions. .xlsx. So this we load
03:59:28
our excel workbook and return a workbook object. OK? Now if you open this workbook, you can see you add only 1 sheet, and that is called sheet 1, so to access that you use square brackets, and specify the name of the sheet, that is sheet one, make sure to spell this with a capital S. Because this is case sensitive, if you don't spell it properly you're going to get an error, so this returns a sheet, now in this sheet, we have various cells. assim next you need to learn how to access a particular cell, and that is very easy. back to py charm, with this sheet object, you can use square brackets and give the coordinate of a cell. Coordinate is the combination of the column and the row. For example, this cell it's coordinate is a1. So back to pycharm, we can type a1, and this returns our first cell. Also, there is another approach to getting a cell, instead of using square brackets with a string, we can
04:00:32
use the cell method of the sheet object, so, sheet.cell, you pass the row and the column, so row and column 1 these return the exact same célula. Now let's print the value of this cell, cell.value and run our program so the value is transaction id, beautiful, so now we need to iterate over all these rows and for each row we need to get the value in the third column. That is the price. We'll get that and then multiply by 0.9. So first we need to know how many rows we have in this spreadsheet. We can get that from the sheet object so sheet has an attribute called mx_ linha. Let's print this, so in this sheet, we have 4 row, and you can verify that here. So we have a total of 4 rows. So we need to add a for loop. that would generate the numbers 1-4. Assim, let's delete this print statement, nd add a for loop
04:01:36
for row in were going to use the range function unction to generate a range of numbers, starting from 1, all the way to sheet .max_grow. Plus 1. The reason we're adding 1 to this, is because as I told you before this range function will generate numbers, starting from this value all the way to this value, but it will not include the second value. So currently max row returns 4, if you use range of 1-4 this will generate the numbers 1, 2, and 3, but not 4. So to include 4, we need to add 1 to it. Let's go over here, so we tied sheet.max underline row plus 1. Now before going any further let's just print row and make sure our program is working up to this point. So let's run this, we get the numbers 1-4 beautiful. So now we can easily get the cells in the third column. Contudo we don't really want this first cell, that's the heading. so technically you want to ignore the first row. Back here, you want to change
04:02:40
our range function, and start from 2. Now, we're going to use sheet.cell to get access to the cell at this row. And the column should be 3. We get a cell object, let's print it's value and make sure you're on the right track, so run the program these are the values we get. 5.95 6.95 and 7.95 these are the values of the third column. Next we need to multiply each value by 0.9 so instead of printing cell.value we multiplied by 0.9 and this is the corrected underline price, so this is the mistake we're going to make with our program, now we need to add a new cell to our worksheet, so we want to add all the corrected prices, ia new column, it could also overwrite the values in this column, but in this tutorial I'm going to show you how to add a new column. So using the same method, now we need to get a reference to the cell, to the given
04:03:44
row, but in the fourth column. So, we call sheet .cell, and pass row and four as the arguments. Once again, this returns a cell object, let's store that in a separate variable and call it price_cell. So note that my variable names are very descriptive. There is no guess work. You have corrected price which holds actual value and we have corrected price, which is a cell object in this spreadsheet. Next we have to set the value in this célula. So we set corrected price cell. value to this corrected price. With these few lines we can easily update our spreadsheet, but first we need to save it. Assim, after our for loop, we call workbook. Salve . Now let's save this in a new file because we don't want to accidentally overwrite the original file in case our program has a bug so, I'm going to call that transactions 2.sms ex. And finally let's run our program,
04:04:48
so, you can see that happened in a split of a second, now here we have a new file tranactions 2. When we open this we get something like this. So you can see we have this 4th column with the updated prices. Lindo. So half of the problem is solved, now we need to add a chart here. To add a chart, we need to add a couple classes on the top, so, after this import statement let's type out from open py excel.chart, import, bar chart, comma, reference. So lets see what's going on here. In this package you have a module chart, and from this module we're importing two classes, bar chart, and reference. Again, look at the naming convention used Aqui. The first letter of e very word is capitalized. Also it's better to add a line break after our import statements to make our code cleaner. So, before we save our workbook, we need to add achart to the current sheet. First we need to select a range of values. For this exercise, I'm going to select the values in the fourth column/.
04:05:52
So all the values in rows 2-4 these are the values I'm going to use in our chart. Now in this part 2 example it doesn't really make sense to add a chart per transaction, but that doesn't really matter we just want a bunch of numbers to create a chart, so after our for loop, we're going to use the reference class to select a range of valores. Now the first argument in the constructor is the Folha. So we pass our sheet here, then we add 4 keyword arguments, the first one is min_row, we set this to 2. The second one is max_row we set this to the maximum row in this sheet. That is sheet, .max_row, so we want to select the cells in row 2-4. kay? Now to make this code a little bit cleaner I'm going to put this on a new line, so we can see clearly, now this is going to select all the cells in all the columns in these rows. That's not what we want. we only want the values in the fourth column, so back here
04:06:56
we need to set a couple more key word arguments men_call or column, we set that to for, and also max underline call, we set that to 4 as well. So we are limiting the range of cells we're selecting to the fourth column. Now, we're creating an instance of the reference class, let's store the result in a variable called values, so this values object will have all these values in the fourth column, now we are ready to create a chart, so we create an instance of the bar chart class and store it in this object. Next, we call chart.add_date and pass our values. That is pretty straight forward finally we need to add this chart to our sheet. So, we call sheet, .add_chart and pass this chart object We should also specify where we want to add this chart. let's say we want to add it here, on row 2, after the fourth column. So the coordinate of this cell is e2, and this is going to be,
04:08:00
the top left corner of our chart. So as the coordinate I'm going to pass e2 that's all we had to do, done. Let's run our program one more time, beautiful, let's open up the update workbook. And here's the end result, so right after the fourth column, we have this beautiful chart. Now we could take this to the next level, we could add a legend here, we could change the color of these bars, we could even use a different kind of chart, it doesn't have to be a bar chart. So to learn more about this we can read the documentation for openpyxl. assim our program is complete, for our code is dirty, it's not clean, it's not organizado. We don't have any functions here. We have written all the code in app.py. So let's goo ahead and organize this code like a professional software developer. So, on line 4, we are loading our workbook then we're getting a reference to the first sheet, but we don't really need these two lines here this is purely for demonstration to show you how to access a cell. Assim, let's delete these unnecessary lines, this is a very important practice as you're coding always look at your code, always review it, see if you have some code that is
04:09:04
not used. Always delete those. Okay, next we are iterating over all the rows, fixing the prices, and then we select the values to add a chart, and finally we save the workbook. Now, if you were going to use this to automate the process of updating thousands of spreadsheets, this program wouldn't work, because it's only relying on this file. So we want o reorganize this code, and move it inside of a function. This function should take the name of a function So let's define a function. Vamos call it process_workbook. It gets a file name. Now, we move all the code inside of this function, so let's select everything, and press tab, beautiful, now back to our function, instead of loading this transactions file we're going to load this file name, that's better, Also, now that our program is working properly, there is really no need to store the result in a separate file. So here we can
04:10:08
simply overwrite the same file. So let's pass file name, that is the end of our function, so, now, we have this reusable function, we can simply reuse this to process thousands of spreadsheets. Earlier in this python course you learned how to find all the files in a directory, so we can get each file in a directory and pass the name of the file to this function, this function will go ahead and update this spreadsheet in just a second or less. So, that was just one example of using python to automate repetitive boring task that waste your time. But automation is not just about processing excel spreadsheets, there are so many things we can automate. Here's a question for you, what do you want to automate, how do you want to use python to make your life easier? Use the comment box below and let me know. I love to hear about your ideas. Next we're going to work on project which involves machine learning, which is a subset of artificial intelligence. Você está animado? Vamos começar. In this section, you're going to learn about machine learning, which is a subset of
04:11:12
AI or artificial intelligence. It's one of the trending topics in the world, these days, and it's going to have a lot of applications in the future. Aqui está um exemplo. Imagine I ask you to write a program to scan an image, and tell if it's a cat or a dog. If you want to build this program using traditional programming techniques, your program is going to get overly complex You will have to come up with lots of rules to come up with specific curves edges and colors in an image to tell if it's a cat or a dog. But if I give you a black and white photo, your rules may not work, they may break. Then you would have to rewrite them. Or I may give you a picture of a cat or a dog from a different angle that we did not predict before. So solving this problem using traditional programming techniques is going to get overly complex or sometimes impossible. Now to make the matter worse. What if I ask you to extend this program such that it supports 3 kinds of animals. Cats, dogs, and horses, once again you will have to rewrite all those rules. Isso não vai funcionar. So machine learning is a technique to solve these kinds of problems, and this is how it works. We build
04:12:16
a model or an engine and give it lots and lots of data. For example, we give it thousands or tens of thousands of pictures of gatos e cachorros. Our model will then find and learn patterns and the input data, so we can give it a new picture of a cat that we haven't seen before. And ask it, is it a cat or a dog or a horse and it will tell us with a certain level of accuracy, the more input data we give it, the more accurate our model is going to be. So that was a very basic example, but machine learning has other applications in self driving cars, robotics, language processing, vision processing, forecasting things like stock market trends and the weather, games and so on. So that's the basic idea about machine learning. Next we'll look at machine learning in action. A machine learning project involves a number of steps, the first step is to import our data which often comes in the form of a csv file. You might have a database with lots of data, we can simply export that data and store it in a csv file for the
04:13:20
purpose of our machine learning project. So we import our data, next, we need to clean it. And this involves tasks such as duplicated data. If you have duplicates in the data, we don't want to feed this to the model, because otherwise our model will learn bad patterns in our data and will produce the wrong result, so we should make sure that our input data is in a good, and clean shape. If there is data that is irrelevant we should remove them, if there are duplicates or incomplete we can remove or modify them, if our data is text based, like the name of countries, or genres of music, or cats and dogs, we need to convert them to numerical values. So this step really depends on the kinds of data we're working with, every project é diferente. Now that we have a clean data set, we need to split it into two segments. One for training our model, and the other for testing it, to make sure our model produces the right result. For example, if you have 1,000 pictures of cats and dogs, we can reserve 80% for training, and another 20% for testing. The next step is to create a model, and this involves selecting
04:14:24
an algorithm to analyze the data. There are so many machine learning algorithms out there, such as decision trees, neural networks and so on. Each algorithm have pros and cons in terms of accuracy and performance so the algorithm you use, depends on the kind of problem you're trying to solve and your input data. Now the good news isnthat we don't have to explicitly program an algorithm, there are libraries out there that provide these algorithms, one of the most popular ones, which we are going to look at in this tutorial, is side kick learn. So we build a model using an algorithm , next we need to train our model. So we feed it our training data. Our model will then look for the patterns in the data, so enxt we can ask it to make predictions. Back to our examples of cats and dogs, we can ask our model is this a cat or is this a dog and our model will make a prediction, now the prediction is not always accurate in fact when you start out, it's very likely your predictions are inaccurate. So we need to envalue the predictions and measure their accuracy. Then we need to get back to our model and either select a different algorithm
04:15:28
that is going to produce a more accurate result for the kind of problem we're trying to solve. Or fine tune the parameters of our model. So each algorithm has parameters that we can modify to optimize the precisão. So these are the high level steps that you follow in a machine learning projeto. Next we'll look at the libraries and tools for machine learning. In this lecture we're going too look at the popular python library that we use in machine learning projects. The first one is numpy which provides a multidimensional array. A very, very, popular library. The seconnd one is pandas, which is a data analysis library that provides a concept called data frame. Data frame is a two dimensional data structure similar to an excel spreadsheet. So we have rows and columns we can select columns in a row or a column or a range of rows and columns, again, very very popular in machine learning and data science projects. The third library is mad plot lib which is a two dimensional plotting library for creating graphs on plots. The next library is sidekick learn, which is one of the most popular machine learning
04:16:36
libraries that provides all these common algorithms like decision trees, neural networks and so on. Now, when working with machine learning projects, we use an environment called jupiter for writing our code, technically we can still use vs code or any other code editor, but these editors are not ideal for machine learning projects, because we need to frequently inspect the data, and that is really hard in environments like vs code and terminal. If you're working with a table of 10 or 20 columns visualizing this data in a terminal window is really, really difficult and messy, so thats why we use jupiter. So that's why we use jupiter, it makes it really easy to inspect our data. Now to install jupiter, we are going to use platform called anaconda. So, head over to Anaconda.com/download. On this page you can download Anaconda distribution for your operating system, so, we have distributions for Windows Mac and Linux. So let's go ahead and install Anaconda for python 3.7. Download, Tudo bem, então
04:17:40
here's Anaconda, download it on my machine, let's double click this. Alright, first it's going to run a program to determine if the software can be installed. So, let's continue and once again continue, pretty easy, continue one more time, I agree with the license agreement, we can use the default you ca use the default installation location so don't worry about that, just click install, give it a few second, now the beautiful thing about Anaconda is it will install jupiter, as well as all those data popular science libraries like numpy, Pandas and so on. So we don't have to manually install this using pip. Alright now as part of the next step Anaconda is suggesting to install Microsoft vs code. Nós already have this on our machine so we don't have to install it we can go with continue and close the installation, now finally we can move the this to trash because we don't need this installer in the future. Alright, now open upa terminal window and type jupiter, with ay, space, notebook.
04:18:44
This will start the notebook server on your machine. So enter ai está. This will start the notebook server on your machine, we can see these default messages here, don't worry about them, now it automatically opens a browser window, pointing to local host port 888. This is what we call jupiter dashboard. On this dashboard we have a few tabs, the first tab is the files tab, and by default, this points to your home directory. So every user on your machine has a home directory, this its my home directory on Mac, you can see here we have a desktop folder as well as documents, downloads and so on. On your machine you're going to see different folders, so somewhere so somewhere on your machine you need to create a jupiter notebook. I'm going to go to desktop here's my desktop I don't have anything here, and then click new, I want to create a notebook for python 3. In this notebook we can write python code, and execute it line by line. We can easily visualize our data as you can see over the next few videos. Assim, let's go ahead with this,
04:19:48
alright, here's our first notebook, you can see by default it's called untitled, let's change that to Hello World so this is going to be the hello world of our machine learning project. Vamos rename this now if you look at your desktop you can see this file hello world.ipynb. This is a jupiter notebook. It's kind of similar to our py files where we write our python code, but it includes additional data that jupiter uses to execute our código. So back to our notebook, let's do a print hello world. And then, click this run button here and here's the result printed in jupiter, so we don't have to navigate back and forth between the terminal window we can see all the result bem aqui. Next I'm going to show you how to load a data set from a csv file in jupiter. Alright, in this lecture we're going to download a data set from a very popular website called caggle.com. Caggle is basically a place to do data science projects.
04:20:56
So the first thing you need to do is to create an account, you can sign up with Facebook, Google, or using a custom email and password, once you sign up then come back here, on caggle.com, Here one the search bar search for video game sales. This is the name of a very popular data set that we're going to use in this lecture. Assim, here in this list you can see the first item with this kind of reddish icon, so, let's go with that, as you can see this data set includes the sales data for more then 16,000 videos jogos. On this page you can see the description of various columns in this data set, we have rank, name, platform, year, and so on, so here's our data source, it's a csv file called vg sales.csv, as you can see there are over 16,000 rows, and 11 columns in this data set. Right below that you can see the first few records of this data set. So, here's our first record, the ranking for this game is 1, it's the wi sport game for wii as the platform and it was released in the year 2006,
04:22:00
now, what I want you to do is go ahead and download the data set, and as I told you before you need to sign in before you can download this. So this will give you a zip file as you can see here, here's our csv file, now I want you to put this right next to your jupiter notebook, on my machine that is on my desktop so I'm going to drag and drop this onto the desktop folder. Now, if you look at the desktop you can see here's my jupiter, hello world notebook, and right next to that we have vgsales.csv. With that, we go back to our jupiter notebook, let's remove the first line and instead import pandas as pd. With his we're importing pandas module and renaming it to pd, so we don't have to type pandas. several times in this code. Now let's type pd. read_csv. And pass the name of our csv file. That is vgsales.
04:23:04
csv. Now because this csv file, is in the current folder right next to our jupiter notebook, we can easily load it, otherwise we have to supply the full path to this file. So, this returns a data frame object which is like an excel spreadsheet. Deixe-me te mostrar. So we store it here, and then we can simply type df to inspect it. So one more time let's run this program here's our data frame with these rows and these columns so we have frank name platform and so on. Now this data frame object has lots of attributes and methods that we're not going to cover in this tutorial, that's really beyond the scope of what we're going to do, so I'm going to leave it up to you to read pandas documentation or follow other tutorials to find out about pandas data frames. But in this lecture, I'm going to show you some of the most useful methods and attributes. The first one is shape, so shape let's run this one more time, so here's the shape of this data set, we have over 16,000 records and 11 columns. Technically this is a 2 dimensional array of 16,000
04:24:08
and 11, okay? Now, we can see here we have another segment for writing code. SO we don't have to write all the code in the first segment so here in the second segment we can call one of the methods of the dataframe, that is df.describe. Now when we run this program, we can see the output for each segment right next to it. So here's our first segment, here we have these three lines, and this is the output of the last line. Below that we have our second segment, here we're calling the describe method, and right below that we have the output of this segment So this is the beauty of jupiter, you can easily visualize our datsa, doing this with vscode in windows is really tedious and clunky. So what is the describe method returning? Basically it's returning some basic information about each column in this data set, So, as you saw earlier we have columns like rank, year and so em. These are the columns with numerical values. Now for each column we have the count which is the number of records in that column, you can se
04:25:12
our rank column has 16,5 -98 records whereas the year column has 16,3- -27 records.. So this shows that some of our records don't have the value for the year column. We have null values. So in a real data science or machine learning project we'll have to use some techniques to clean up our data set. One option is to remove the records that don't have a value for the year column. Or we can assign them a default value. That really depends on the project. Now another attribute for each column is mean so this is the average of all the values, now in the case of the rank column, this rank doesn't really matter, but look at the year. So the average year year for all these video games in our dataset is 2006. And this might be important in the problem we're trying to solve. We also have standard deviation, which is a measure to quanitfy the amount of variation in our set of values, below that we have min, as an example the minimum value for the year column is 1980. So quite often when we work with a new data set,
04:26:16
we call the describe method to get some basic statistics about our data. Let me show you another useful attribute. So, in the next segment, let's type df.values. Let's run this, as you can see this returns a two dimensional array, this square bracket indicates the outer array and a second one represents an inner array. So the first element inn our outer array, is an array itself, these are the values in this array, which basically represent the first row in our data set. So the video game we ranking 1, which is called wii sports. So this was a basic overview of pandas data frames, in the next lecture I'm going to show you some of the useful shortcuts of jupiter. In this lecture I'm going to show to you some of the most useful shortcuts in Jupiter, Now the first thing I want you to pay attention to is this green bar on the left. This indicates that this cell is currently in the edit mode, so we can write code here. Now, if we press the
04:27:24
escape key, green turns to blue, and that means this cell is currently in the command mode. So basically the activated cell can either be in the edit mode or command mode. Dependendo on the mode, we have different shortcuts, so here we're in the command mode. If we press h, we can see the list of all the keybord shortcuts, right above this list we can see, Mac OS modifier keys, these are the extra keys on a Mac keyboard. If you're a Windows user you're not gong to see these. So as an example, here is the shape of the command key, this is control, this is option, e assim por diante. With this guideline you can easily understand the shortcut associated with each command. Deixe-me te mostrar. So here we have all the commmands when a cell is in the command mode. For example, we have this command, open the command palette. This is exactly like the command palette that we have in vs code. Here is a short cut to execute this command. That is command shift and F.
04:28:28
Okay, so here we have lots of shortcuts, of course you're not going to use all of them all the time, but it's good to have a quick look here to see what is available for you. Tis these shortcuts you can write code much faster. So let me show you somme of the most useful ones. I'm going to close this, now with our first cell in the command mode I'm going to press b, and this inserts, a new cell below this cell. We can also go back to our first cell, press escape, now the cell is in the command modo. We can insert an empty cell above this cell by pressing a. So either a or b. A for above or b for below. Now if you don't want this cell, you can press d twice to delete it. Como isso. Now in the cell I'm going to print a hello world message. So print Olá Mundo. Now, to run the code in this cell, we can click on the run button here, so, here's our print function, and
04:29:32
right below that you can see the output of this function. But note that when you run a cell, this will only execute the code in that cell. In other words, the code in other cells will not be executed. Let me show you want I mean, so in the cell below the cell, I'm going to delete the call to a describe method. Instead I'm going to print oceano. Agora eu vou to put the cursor back in this cell where we print this hello world message and run this cell. So we can see hello world is displayed here, but the cell below is still displaying the describe table, so we don't see the changes here. Agora, to solve this problem, we can go to the cell menu on the top, and run all cells together. This can work for a small project, but sometimes you're working with a large data set, so if you want to run all these cells together it's going to take a lot of time. Isso é the reason jupiter saves the output of each cell, so we don't have to rerun that code if it hasn't changed. So this notebook file that we have here,
04:30:36
includes our source code organized in cells as well as the output for each cell. That is why it's different from a regular py file where we only have the source code. Here we also have autocompletion and intellisence, so in this cell, let's call df data frame . now if you press tab you can see all the attributes and methods in this object. So let's call describe, now with the cursor on the name of the method we can press shift and tab, to see this tool tip that describes what this method does and what parameter it takes. So here in front of so here in front of signature you can see the describe method, these are the paramter and their default value, and right below that you can see the description of what that method does. In this case, it describes generates descriptive statistics, that summarize the central tendency and so on. Similar to vs code, we can also convert a line to comment by pressing command and slash on mac, or
04:31:40
control slash on windows. Como isso. Now that line is a comment, we can press the same shortcut one more time to remove the comment, so these are some of the most useful shortcuts in jupiter. Now over the next few lectures we're going to work on a real machine learning project, but before we get there, let's delete all the cells here, so we start with only a single empty cell, so here, in this cell, first I'm going to press the escape button, now the cell is blue, so we're in the command mode, and we can delete the cell by pressing d twice. Ai está. Now, the next cell is activated and is in the command mode. So, let's delete this as well, so we have two more cells to delete there you go, and the last one, like this, so now we have an empty notebook with a single cell. Over the next few lectures, we're going to work on a real machine learning project, imagine we have an online music store, when our users sign up, we asked our age and gender, and based on their profile, you recommend various music albums their likely to buy. So in this project,
04:32:48
you want to use machine learning to increase sales. So, we want to build a model, we feed this model with some sample data, based on the existing users. Our model will learn the patterns in our data, so we can ask it to make predictions. When a new user signs up, we tell our model, hey, we have a new user with this profile, what is the kind of music, that this user is interested in, our model will say jazz, or hip hop, or whatever, and baed on that we can make suggestions to the user so, this is the problem we're going to solve, now back to the list of steps in the machine learning projects, first we need to import our data, then, we should prepare or clean it, next we select a machine learning algorithm to build a model, we treat our model and ask it to make predictions. And finally, we evaluate our algorithm to see it's precisão. if it's not accurate we either fine tune our model or select a different algorithm. So let's focus on the first step. Head over to bit.ly/music.csv this is a very basic csv that I've created for this project, it's just some random
04:33:52
made up data it's not real. So we have a table with 3 columns, age, gender, and genre. Gênero can either be one which represents a male, or a 0, which represents a female, here I'm making a few assumptions. I'm assuming that men between 20 and 25 like hip hop men between 26 and 30 like jazz, and after the age of 30, they like classical music. For women I'm assuming that if they are between 20 and 25 they like dance music, if they are between 26 and 30 they like acoustic music, and just like men, after the age of 30 they like classical music. Once again this is a made up pattern, it's not the representation of the reality, so, let's go ahead and download this csv. Click on this ... icon here and download this file. In my downloads folder, here we have this music.csv. I'm going to drag and drop this onto the desktop because that's where I've stored this hello world notebook. So I want you to put this csv file
04:34:56
right next to your jupiter notebook. Now, back to our notebook, you need to read the csv file, so just like before first we need to import the pandas module, so import panda as pd. And then we'll call pd, .read_csv and the name of our file is music.csv. As you saw earlier this returns a data frame which is a two dimensional array similar to an xl spreadsheet, so let's call that music_ dados. Now let's inspect this music_data to make sure we loaded everything properly so run, so here's our data frame, beautiful, next we need to prepare or clean the data. And that's the topic for the next lecture. next lecture. The second step in a machine learning project, is cleaning, or preparing the data, and that involves tasks such as removing duplicate null values and so on. Now on this particular data set we don't have to do anything
04:36:00
kind of cleaning, because we don't have any duplicates, and as you can see As you can see, all rows have values for all columns, so we don't have null values. But there is one thing we need to do, we should split this data set into two separate data sets, one into the first two columns, which we refer to as the input set, and the other with the last column which we refer to as the output set. So when we train a model, so when we train a model we give it two separate data sets. The input set and the output set. The output set which is in this case the genre column contains the predictions so we're telling our model that if we have a user who's 20 years old and a male they like hip hop. Once we train our model then we give it a new input set. For example, we have a new user who is 21 years old and is a male, what is the genre of the music that this user probably likes. As you can see in our input set, we don't have a sample for a 21 year old male, so we're going to ask our model to predict that. That is the reason we need to split this data
04:37:04
set into two separate sets. Input and output So back to our code, this data frame object has a method called drop. Agora if you put the cursor on the method name and press shift and tab, you can see this tool tip, so this is the signature of this drop method, these are the parameters you can pass here. the parameter we're going to use in this lecture is set to none by default. Witht his parter we can specify the columns we want to drop, so in this case we set columns to an array with one string, genre now this method doesn't actually modify the original data set. In fact it will create a new data set but without thisq ligar. So by convention we use a capital X to represent that data set, so capital x equals this expressão. Now, let's inspect x, so as you can see our input set or x
04:38:08
includes these two columns, age and gender, it doesn't have the output or predictions. Next we need to create our output set so, once again we start with our data frame using data, using square brackets we can get all the values in a given column. In this case, genre. Once again this returns a new data set. By convention we use a lower case y to represent that. So that is our output dados. Let's inspect that as well. Assim, in this data set we only have the predictions or the answers. So we have prepared our data, next we want to create a model using an algoritmo. The next step is to build a model using a machine learning algorithm. There are so many algorithms out there, each algorithm has its pros and cons, in terms of the performance and accuracy. In this lecture we're going to use a very simple algorithm called decision tree. Now the good news is we don't have to explicitly
04:39:12
program these algorithms, they're already implemented in a library called side kick aprender. So, here on the top, from sklearn.tree let's import the decision tree classifier. So sklearn is the package that comes with sidekick learn library, this is the most popular machine learning library in python. In this package, we have a module called tree. And in this module we have a class called decision tree classifier. This class implements the decision tree operator, okay? So, now we need to create a new instance of this class. So, at the end, let's create an object called models nd set it to anew instance of decision, tree classifier. Como isso. So now we have a model, next we need to train it so it learns patterns in the data, and that is pretty easy. You call model, .fit this method takes
04:40:16
2 data set. The input set and the output set. So they are capital x, y. Now finally, we need to ask our model to make a prediction, so we can ask it, what is the kind of music a 24 year old male likes? Now before we do that, let's temporarily inspect our initial data set. Isso é music data. So, look what we got here. As I told you earlier, I've assumed that men between 20 and 25 like hip hop music but here we only have 3 samples for men age 20, 23,and 25. We don't have a sample for a 21 year old male. So if you ask our model to predict the kind of music that a 21 year old male likes, we expect it to say hip hop. Similarmente, I've assumed that women between 20 and 25 like dance music, but we don' have a sample for a 22 year old female. So once again if you ask our model to predict the kind of music that a 22 year old woman likes, we expect it to say dance.
04:41:20
So, with these assumptions let's go ahead and ask our model to make predictions. So let's remove the last line, and instead we're going to call model .predict. This method takes a 2 dimensional array. So here's the outer array. In this array, each element is an array. So I'm going to pass another array here, and in this array I'm going to pass a new input set. a 21 year old male. So 21, 1 that is like a new record in this table. OK? Assim, this is one input set, let's pass another input for a 22 year old female. So here's another array, here, we add 22 comma 0, so we're asking our model to make 2 predictions ao mesmo tempo. We get the result and store it in a variable called predictions, and finally let's inspect that in our notebook. Run, look what we got, our
04:42:24
model is saying that a 21 year old male likes hip hop, and a 22 year old female likes dance music. So our model successfully will make predictions here. But wait a minute, building a model that makes predictions accurately is not always that easy. After we build a model we need to measure it's accuracy. And if it's not accurate enough, we should either fine tune it or build a model using a different algoritmo. So next lecture I'm going to show you how to measure the accuracy of uma modelo. In this lecture I'm going to show you how to measure the accuracy of your models. Now in order to do so, first we need to split our data set into two sets. One for training and the other for testing, because right now, we are passing the entire data set, for training the model and we're using 2 samples for making predictions. That is not enough to calculate the accuracy of a model. A general rule of thumb is to annotate 70-80% of our data to training, and another20-30%
04:43:28
for testing, then instead of passing only two samples for making predictions, we can pass the data set for testing we'll get the predictions and then compare the predictions with the actual values. In the test set. Based on that, we can calculate the precisão. That's really easy, all we have to do is import a couple functions and call them in this code. Deixe-me te mostrar. So first on this top from sklearn.model underline selection module we import a function called train test split. With this function we can easily split our data set into two sets. So training and testing, now, right here, after we define x and y, sets, we call this funciton, so train test split. We give it 3 arguments, x, y, ad a keyword argument that specifies the size of our test dataset. So test _size we set it to 0.2 So we're allocating 20%
04:44:32
of our data for testing. Now this functions returns a tuple, so we can unpack it into 4 variables bem aqui. x_train x_test y_train and y _test. so the first two variables are the input sets for training and testing. And the other are the output sets for training and testing, now, when training our model, instead of passing the entire data set we want to pass only the training data set. So, x_train, and y_train. Also, when making predictions instead of passing these two samples, we pass x_test. So thats the datas set. That contains input values for testing. Now we get the predictions. To calculate the accuracy we simply have to compare these predictions with the actual values we have in the output set
04:45:36
for testing. Isso é muito fácil. First on the top, we need to import a funciton, so, from sklearn.metric .metrics import accuracy _score. Now at the end. We call this function, so accuracy score and give it two arguments y_test. Which contains the expected values and predictions which contains the actual value. Now this functions returns an accuracy score between 0 to 1. So we can store it here, and simply display it on the console. Então vamos em frente and run this program. So, the accuracy score is 1 or a 100% but if we run this one more time, we're going to see a different result because every time we split our data set into training a test sets. We'll have different data sets, because this function randomly picks data for training and testing. Let me show you, so put the cursor
04:46:40
in the cell, now we can see this is activated note that if you click this button here, it will run the cell and also insert a new cell below this cell. Deixe-me te mostrar. So if I go to this second cell press the skip button, now we are in the command mode, press d twice, okay now it's deleted, if we click the run button, we can see, this code was executed, and now we have a new cell, so if you want to run our cell multiple times every time you have to click this and then run it, and then click again, and run it, it's a little bit tedious. So I'll show you a shortcut. Activate the first cell, and press control and enter this runs the current cell without adding a new cell below it. So, back here, lets run it multiple times okay, now look the accuracy dropped to 0.75, it's still good, so the cuuracey scored here, is somewhere between 75% to a hundred %. But let me show you something, if I change the test size, from 0.2 to 0.
04:47:44
8, so essentially we're using only 20 percent of our data, for training this model. And you're using the other 80% for testing. Now let's see what happens when we run this cell multiple vezes. SO, control and enter, look, the accuracy immediately dropped to 0.4 One more time, now 46% 40%, 26% it's really, really bad. A razão pela qual isso está acontecendo é porque you are using very little data for training this model. This is one of the key concepts in machine learning, the more data we give to our model and the cleaner the data is, we get the better result, so if you have duplicates, irrelevant data, or incomplete values, our model will learn back patterns in our data. That's why it's really important to clean before training our model. Now let's change this back to 0. 2, run this one more time, okay, now the accuracy is 1, 75%, now we drop to 50% again, the reason this is happening, is because we don't have enough data.
04:48:48
Some machine learning problems, require, thousands or even millions of samples, to train model, the more complex a problem is, the more data we need. For example, here we're only dealing with a table of three columns, but if you want to build a model to tell if a picture of a cat or a dog or a horse, or a lion, we will need millions of pictures, the more animal it will support the more pictures we need. In the next lecture, we're going to talk about model persistence. Então esta é uma very basic implementation of building a training a model to make a prediction. Now to simplify things I have removed all the code that you wrote in the last lecture for calculating the accuracy, because in this lecture, you're going to focus on a different topic, So basically we import our data set. Create a model, train it, and then ask it to make predictions, now this piece of code that you see here, is not what we want to run everytime we have a new user or every time we want to make recommendations to an existing user
04:49:52
sometimes it's really time consuming. In this example, we're dealing with a very small data set that only has 20 records. But in a real application, you might have a data set with thousands or trillions of examples, training for that might take seconds or minutes or even hours. And that is wy model persistence is important, once in a while, you build and train our model and then we save it to a file. Now, next time we want to make predictions, we simply load the model from the file and ask it to make predictions. That model is already trained you don't need to retrain it, it's like an intelligent person. Então deixe-me mostrar-lhe how to do this. it's very very easy. On the top, from sklearn.externals module we import joblib. este job lib object has methods for saving and loading modules. Assim, after we train our model we'll simply call job lib .dump and give it two arguments. Our model and the name of the file
04:50:56
in which we want to store this model. Let's call this music -recommender.job lib That's all we have to do. Now temporarily I'm going to comment out this line, we don't want to make any predictions, we just want to store train model in a file. So let's run this cell with control, and slash, okay, look, in the output we have an array that contains the name of our model file. So this is the return value of the dump method. Now back to our desktop, right next to my notebook we can see our job lib file, this is where our model is stored. It's simply a binary file. Now back to our jupiter notebook. As I told you before in a real application we don't want to train model every time. So let's comment out these few lines, on Mac, we can press command and slash and on windows control slash. Okay, these lines are commented out, now this time, instead of dumping our model, we're going to load it, so we call the load method, we don't have the model, we simply
04:52:00
pass the name of our model file. este returns our trained model. Now with this two lines we can simply make predictions, so, earlier, we assumed that men between 20-25 like hip hop music. let's print predictions and see if our model is behaving so control so this is how we persist and load models. Earlier in this section, I told you that decision trees are the easiest para entender. And that's why we started machine learning with decision trees. In this lecture, we're going to export our model in visual format, so you will see how this model makes predictions, that is really, really cool. Deixe-me te mostrar. So once again I've simplified this code so we simply import our data set, create input and output sets, create a model, and train it, that's all we are doing, now I want you to follow along with me, type everything exactly as I show you in this lecture. Não faça
04:53:08
worry about what everything means we'll come back to it shortly. So on the top, from sklearnimport tree, this object has a method for exporting our decision tree in a graphical format. So after we train our model, let's call tree _graph vis. Now here are a few arguments we need to pass. The first argument is our model, the second is the name oft he output file. So here we're going to use keyword arguments, because this method takes so many parameters, and we want to selectively pass keyword arguments without worrying about their order. Assim, the parameter we're going to set it out_file let's set this to music-recommend .dot. This is the dot format, which is the graph format, which is a graph description language, you will see that shortly. Now the other parameter you want to set is feature _names. We set this to an array of two strings,
04:54:12
age and gender. These are the features or the columns of our data set. So they are properties or features of our data. OK? The other parameter is class names. So class_names we should set this to the list of classes or labels we have in our output data set, like hip hop, jazz, classical and so on. So, this y data set includes all the genre or all the classes of our data, but they are repeated a few times in this data set. So, here we call y.unit this returns the unique list of classes, now we should sort this alphabetically. So, we call the sorted function, and pass the result a y.unique. The next parameter is labeled, we set this to a string, all, once again don't worry, about the details of these parameters, we're going to come back to these shortly. Assim, set label to all, then round it,
04:55:16
to true, and finally field to true. Assim, so this is the end result, now let's run this sound using control and enter, okay, here we have a nw file music recommender .. that's a little bit funny. So we want to open this file with vs code. So drag and drop this into a vs code window. Okay, here's a dot format, it's a textural language for describing graphs Now to visualize this graph we need to install an extension in vs code. So on the left side, click extensions panel and search for dot, dot. Look at this second extension here. graphvis or .language by stephon vs. Go ahead and install this extension and then reload vs code. Once you do that, you can visualize this dot file. So let me close this tab. Alright, look at this ... on the right side. Click this,
04:56:20
you should have a new menu, open preview to the side. So like that alright, here's the visualization of our decision tree, let's close the dot file, there you go. This is exactly how our model makes predictions. So we have this binary tree, which means every node can have a maximum of two children. On top of each note we have a condition if this condition is true we go to the child node on the left side. Otherwise we go to the child node on the right side. So let's see what's happening here, the first condition is age less then or equal to 30 .5. If this condition is false, that means that user is 30 years or older, so the genre of the music that their interested in is classical. So here we're classifying people based on their profile. That is the reason we have the word class here, so a user who is 30 years or older, belongs to the class of classical. Or people who like classical music. Now what if this condition é verdade. That means that user is younger then
04:57:24
30, so, now we check the gender, if it's less then 0.5, which basically means it equals to 0, then we're dealing with a female. So we go to the child node here, now once again we have another condition, so we are dealing with a female who is younger than 30. Once again we ned to check their age so is the age less then 25.5? Se for esse o caso then that user likes dance music, otherwise they like acoustic music. So this is a decision tree that our model uses to make predictions Now if you're wondering why we have these floating point numbers like 25.5 These are basically the rules that our model generates, based on the patterns in our dataset. As we give our model more data, these rules will change so they are not always the same. So they are not always the same, also the more columns or the more features we have, our decision tree is going to get more complex. We only have two features, age, and gender. Now back to our code let me quickly explain the meaning of all these parameters, we set field to true
04:58:28
so each box or each node is filled with a color. We set rounded to true, so they have rounded corners. We set label to all so every node has labels that we can read. We set class names to the unique list of genres and that's for displaying the class for each note, right here, and we set feature names to age and gender, sow e can see the rules in our notes. So that was a short and sweet introduction to machien learning. Now you can use the materials that you learn in this section and apply them to solve a different set of problems. Now here's a question for you: What ideas do you have for machine learning? What kind of problems do you want to solve with machine learning? Use the comments box below and let me know. I love to hear about your ideas! Next we're going to use python and a popular framework called django. To build a web application. Are you ready, let's get started In this turorial, I'm going to show you how to create your first website with python, and A and a very popular framework called django. So it's spelled with a silent D, and is pronounced django. it's a web framework for
04:59:36
perfectionists with deadlines. So if you're a perfectionist and you want to quickly put together a website that is fast, scaleable and secure, django is your best friend. And here are the popular websites built with Django. Like Instagram, Spotify YouTube, Washington Post, and so on. Now you might say what is a framework, and why do we need a framework to build a web application or a web site? Well, the framework is essentially a library of reusable modules these modules provide functionality for common tasks for example, in the case of a web framework like django we have modules to work with http requests url's, sessions, cookies and so on. These are the concerns of pretty much every website or application out there. So all this functionality is baked into django, we don't have to code it from scratch, that is why we use a framework like django. Agora, django. Now technically a framework is more then a library, apart from providing these modules it also provides a structure for each application It tells us what folders or files we should have in our project. Então, é isso
05:00:40
provides a consistency among various django projects. So as you move from one company to another and work on different projects, you can easily transition from one project to another, because all these applications follow the same structure now, with that interaction, let's create our first django project. So back to pycharm, close the hello world project, and create a new project, create a new project, let's call this new project pyshop go ahead, alright, now down at the bottom let's open up a terminal window, in this window we're going to install django. So we use pip to install django. But be sure to add two equal signs here followed by 2.1 With this we are telling pip that we want to install django version 2.1. The reason I'm doing this, is because in the future when you're watching this video, chances are there is a newer version django out there. Eu want to make sure that you can easily follow these tutorials, even though what I'm going to show you in these tutorials will most likely work with the latest version of django. Eu só quero
05:01:44
be on the safe side. Então vamos em frente alright, django is installed, next we need to create a django project, so here press control and L this cleans up our terminal window, you don't have to do it, but it's just easier to see. To create a django project, we need to execute this command, django, -admin space start project space, you're going to call this project pyshop space period. So when we install django, django brings a command line utility called django admin so this is a utility or program that we can execute form the command line or terminal, right here. Now, this program takes various arguments, in this case we want to use this argument start project, with this we're going to create a project called pushup in the current folder. So this period is imported here, that means the current folder, if you don't add this period, this utility is going to create an extra folder and that
05:02:48
looks a little bit repetitive, so let's go ahead with this, alright, now, back to the project panel, if you expand py shop we can see that this is our project that we created in pycharm and in this folder we have these files. So, init.py, you have seen this before, that means this folder is package, so we can import various modules, of this package into other modules, and in this module, we define various settings for our application, you're going to see this later in este curso. You also have this url's module, and with this module we define what should the user see when they see slash about/contact/products/shopping cart again, we're going to work with this only. And finally we have this module, that wsgi, that is short for web server gateway interface. The purpose of this module is to provide a standard interface between applications built with django and web servers. Isto é an advanced topic, so for now, don't worry about it. Now, outside of this folder,
05:03:52
of this folder you also have this new folder in our project manage.py. As the name implies, we use this to manage this django project. With this we can start our web server, we can work with our data base, again, we're going to work with this soon, let's open up the terminal window one more time, now, type out this command, python if you're on windows or python 3 if you're on Mac, because as I told you at the beginning of the course, Mac by default comes with an installation of python, that is python 2. But that is this course is python 3. So python 3 space manage .py space run servidor. O que está acontecendo aqui? So with python interpreter we are running this program manage.py and passing run server as an argument. This manage.py is essentially the same program that we worked with here, django admin. But we use django admin before creating a django project, now we have a django project, so now in this project we work with manage.py this
05:04:56
is a module that contains some python code, so we use this module to manage our django project. Então vamos em frente e

DOWNLOAD SUBTITLES: