Skip to content

Python3 Loop Statements

This section introduces the use of Python loop statements.

Python has two loop statements: for and while.

The control structure diagram of Python loop statements is shown below:

Keyword / Function Description Example
for Iteration loop, used to traverse sequences or iterable objects for i in list:
while Conditional loop, continuously executes while the condition is True while x > 0:
break Immediately terminates the current loop break
continue Skips the remaining code of the current iteration and proceeds to the next iteration continue
else (loop) Executes when the loop ends normally (not terminated by break) for i in range(3): ... else: ...
pass Placeholder statement in a loop (no operation) for i in range(5): pass
range() Generates integer sequences, often used with for loops range(0, 5)
enumerate() Gets both index and value while traversing for i, v in enumerate(list):

The general form of a while statement in Python:

while condition:
    statements……

The execution flow diagram is as follows:

Execution Gif demonstration:

Also, note the colon and indentation. Additionally, Python does not have a do..while loop.

The following example uses while to calculate the sum from 1 to 100:

#!/usr/bin/env python3
 
n = 100
 
sum = 0
counter = 1
while counter <= n:
    sum = sum + counter
    counter += 1
 
print("Sum of 1 to %d is: %d" % (n,sum))

Execution result:

Sum of 1 to 100 is: 5050

We can implement an infinite loop by setting the conditional expression to never be false, as shown in the example below:

#!/usr/bin/python3
 
var = 1
while var == 1 :  # Expression is always true
   num = int(input("Enter a number: "))
   print ("You entered: ", num)
 
print ("Good bye!")

Executing the above script produces the following output:

Enter a number: 5
You entered:  5
Enter a number: 

You can use CTRL+C to exit the current infinite loop.

Infinite loops are very useful for real-time client requests on servers.

If the condition after while is false, the else statement block is executed.

Syntax format:

while <expr>:
    <statement(s)>
else:
    <additional_statement(s)>

If the expr condition is true, the statement(s) block is executed. If false, additional_statement(s) is executed.

Loop to output numbers and determine their size:

#!/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")

Executing the above script produces the following output:

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

Similar to the syntax of if statements, if your while loop body has only one statement, you can write that statement on the same line as while, as shown below:

#!/usr/bin/python
 
flag = 1
 
while (flag): print ('Welcome to Runoob Tutorial!')
 
print ("Good bye!")

Note: For the above infinite loop, you can use CTRL+C to interrupt the loop.

Executing the above script produces the following output:

Welcome to Runoob Tutorial!
Welcome to Runoob Tutorial!
Welcome to Runoob Tutorial!
Welcome to Runoob Tutorial!
Welcome to Runoob Tutorial!
……

Python for loops 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:

#!/usr/bin/python3
 
sites = ["Baidu", "Google","Runoob","Taobao"]
for site in sites:
    print(site)

Output of the above code:

Baidu
Google
Runoob
Taobao

It can also be used to print each character in a string:

#!/usr/bin/python3
 
word = 'runoob'
 
for letter in word:
    print(letter)

Output of the above code:

r
u
n
o
o
b

Integer range values can be used with the range() function:

#!/usr/bin/python3
 
#  All numbers from 1 to 5:
for number in range(1, 6):
    print(number)

Output of the above code:

1
2
3
4
5

In Python, the for…else statement is used to execute a block of code after the loop ends.

Syntax format:

for item in iterable:
    # Loop body
else:
    # Code executed after the loop ends

When the loop finishes executing (i.e., after iterating through all elements in iterable), the code in the else clause is executed. If a break statement is encountered during the loop, the loop is interrupted and the else clause is not executed.

for x in range(6):
  print(x)
else:
  print("Finally finished!")

After executing the script, the output is:

0
1
2
3
4
5
Finally finished!

The following for example uses a break statement. The break statement is used to jump out of the current loop body, and the else clause will not be executed:

#!/usr/bin/python3
 
sites = ["Baidu", "Google","Runoob","Taobao"]
for site in sites:
    if site == "Runoob":
        print("Runoob Tutorial!")
        break
    print("Loop data " + site)
else:
    print("No loop data!")
print("Loop finished!")

After executing the script, the loop body will be exited when encountering “Runoob”:

Loop data Baidu
Loop data Google
Runoob Tutorial!
Loop finished!

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:

>>>for i in range(5):
...     print(i)
...
0
1
2
3
4

You can also use range() to specify a range of values:

>>>for i in range(5,9) :
    print(i)
 
    
5
6
7
8
>>>

You can also make range() start at a specified number and specify a different increment (which can even be negative, sometimes called a ‘step’):

>>>for i in range(0, 10, 3) :
    print(i)
 
    
0
3
6
9
>>>

Negative numbers:

>>>for i in range(-10, -100, -30) :
    print(i)
 
    
-10
-40
-70
>>>

You can combine the range() and len() functions to iterate over the indices of a sequence, as shown below:

>>>a = ['Google', 'Baidu', 'Runoob', 'Taobao', 'QQ']
>>> for i in range(len(a)):
...     print(i, a[i])
... 
0 Google
1 Baidu
2 Runoob
3 Taobao
4 QQ
>>>

You can also use the range() function to create a list:

>>>list(range(5))
[0, 1, 2, 3, 4]
>>>

For more on the range() function, refer to: https://www.runoob.com/python3/python3-func-range.html


break and continue Statements and the else Clause in Loops

Section titled “break and continue Statements and the else Clause in Loops”

break execution flowchart:

continue execution flowchart:

while statement code execution process:

for statement code execution process:

The break statement can jump out of both for and while loop bodies. If you terminate from a for or while loop, any corresponding loop else block will not be executed.

The continue statement is used to tell Python to skip the remaining statements in the current loop block and then proceed to the next iteration.

Using break in while:

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:

n = 5
while n > 0:
    n -= 1
    if n == 2:
        continue
    print(n)
print('Loop ended.')

Output:

4
3
1
0
Loop ended.

More examples:

#!/usr/bin/python3
 
for letter in 'Runoob':     # 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!")

Output of the above script:

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 Runoob and skips output when encountering the letter o:

#!/usr/bin/python3
 
for letter in 'Runoob':     # First example
   if letter == 'o':        # Skip output when the letter is o
      continue
   print ('Current letter:', letter)
 
var = 10                    # Second example
while var > 0:              
   var = var -1
   if var == 5:             # Skip output when the variable is 5
      continue
   print ('Current variable value:', var)
print ("Good bye!")

Output of the above script:

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!

Loop statements can have an else clause, which is executed when the loop is exhausted (for a for loop) or the condition becomes false (for a while loop), but not when the loop is terminated by break.

The following example is a loop for finding prime numbers:

#!/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:
        # No element found in the loop
        print(n, ' is a prime number')

Output of the above script:

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

Python’s pass is an empty statement, used to maintain the structural integrity of the program.

pass does nothing and is generally used as a placeholder statement, as shown in the example below:

>>>while True:
...     pass  # Wait for keyboard interrupt (Ctrl+C)

Minimal class:

>>>class MyEmptyClass:
...     pass

The following example executes a pass statement block when the letter is o:

#!/usr/bin/python3
 
for letter in 'Runoob': 
   if letter == 'o':
      pass
      print ('Execute pass block')
   print ('Current letter:', letter)
 
print ("Good bye!")

Output of the above script:

Current letter: R
Current letter: u
Current letter: n
Execute pass block
Current letter: o
Execute pass block
Current letter: o
Current letter: b
Good bye!

Exercises