Introduction to Python Loops
This chapter introduces how to use loop statements in Python.
Python has two types of loop statements: for
and while
.
Here is a control structure diagram of Python loop statements:
while
Loop
The general syntax of the while
statement in Python is as follows:
while condition: statements
The flowchart for the while
loop is shown below:
Execution Flow
-
The loop continues to execute as long as the condition is
True
. -
Don't forget to use a colon (
:
) and proper indentation.
Additionally, note that Python does not have a do...while
loop.
Example
The following example uses a while
loop to calculate the sum of numbers from 1 to 100:
#!/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 never be False
. Here's an example:
#!/usr/bin/python3 var = 1 while var == 1: # The expression is always true num = int(input("Enter a number: ")) print("You entered: ", num) print("Good bye!")
Execution Result:
Enter a number: 5 You entered: 5 Enter a number:
You can use CTRL+C
to stop the infinite loop. Infinite loops are useful for handling real-time client requests on a server.
while
Loop with else
When the condition in the while
loop becomes False
, the else
block is executed.
Syntax:
while <expr>: <statement(s)> else: <additional_statement(s)>
If the condition is True
, the while
block executes. If it's False
, the else
block executes.
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 if
statements, if the while
loop contains only one statement, it can be written on the same line as the while
keyword.
Example
#!/usr/bin/python flag = 1 while (flag): print("Welcome to the tutorial!") print("Good bye!")
Note: You can interrupt the above infinite loop by pressing CTRL+C
.
Execution Result:
Welcome to the tutorial! Welcome to the tutorial! Welcome to the tutorial! ...
for
Loop
The for
loop in Python 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:
Example
#!/usr/bin/python3 sites = ["Baidu", "Google", "Runoob", "Taobao"] for site in sites: print(site)
Execution Result:
Baidu Google Runoob Taobao
You can also use a for
loop to print each character in a string.
Example
#!/usr/bin/python3 word = 'runoob' for letter in word: print(letter)
Execution Result:
r u n o o b
Using range()
with a for
Loop
You can use the range()
function to loop through a range of numbers.
Example
#!/usr/bin/python3 # All numbers from 1 to 5: for number in range(1, 6): print(number)
Execution Result:
1 2 3 4 5
for...else
Statement
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 finishes
When the loop completes (i.e., after iterating through all elements of the iterable), the code inside the else
clause will be executed. However, if the loop encounters a break
statement, it will exit the loop immediately, and the else
clause will not be executed.
Example
for x in range(6): print(x) else: print("Finally finished!")
Execution Result:
0 1 2 3 4 5 Finally finished!
In the following for
loop example, a break
statement is used to exit the loop early. In this case, the else
clause will not be executed:
Example
#!/usr/bin/python3 sites = ["Baidu", "Google", "Runoob", "Taobao"] for site in sites: if site == "Runoob": print("cainiao") break print("Looping through: " + site) else: print("No more data in the loop!") print("Loop finished!")
When the loop encounters "Runoob", it will exit:
Execution Result:
Looping through: Baidu Looping through: Google cainiao Loop finished!
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.
Example
>>> for i in range(5): ... print(i) ...
Execution Result:
0 1 2 3 4
You can also specify the start and end values for the range()
function:
Example
>>> for i in range(5, 9): print(i)
Execution Result:
5 6 7 8
You can make range()
start at a specific number and use a custom step value (even negative numbers, which is sometimes called a 'step'):
Example with Positive Step
>>> for i in range(0, 10, 3): print(i)
Execution Result:
0 3 6 9
Example with Negative Step
>>> for i in range(-10, -100, -30): print(i)
Execution Result:
-10 -40 -70
You can also combine the range()
function with len()
to iterate over the indices of a sequence:
Example
>>> a = ['Google', 'Baidu', 'Runoob', 'Taobao', 'QQ'] >>> for i in range(len(a)): ... print(i, a[i]) ...
Execution Result:
0 Google 1 Baidu 2 Runoob 3 Taobao 4 QQ
Additionally, you can use the range()
function to create a list:
Example
>>> list(range(5)) [0, 1, 2, 3, 4]
break
and continue
Statements and the else
Clause in Loops
break
Flowchart:
The break
statement allows you to exit a for
or while
loop prematurely. If you terminate a loop using break
, any corresponding else
block will not be executed.
continue
Flowchart:
The continue
statement is used to skip the remaining code inside the loop for the current iteration and move on to the next iteration.
Code Execution for while
Statement:
Code Execution for for
Statement:
Using break
in a while
Loop
In the following example, break
is used to exit the while
loop:
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 a while
Loop
The continue
statement skips the rest of the code and proceeds with the next iteration of the loop:
Example
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
Example 1
In this example, we use break
to exit the loop when the letter 'b'
is encountered:
#!/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 -= 1 if var == 5: break print("Goodbye!")
Output:
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 Goodbye!
Using continue
to Skip Loop Iterations
In this example, we skip printing the letter 'o'
:
Example 2
#!/usr/bin/python3 for letter in 'Runoob': # First example if letter == 'o': # Skip 'o' continue print('Current letter:', letter) var = 10 # Second example while var > 0: var -= 1 if var == 5: # Skip when var is 5 continue print('Current variable value:', var) print("Goodbye!")
Output:
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 Goodbye!
else
Clause in Loops
Loops in Python can have an else
clause, which is executed when the loop exhausts the list (in for
loops) or when the condition becomes False
(in while
loops). However, if the loop is terminated by a break
statement, the else
clause will not execute.
Here is an example that uses loops 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')
Output:
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
The pass
statement in Python is a null statement. It is used when a statement is required syntactically but you do not want to execute any code. It is generally used as a placeholder.
Example: pass
in a Loop
>>> while True: ... pass # Waiting for keyboard interrupt (Ctrl+C)
Minimal Class Example
>>> class MyEmptyClass: ... pass
Example: Using pass
in a Loop
#!/usr/bin/python3 for letter in 'Runoob': if letter == 'o': pass print('Executing pass block') print('Current letter:', letter) print("Goodbye!")
Output:
Current letter: R Current letter: u Current letter: n Executing pass block Current letter: o Executing pass block Current letter: o Current letter: b Goodbye!