All programming languages need ways of doing similar things many times, this is called iteration.
Examples of iteration in Python are Loops. Python uses the For Loop, While Loop and Nested Loops.
- For Loops
- Using the python range function
- While Loop
- Eternal Loops
- Nested Loops
- Breaking out of Loops
For loops in Python allow us to iterate over elements of a sequence, it is often used when you have a piece of code which you want to repeat “n” number of time.
The for loop syntax is below:
for x in list : do this.. do this..
Example of a for loop
Let’s say that you have a list of browsers like below. That reads, for every element that we assign the variable browser, in the list browsers, print out the variable browser
browsers = ["Safari", "Firefox", "Chrome"] for browser in browsers: print browser
Another example of a for loop
Just to get a bit more practice on for loops, see the following examples:
numbers = [1,10,20,30,40,50] sum = 0 for number in numbers: sum = sum + number print sum
Loop through words
Here we use the for loop to loop through the word computer
word = "computer" for letter in word: print letter
Using the python range function
The Python programming language has a built-in function “range” to generate a list containing numbers that we specify inside the range.
The given end point is never part of the generated list;
range(10) generates a list of 10 values, the legal indices for items of a sequence of length 10.
It is possible to let the range function start at another number, or to specify a different increment (even negative.
This is called the ‘step’.
Range Function Syntax
range(start, stop, step)
Start is your position to start.
Stop is the number at which to stop and is not included.
Step is the incrementation, default value is 1.
Range Function Examples
Print the numbers starting with 0 and ending at 5(not including). This example uses a for loop with range.
>>> for number in range(0,5): print number ... 0 1 2 3 4 >>>
Print the range starting with 1 and ending at 10, not including. This range example does not use a for loop.
>>> range(1,10) [1, 2, 3, 4, 5, 6, 7, 8, 9] >>>
This range function example is assigned to a variable. That variable is then iterated through using a for loop.
>>> a = range(1,10) >>> for i in a: print i ... 1 2 3 4 5 6 7 8 9 >>>
This is an example of using a step in range. The step default value is 1. In this example we use -2 as the step and start with 21 until we get to -1.
>>> for a in range(21,-1,-2): print a ... 21 19 17 15 13 11 9 7 5 3 1 >>>
The while loop in Python tells the computer to do something as long as the condition is met It’s construct consists of a block of code and a condition.
Between while and the colon, there is a value that first is True but will later be False.
The condition is evaluated, and if the condition is true, the code within the block is executed.
As long as the statement is True , the rest of the code will run.
The code that will be run has to be in the indented block.
It works like this: ” while this is true, do this “
Example of a While Loop
The example below reads like this: as long as the value of the variable i is less than the length of the list (browsers), print out the variable name.
browsers = ["Safari", "Firefox", "Google Chrome"] i = 0 while i < len(browsers): print browsers[i] i = i + 1
Another example of While Loops
The script below, first sets the variable counter to 0.
For every time the while loop runs, the value of the counter is increased by 2. The loop will run as long as the variable counter is less or equal with 100.
counter = 0 while counter <= 100: print counter counter = counter + 2
Count with While Loops
This small script will count from 0 to 9. The i = i + 1 adds 1 to the i value for every time it runs.
i = 0 while i < 10: print i i = i + 1
Be careful to not make an eternal loop in Python, which is when the loop continues until you press Ctrl+C. Make sure that your while condition will return false at some point.
This loop means that the while condition will always be True and will forever print Hello World.
while True: print "Hello World"
In some script you may want to use nested loops.
A nested loop in Python is a loop inside a loop.
It’s when you have a piece of code you want to run x number of times, then code within that code which you want to run y number of times
In Python, these are heavily used whenever someone has a list of lists – an iterable object within an iterable object.
for x in range(1, 11): for y in range(1, 11): print '%d * %d = %d' % (x, y, x*y)
Breaking out of Loops
To break out from a loop, you can use the keyword “break”. Break stops the execution of the loop, independent of the test. The break statement can be used in both while and for loops.
This will ask the user for an input. The loop ends when the user types “stop”.
while True: reply = raw_input('Enter text, [type "stop" to quit]: ') print reply.lower() if reply == 'stop': break
Another Break Example
Let’s see one more example on how to use the break statement.
while True: num=raw_input("enter number:") print num if num=='20': break
Let’s an example on how to use the break statement in a for loop.
for i in range(1,10): if i == 3: break print i
The continue statement is used to tell Python to skip the rest of the statements in the current loop block and to continue to the next iteration of the loop.
The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop.
The continue statement can be used in both while and for loops.
for i in range(1,10): if i == 3: continue print i
This example is taken from tutorialspoint.com
#!/usr/bin/python for letter in 'Python': # First Example if letter == 'h': continue print 'Current Letter :', letter var = 10 # Second Example while var > 0: var = var -1 if var == 5: continue print 'Current variable value :', var print "Good bye!"
The above output will produce the following result:
Current Letter : P Current Letter : y Current Letter : t Current Letter : o Current Letter : n Current variable value : 10 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 Good bye!
The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.
>>> while True: ... pass # Busy-wait for keyboard interrupt ...
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.