This part will be dedicated to For and While loops in python as well as Infinite loops and Break. Loops allow us to execute a certain block of codes multiple times without really typing it multiple time. Below is a list of topics we have already gone through:
- Seven steps to compile Python 3.5.0 from source
- Getting started with Python and Anjuta
- Starting up with Python – Part 1 – Numbers and Maths, Variables
- Starting up with Python – Part 2 – Modules and Functions, Strings
- Starting up with Python – Part 3 – Sequences and List, Slicing and Editing
- Starting up with Python – Part 4 – More list functions and Slicing lists
- Starting up with Python – Part 5 – Methods
- Starting up with Python – Part 6 – Sort and Tuples, Strings and stuff, methods and Dictionary
- Starting up with Python – Part 7 – If statement, Else and elif statements
- Starting up with Python – Part 8 – Nesting and Comparison operators
- Starting up with Python – Part 9 – And and Or operators
21. The While loop
To make a basic loop, we will need a variable. The code below shows a which is assigned to 1. Then in the second line, it says while 1 is less or equal to 10, let’s print a by adding 1 to it. This will keeps on adding 1 until a is less or equal to 10. If the fourth line is not used, a will be equal to 1 for the whole time because it does not know when a will end.
#! /usr/bin/env python
a = 1
while a <=10:
print a
a +=1
22. The For loop
The code below shows a list where the variable country is assigned with values. At line 2 when the for loop starts, it puts every country’s name in the value called a. The code simply said for a in country each time several times by grabbing all values (countries) assigned to country. So, the output is done by assigning the value of each time to the line it’s printing.
#! /usr/bin/env python
country=['mauritius','usa','france','uk']
for a in country:
print 'i want to go to ' + a
23. The Infinite loop
The loop here is going to print the country together with the temperature value.
#! /usr/bin/env python
temperature={‘mauritius’:42,’usa’:1,’france’:12}
for a in temperature:
print a, temperature[a]
24. Break a loop
What is most interesting is to break a loop by keeping the prompt until the right answer is found. Here is an example. As you can see the while 1 is a test to keep on looping forever. To stop the unlimited look, we use a break statement at line 2. The variable name is used to test the break statement. So each time a name is going to be inserted, it’s going to store it in raw_input. What is going to happen is that it’s going to loop forever until the name ‘nitin‘ is found.
>>> while 1:
... name = raw_input('My name is: ')
... if name == 'nitin': break
...
My name is: tim
My name is: what?
My name is: nitin