All programming languages need ways of doing similar things many times, this is called iteration.
For Loops
For loops allows 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.
It works like this:
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", "Google Chrome", "Opera", "IE"] for browser in browsers: print browser
- Python Programming – Python Loops
- Python Programming – Accessing Lists
- Using Break and Continue Statements in Python
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 range function
We can also use the 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 start at another number, or to specify a different increment (even negative;
Sometimes this is called the ‘step’):
Range Usage
# You can use range() wherever you would use a list.
Example 1
for number in range(0,5): print number
Example 2
>>> range(1,10) [1, 2, 3, 4, 5, 6, 7, 8, 9]
Example 3
a = range(1, 10) for i in a: print i
Example 4
for a in range(21,-1,-2): print a, #output>> 21 19 17 15 13 11 9 7 5 3 1
While Loop
The while loop 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", "Opera", "IE"] 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 while 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
Eternal Loops
Be careful to not make an eternal loop, 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 loop will always be True and will forever print Hello World.
while True: print "Hello World"
Nested Loops
In some script you may want to use nested loops.
A nested loop 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.
Break Example
This will ask the user for an input. The while 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 in a while loop
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
Continue
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
Continue Example
This example is taken from
#!/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!"
Output
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!
Pass
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 ...
Also Read: Python Interview Questions on Decision Making and Loops