Python 3 loop statements
Python 3 Loop Statements
This chapter will introduce the use of loop statements in Python.
Python. Loop statements include for and while.
While Loop
General form of the while statement in Python:
While condition:
Execute statements...
Execution GIF demonstration:
Also, note the colon and indentation. Also, there is no do..while loop in Python.
The following example uses while 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 of numbers 1 to %d is: %d" % (n,sum))
The execution result is as follows:
The sum of numbers 1 to 100 is: 5050
Infinite Loop
We can implement an infinite loop by setting the conditional expression to never be false. The example is as follows:
Example
#!/usr/bin/python3
var = 1
while var == 1: # The expression is always true
num = int(input("Enter a number:"))
print ("The number you entered is: ", num)
print ("Good bye!")
Executing the above script will produce the following output:
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 a server.
Using the else Statement in a while Loop
In a while … else loop, the else block is executed if the conditional statement is false.
The syntax is as follows:
while <expr>:
<statement(s)>
else:
Loop to output numbers and check their size:
Example
#!/usr/bin/python3
count = 0
while count < 5:
print (count, "less than 5")
count = count + 1
else:
print (count, "greater than or equal to 5")
Executing the above script will produce the following output:
0 less than 5
1 less than 5
2 less than 5
3 less than 5
4 less than 5
5 greater than or equal to 5
Simple Statement Group
Similar to the syntax of an if statement, if your while loop contains only one statement, you can write it on the same line as the while loop, as shown below:
Example
#!/usr/bin/python
flag = 1
while (flag): print ('Welcome to Geek Tutorial!')
print ("Good bye!")
Note: You can use CTRL+C to interrupt the infinite loop above.
Executing the above script will produce the following output:
Welcome to Geek Tutorial!
Welcome to Geek Tutorial!
Welcome to Geek Tutorial!
Welcome to Geek Tutorial!
Welcome to Geek Tutorial!
…
For Statement
The Python for loop can iterate over any sequence of items, such as a list or a string.
The general format of a for loop is as follows:
for <variable> in <sequence>:
<statements>
else:
<statements>
Python for loop example:
Example
>>>languages = ["C", "C++", "Perl", "Python"]
>>> for x in languages:
... print (x)
...
C
C++
Perl
Python
>>>
The following for example uses a break statement, which is used to jump out of the current loop body:
Example
#!/usr/bin/python3
sites = ["Baidu", "Google","Geekdoc","Taobao"]
for site in sites:
if site == "Geekdoc":
print("Geek Tutorial!")
break
print("Loop data " + site)
else:
print("No loop data!")
print("Loop completed!")
After executing the script, the loop will exit when it reaches “Geekdoc”:
Loop data Baidu
Loop data Google
Geek Tutorial!
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 the value of the interval:
Example
>>>for i in range(5,9) :
print(i)
5
6
7
8
>>>
You can also make the range start at a specific number and specify a different increment (even a negative number, sometimes called a ‘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 the range() and len() functions to iterate over the indices of a sequence, as shown below:
Example
>>>a = ['Google', 'Baidu', 'Geekdoc', 'Taobao', 'QQ']
>>> for i in range(len(a)):
... print(i, a[i])
...
0 Google
1 Baidu
2 Geekdoc
3 Taobao
4 QQ
>>>
You can also 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
Code execution process:
Break statements can be used to jump out of for and while loops. If you break out of a for or while loop, any corresponding else block will not be executed.
continue is used to tell Python to skip the remaining statements in the current loop block and continue with the next iteration.
Example
Using break in while:
Example
n = 5<br>
while n > 0:<br>
n -= 1<br>
if n == 2:<br>
break<br>
print(n)<br>
print('End of loop.')<br>
The output is:
4
3
End of loop.
Using continue in while:
Example
n = 5<br>
while n > 0:<br>
n -= 1<br>
if n == 2:<br>
continue<br>
print(n)<br>
print('The loop ends.')<br>
The output is:
4
3
1
0
The loop ends.
More examples are as follows:
Example
#!/usr/bin/python3
for letter in 'Geekdoc': # First example
if letter == 'c':
break
print ('Current letter is:', letter)
var = 10 # Second example
while var > 0:
print ('Current variable value is:', var)
var = var -1
if var == 5:
break
print ("Good bye!")
The output of executing the above script is:
Current letter is: G
Current letter is: e
Current letter is: e
Current letter is: k
Current letter is: d
Current letter is: o
Current variable value is: 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 “Geekdoc” and skips output when the letter “o” is encountered:
Example
#!/usr/bin/python3
for letter in 'Geekdoc': # First example
if letter == 'o': # Skip output if letter is "o"
continue
print ('Current letter:', letter)
var = 10 # Second example
while var > 0:
var = var -1
if var == 5: # Skip output if variable is 5
continue
print ('Current variable value:', var)
print ("Good bye!") bye!")
Executing the above script will produce the following output:
Current letter: G
Current letter: e
Current letter: e
Current letter: k
Current letter: d
Current letter: c
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!
A loop statement can have an else clause, which is executed when the loop terminates by exhausting the list (in a for loop) or when the condition becomes false (in a while loop). It is not executed when the loop is terminated by a break statement.
The following example is a loop example for finding 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:
# No element found in the loop
print(n, 'is a prime number')
The output of executing the above script is:
2 is a prime number
3 is a prime number
4 is equal to 2 * 2
5 is a prime number
6 is equal to 2 * 3
7 is a prime number
8 is equal to 2 * 4
9 is equal to 3 * 3
pass Statement
A Python pass statement is a blank statement that maintains the integrity of the program structure.
The pass statement does nothing and is generally used as a placeholder, as shown in the following example.
Example
>>>while True:
... pass # Wait for keyboard interrupt (Ctrl+C)
The smallest class:
Example
>>>class MyEmptyClass:
... pass
The following example executes the pass statement block when the letter is o:
Example
#!/usr/bin/python3
for letter in 'Geekdoc':
if letter == 'o':
pass
print ('Executing pass block')
print ('Current letter:', letter)
print ("Good bye!")
Executing the above script will print:
When current letter: G
Current letter: e
Current letter: e
Current letter: k
Current letter: d
Execute the pass block
Current letter: o
Current letter: c
Good bye!