English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Os loops são usados na programação para repetir um bloco de código específico. Neste artigo, você aprenderá como criar um loop while no Python.
Enquanto a expressão de teste (condição) for verdadeira, o loop while no Python pode iterar o bloco de código.
Quando não conhecemos o número de iterações antecipadamente, geralmente usamos este loop.
while test_expression: Corpo do while
No loop while, primeiro é verificado a expressão de teste. Apenas quando o resultado da expressão test_expression for True, o corpo do loop é executado. Após uma iteração, novamente é verificado a expressão de teste. Este processo continua até que a expressão test_expression avalie como False.
No Python, o corpo do loop while é determinado pelo recuo.
O corpo começa com recuo, e a primeira linha não recuada marca o fim.
Python interpreta qualquer valor não nulo como True. None e 0 são interpretados como False.
# Add program of natural numbers # Most numbers # sum = 1+2+3+...+n # Get input from the user # n = int(input("Enter n: ")) n = 10 # Initialize sum and counter sum = 0 i = 1 while i <= n: sum = sum + i i = i+1 # Update counter # Print sum print("sum value", sum)
When running this program, the output is:
Enter n: 10 sum value 55
In the above program, as long as our counter variableiless than or equal ton)(In our program for10),then the test expression is True.
We need to increase the value of the counter variable in the loop body. This is very important (Never forget()). Otherwise, it will cause an infinite loop (an endless loop).
Finally, display the result.
Withfor loopThe same, while the while loop can also have an optional else block.
If the condition in the while loop evaluates to False, then execute this part.
The while loop can be usedbreak statementTermination. In this case, the else statement will be ignored. Therefore, if there is no break interrupt and the condition is False, the else statement of the while loop will run.
This is an example to illustrate this.
'''Example Using else statement With while loop''' counter = 0 while counter < 3: print("Internal loop") counter = counter + 1 else: print("else statement")
Output result
Internal loop Internal loop Internal loop else statement
Here, we use a counter variable to print the string Internal loop Three times.
In the fourth iteration, the condition in the while loop becomes False. Therefore, this else part will be executed.