English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Loops are used in programming to repeat specific code blocks. In this article, you will learn how to create a while loop in Python.
As long as the test expression (condition) is true, the while loop in Python can iterate over the code block.
This loop is usually used when we do not know the number of iterations in advance.
while test_expression: Body of while
In a while loop, the test expression is checked first. The body of the loop is entered only when the result of test_expression is True. After one iteration, the test expression is checked again. This process continues until the test_expression evaluates to False.
In Python, the body of a while loop is determined by indentation.
The body starts with indentation, and the first non-indented line marks the end.
Python interprets any non-zero value as True. None and 0 are interpreted as 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 within 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 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 point.
'''for 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.