About

Swaroop C H is 26 years of age. He graduated in B.E. (Computer Science) from PESIT, Bangalore, India. He has previously worked at Yahoo! and Adobe.

More about

Page
Personal tools
Collection

Python pt-br:Controle de Fluxo

From Notes

Jump to: navigation, search

Contents

[edit] Introdução

Nos programas que vimos até agora, houveram uma série de declarações e o Python executa-os na mesma ordem. E se você quisesse alterar o fluxo de seu funcionamento? Por exemplo, você quer que o programa tome algumas decisões e faça diferentes coisas dependendo das diferentes situações, como imprimir 'Bom Dia' ou 'Boa Tarde' dependendo da hora do dia?

Como você deve ter pensando, isto é alcançado usando as instruções de controle de fluxo no Python - if, for e while.

[edit] A instrução IF

A instrução if é usada para verificar uma condição e se a condição é verdadeira, será executado um bloco de instruções (chamado de bloco-if(if-block)), senão será processado outro bloco de instruções (chamado de bloco-else(else-block)). A cláusula elseé opcional.

Exemplo:

#!/usr/bin/python
# Nome do aquivo: if.py
 
number = 23
guess = int(input('Entre com um número inteiro : '))
 
if guess == number:
    print('Parabéns, você advinhou.') # Novo bloco começa aqui
    print('(mas você não ganhou nenhum prêmio!)') # Novo bloco termina aqui
elif guess < number:
    print('Não, era um pouco maior que isso') # Outro bloco
    # Você pode fazer o que quiser em um bloco ...
else:
    print('Não, era um pouco menor que isso')
    # Você deve adivinhar > número a alcançar aqui
 
print('Feito')
# Esta última instrução é sempre executada, depois da instrução if ser executada

Saída:

   $ python if.py
   Entre com um número inteiro : 50
   Não, era um pouco menor que isso
   Feito
   
   $ python if.py
   Entre com um número inteiro : 22
   Não, era um pouco maior que isso
   Feito
   
   $ python if.py
   Entre com um número inteiro : 23
   Parabéns, você advinhou.
   (mas você não ganhou nenhum prêmio!)
   Feito

Como Funciona:

Neste programa, recebemos tentativas de advinhações do usuário e verificamos se este é igual ao número que temos. Setamos a variável number para qualquer inteiro que desejarmos, digamos 23. Então, pegamos a tentativa de advinhação do usuário usando a função input(). Funções são peças de programas reutilizáveis. Iremos ler mais sobre elas no próximo capítulo.

Nós fornecemos uma string para função enbutida input que a imprime na tela e aguarda uma entrada do usuário. Uma vez que entramos com algum valor e apertamos a tecla enter, a função input() retorna o valor que entramos, como uma string. Nós, então, convetemos essa string para um inteiro usando int e depois armazenamos na variável guess. Na verdade, o int é uma classe, mas tudo o que voê precisa saber agora é que você pode usá-la para converter uma string em um número inteiro (assumindo que a string contém um número inteiro válido no texto).

A seguir, comparamos a tentativa de adivinhação do usuário com o número que escolhemos. Se eles forem iguais, imprimimos uma mensagem de sucesso. Note que utilizamos níveis de indentaçãopara dizer ao Python que instruções pertencem a qual bloco. É pos isso que a indentação é tão importante no Python. Eu espero que você esteja mantendo a regra da "indentação consistente". Você está?

Perceba que a instrução if contém 'dois pontos' no final - nós estamos indicando ao Python que a seguir há um bloco de instruções.

Então, checamos se a tentativa de advinhação do usuário é menor que o número da variável number, e se for verdadeiro, informamos ao usuário para tentar com um número um pouco maior que o inserido. O que usamos aqui é a clausula elif que, na verdade, combina duas instruções if else-if else relacionadas em uma instrução if-elif-else combinada. Isso torna o programa mais fácil e reduz quantidade de indentações requeridas.

As instruções elif else devem, também, possuir 'dois pontos' no final da linha lógica, seguido pelo seu bloco de instruções correspondente (com indentação apropriada, é claro).

Você pode ter outra instrução if dentro de um bloco-if de uma instrução if if a assim por diante - isto é chamado de instrução if aninhada

Lembre que as partes elif e else são opcionais. Uma instrução if mínima válida é:

if True:
    print('Sim, é verdadeiro')

Depois que python terminou de executar a instrução if completamente, junto com as cláusulas elif e else associadas, ele passa para a próxima instrução no bloco contendo a instrução if. Neste caso, é o bloco principal onde a execução do programa inicia e a próxima instrução é print('Feito'). Depois disso, Python vê o final do programa e simplesmente termina.

Ainda que este seja um programa muito simples, eu estive apontando várias coisas que você deve notar em programas assim. Todas elas são bem avançadas (e surpreendentemente simples para todos vocês com conhecimento em C/C++) e requerem que você esteja inicialmente ciente de todas elas, mas depois disso, você irá se familiarizar e isso irá se tornar 'natural' para você.

Nota para os programadores de C/C++
Não há a instrução switch no Python. Você pode usar uma instrução if..elif..else para fazer a mesma coisa (e em alguns casos, usar um dicionário para fazê-lo rapidamente)

[edit] A instrução while

A instrução while permite que você execute repetidamente um bloco de instruções enquanto uma condição for verdadeira. Uma instrução while é um exemplo do que é chamado de instrução de looping. Uma instrução while pode ter uma cláusula else opcional.

Exemplo:

#!/usr/bin/python
# Nome do arquivo: while.py
 
number = 23
running = True
 
while running:
    guess = int(input('Entre com um número inteiro : '))
 
    if guess == number:
        print('Parabéns, você advinhou.')
        running = False # Isto faz o loop while parar
    elif guess < number:
        print('Não, é um pouco maior que este.')
    else:
        print('Não, é um pouco menor que este.')
else:
    print('O loop while terminou.')
    # Faça qualquer outra coisa que quiser aqui
 
print('Fim')

Saída:

   $ python while.py
   Entre com um número inteiro : 50
   Não, é um pouco menor que este.
   Entre com um número inteiro : 22
   Não, é um pouco maior que este.
   Enter an integer : 23
   Parabéns, você advinhou.
   O loop while terminou.
   Fim

Como funciona:

Neste programa, nós ainda estamos jogando o jogo da advinhação, mas a vantagem é que o usuário pode continuar tentando advinhar até que ele acerte o número - não ha necessidade de rodar novamente o programa para cada tentativa de adivinhação, como fizemos na seção anterior. Isto demonstra o uso da instrução while.

Nós movemos oinput e a instrução if para dentro do loop while e setamos a variável running para True antes do loop while. Primeiro, nós checamos se a variável running é True(verdadeiro) e então seguimos para executar executar o <emphasis>bloco while</emphasis> correspondente. Depois que o bloco é executado, a condição é novamente checada que neste caso é a variável running. Se isso é verdade, nós executamos o bloco while novamente, senão continuamos para executar o bloco else optional e então seguir para a próxima instrução.

O bloco else é executado quando a condição do loop while se torna False(falso) - esta pode até ser a primeira vez que a condição é verificada. Se há alguma cláusula else para um loop while, ele é sempre executado a menos que você tenha um loop while que se executado para sempre sem sair sequer uma vez!

Os valores True(verdadeiro) e False(falso) são chamados tipos Booleanos e você pode considerá-los equivalentes aos valores 1 e 0 respectivamente.

O bloco else é, na verdade, redundante a partir que você pode colocar estas instruções no mesmo bloco (como a instrução while) depois da instrução while para conseguir o mesmo efeito.

Nota para programadores de C/C++
Lembre que você pode ter uma cláusula else else para o loop while.

[edit] The for loop

The for..in statement is another looping statement which iterates over a sequence of objects i.e. go through each item in a sequence. We will see more about sequences in detail in later chapters. What you need to know right now is that a sequence is just an ordered collection of items.

Example:

#!/usr/bin/python
# Filename: for.py
 
for i in range(1, 5):
    print(i)
else:
    print('The for loop is over')

Output:

   $ python for.py
   1
   2
   3
   4
   The for loop is over

How It Works:

In this program, we are printing a sequence of numbers. We generate this sequence of numbers using the built-in range function.

What we do here is supply it two numbers and range returns a sequence of numbers starting from the first number and up to the second number. For example, range(1,5) gives the sequence [1, 2, 3, 4]. By default, range takes a step count of 1. If we supply a third number to range, then that becomes the step count. For example, range(1,5,2) gives [1,3]. Remember that the range extends up to the second number i.e. it does not include the second number.

The for loop then iterates over this range - for i in range(1,5) is equivalent to for i in [1, 2, 3, 4] which is like assigning each number (or object) in the sequence to i, one at a time, and then executing the block of statements for each value of i. In this case, we just print the value in the block of statements.

Remember that the else part is optional. When included, it is always executed once after the for loop is over unless a break statement is encountered.

Remember that the for..in loop works for any sequence. Here, we have a list of numbers generated by the built-in range function, but in general we can use any kind of sequence of any kind of objects! We will explore this idea in detail in later chapters.

Note for C/C++/Java/C# Programmers
The Python for loop is radically different from the C/C++ for loop. C# programmers will note that the for loop in Python is similar to the foreach loop in C#. Java programmers will note that the same is similar to for (int i : IntArray) in Java 1.5 .
In C/C++, if you want to write for (int i = 0; i < 5; i++), then in Python you write just for i in range(0,5). As you can see, the for loop is simpler, more expressive and less error prone in Python.

[edit] The break Statement

The break statement is used to break out of a loop statement i.e. stop the execution of a looping statement, even if the loop condition has not become False or the sequence of items has been completely iterated over.

An important note is that if you break out of a for or while loop, any corresponding loop else block is not executed.

Example:

#!/usr/bin/python
# Filename: break.py
 
while True:
    s = input('Enter something : ')
    if s == 'quit':
        break
    print('Length of the string is', len(s))
print('Done')

Output:

   $ python break.py
   Enter something : Programming is fun
   Length of the string is 18
   Enter something : When the work is done
   Length of the string is 21
   Enter something : if you wanna make your work also fun:
   Length of the string is 37
   Enter something :       use Python!
   Length of the string is 12
   Enter something : quit
   Done

How It Works:

In this program, we repeatedly take the user's input and print the length of each input each time. We are providing a special condition to stop the program by checking if the user input is 'quit'. We stop the program by <emphasis>break</emphasis>ing out of the loop and reach the end of the program.

The length of the input string can be found out using the built-in len function.

Remember that the break statement can be used with the for loop as well.

[edit] Swaroop's Poetic Python

The input I have used here is a mini poem I have written called Swaroop's Poetic Python:

   Programming is fun
   When the work is done
   if you wanna make your work also fun:
       use Python!

[edit] The continue Statement

The continue statement is used to tell Python to skip the rest of the statements in the current loop block and to continue to the next iteration of the loop.

Example:

#!/usr/bin/python
# Filename: continue.py
 
while True:
    s = input('Enter something : ')
    if s == 'quit':
        break
    if len(s) < 3:
        print('Too small')
        continue
    print('Input is of sufficient length')
    # Do other kinds of processing here...

Output:

   $ python test.py
   Enter something : a
   Too small
   Enter something : 12
   Too small
   Enter something : abc
   Input is of sufficient length
   Enter something : quit

How It Works:

In this program, we accept input from the user, but we process them only if they are at least 3 characters long. So, we use the built-in len function to get the length and if the length is less than 3, we skip the rest of the statements in the block by using the continue statement. Otherwise, the rest of the statements in the loop are executed and we can do any kind of processing we want to do here.

Note that the continue statement works with the for loop as well.

[edit] Summary

We have seen how to use the three control flow statements - if, while and for along with their associated break and continue statements. These are some of the most often used parts of Python and hence, becoming comfortable with them is essential.

Next, we will see how to create and use functions.



<math><math>Insert formula here</math></math>

Please add your comments by clicking on the 'Discussion' link in the left sidebar.