English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Les boucles sont utilisées en programmation pour répéter un bloc de code spécifique. Dans cet article, vous apprendrez à créer une boucle while en Python.
Tant que l'expression de test (condition) est vraie, la boucle while en Python peut itérer le bloc de code.
Lorsque nous ne connaissons pas à l'avance le nombre d'itérations, nous utilisons généralement ce type de boucle.
while test_expression: Corps de la boucle while
Dans une boucle while, le test expression est vérifié d'abord. Le corps de la boucle n'est entré que si le résultat de test_expression est True. Après une itération, le test expression est vérifié à nouveau. Ce processus continue jusqu'à ce que l'évaluation de test_expression soit False.
En Python, le corps de la boucle while est déterminé par l'indentation.
Le corps commence par un indentation et se termine par une ligne non indentée.
Python considère toute valeur non nulle comme True. None et 0 sont interprétés comme False.
# Program to add natural numbers # Maximum number of digits # 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("The value of sum", sum)
When running this program, the output is:
Enter n: 10 the value of sum 55
In the above program, as long as our counter variableiless than or equal ton(In our program it is10), 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, and the while loop can also have an optional else block.
If the condition in the while loop evaluates to False, then execute this part of else.
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.