Python3 Loop Statements
This section will introduce the use of loop statements in Python.
Python has two types of loop statements: for and while.
The control structure diagram for Python loop statements is shown below:
while Loop
The general form of a while statement in Python:
while condition:
statements...
Execution flowchart:
Execution GIF demonstration:
It is important to note the colon and indentation. Additionally, there is no do..while loop in Python.
The following example uses a while loop to calculate the sum of numbers from 1 to 100:
Example
#!/usr/bin/env python3
n = 100
sum = 0
counter = 1
while counter <= n:
sum = sum + counter
counter += 1
print("The sum from 1 to %d is: %d" % (n, sum))
Execution result:
The sum from 1 to 100 is: 5050
Infinite Loop
We can create an infinite loop by setting the condition expression to always be true, as shown in the following example:
Example
#!/usr/bin/python3
var = 1
while var == 1: # Expression is always true
num = int(input("Enter a number :"))
print("The number you entered is: ", num)
print("Good bye!")
Execution result:
Enter a number :5
The number you entered is: 5
Enter a number :
You can use CTRL+C to exit the current infinite loop.
Infinite loops are useful for real-time client requests on servers.
while Loop with else Statement
If the condition statement after while is false, the else block is executed.
Syntax format:
while <expr>:
<statement(s)>
else:
<additional_statement(s)>
If the expr condition is true, statement(s) are executed; if false, additional_statement(s) are executed.
Loop through numbers and check their size:
Example
#!/usr/bin/python3
count = 0
while count < 5:
print(count, " is less than 5")
count = count + 1
else:
print(count, " is greater than or equal to 5")
Execution result:
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is greater than or equal to 5
Simple Statement Group
Similar to the syntax of an if statement, if your while loop body contains only one statement, you can place it on the same line as the while statement, as shown below:
Example
#!/usr/bin/python
flag = 1
while (flag): print('Welcome to tutorialpro.org!')
print("Good bye!")
Note: You can use CTRL+C to interrupt the infinite loop above.
Execution result:
Welcome to tutorialpro.org!
Welcome to tutorialpro.org!
Welcome to tutorialpro.org!
Welcome to tutorialpro.org!
Welcome to tutorialpro.org!
……
for Statement
Python's for loop can iterate over any iterable object, such as a list or a string.
The general format of a for loop is as follows:
for <variable> in <sequence>:
<statements>
else:
<statements>
Flowchart:
Python for loop example:
Example
#!/usr/bin/python3
sites = ["Baidu", "Google", "tutorialpro", "Taobao"]
for site in sites:
print(site)
Execution result:
Baidu
Google
tutorialpro
Taobao
It can also be used to print each character in a string:
Example
#!/usr/bin/python3
word = 'tutorialpro'
for letter in word:
print(letter)
Execution result:
r
u
n
o
o
b
Integer range values can be used with the range() function:
Example
#!/usr/bin/python3
for i in range(5):
print(i)
Execution result:
0
1
2
3
4
This is a Chinese to English translation. Please provide the English translation for this text. Do not provide any explanations or text apart from the translation.
Chinese:
# All numbers from 1 to 5:
for number in range(1, 6):
print(number)
The output of the above code is:
1
2
3
4
5
for...else
In Python, the for...else statement is used to execute a block of code after the loop has finished.
The syntax is as follows:
for item in iterable:
# Loop body
else:
# Code to execute after the loop
When the loop completes (i.e., it has iterated through all elements in the iterable), the code in the else clause is executed. If a break statement is encountered during the loop, the loop is terminated, and the else clause is not executed.
Example
for x in range(6):
print(x)
else:
print("Finally finished!")
The output of this script is:
0
1
2
3
4
5
Finally finished!
The following for example uses a break statement. The break statement is used to exit the loop, and the else clause is not executed:
Example
#!/usr/bin/python3
sites = ["Baidu", "Google", "tutorialpro", "Taobao"]
for site in sites:
if site == "tutorialpro":
print("tutorialpro.org!")
break
print("Loop data " + site)
else:
print("No loop data!")
print("Loop completed!")
The output of this script, when the loop reaches "tutorialpro", breaks out of the loop:
Loop data Baidu
Loop data Google
tutorialpro.org!
Loop completed!
range() Function
If you need to iterate over a sequence of numbers, you can use the built-in range() function. It generates a sequence of numbers, for example:
Example
>>> for i in range(5):
... print(i)
...
0
1
2
3
4
You can also use range() to specify a range of values:
Example
>>> for i in range(5, 9):
print(i)
5
6
7
8
>>>
You can also use range() to start at a specified number and specify a different increment (even a negative one, sometimes called 'step'):
Example
>>> for i in range(0, 10, 3):
print(i)
0
3
6
9
>>>
Negative numbers:
Example
>>> for i in range(-10, -100, -30):
print(i)
-10
-40
-70
>>>
You can combine range() and len() functions to iterate over the indices of a sequence, as follows:
Example
>>> a = ['Google', 'Baidu', 'tutorialpro', 'Taobao', 'QQ']
>>> for i in range(len(a)):
... print(i, a[i])
...
0 Google
1 Baidu
2 tutorialpro
3 Taobao
4 QQ
>>>
You can also use range() function to create a list:
Example
>>> list(range(5))
[0, 1, 2, 3, 4]
>>>
For more about the range() function, refer to: https://www.tutorialpro.org/python3/python-func-range.html
break and continue Statements and Loop else Clause
break Execution Flowchart:
continue Execution Flowchart:
while Statement Execution Flow:
for Statement Execution Flow:
The break statement can exit the for and while loop bodies. If terminated from a for or while loop, the corresponding loop else block will not execute.
The continue statement is used to tell Python to skip the remaining statements in the current loop block and continue with the next loop.
Example
Using break in while:
Example
n = 5
while n > 0:
n -= 1
if n == 2:
break
print(n)
print('Loop ended.')
Output:
4
3
Loop ended.
Using continue in while:
Example
n = 5
while n > 0:
n -= 1
if n == 2:
continue
print(n)
Output:
4
3
1
0
The loop has ended.
Output result:
4
3
1
0
The loop has ended.
More examples are as follows:
Example
#!/usr/bin/python3
for letter in 'tutorialpro': # First example
if letter == 'b':
break
print ('Current letter :', letter)
var = 10 # Second example
while var > 0:
print ('Current variable value :', var)
var = var -1
if var == 5:
break
print ("Good bye!")
Execution of the above script outputs:
Current letter : R
Current letter : u
Current letter : n
Current letter : o
Current letter : o
Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Good bye!
The following example loops through the string 'tutorialpro' and skips the output when the letter is 'o':
Example
#!/usr/bin/python3
for letter in 'tutorialpro': # First example
if letter == 'o': # Skip output when letter is 'o'
continue
print ('Current letter :', letter)
var = 10 # Second example
while var > 0:
var = var -1
if var == 5: # Skip output when variable is 5
continue
print ('Current variable value :', var)
print ("Good bye!")
Execution of the above script outputs:
Current letter : R
Current letter : u
Current letter : n
Current letter : b
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Current variable value : 4
Current variable value : 3
Current variable value : 2
Current variable value : 1
Current variable value : 0
Good bye!
The loop statement can have an else clause, which is executed when the loop has exhausted the list (for a for loop) or when the condition becomes false (for a while loop), but not when the loop is terminated by a break statement.
The following example is a loop to find prime numbers:
Example
#!/usr/bin/python3
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n//x)
break
else:
# Loop did not find a factor
print(n, 'is a prime number')
Execution of the above script outputs:
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
pass Statement
Python pass is a null statement to maintain the integrity of the program structure.
pass does nothing; it is generally used as a placeholder statement, as shown in the following examples:
Example
>>>while True:
... pass # Wait for keyboard interrupt (Ctrl+C)
Smallest class:
Example
>>>class MyEmptyClass:
... pass
The following example executes the pass block when the letter is 'o':
Example
#!/usr/bin/python3
for letter in 'tutorialpro':
if letter == 'o':
pass
print ('Executing pass block')
print ('Current letter :', letter)
print ("Good bye!")
Execution of the above script outputs:
Current letter : R
Current letter : u
Current letter : n
Executing pass block
Current letter : o
Executing pass block
Current letter : o
Current letter : b
Good bye!
if None:
print(“Hello”)
for i in [1, 0]:
print(i+1)
i = sum = 0
while i <= 4:
sum += i
i = i+1
print(sum)
while 4 == 4:
print('4')
```python
for char in 'PYTHON STRING':
if char == ' ':
break
print(char, end='')
if char == 'O':
continue