Loops: while and for
While and for loops act similar to what they do in Java, the syntax follows the python design and can be seen from the examples below.
condition = 1
while condition < 10:
print(condition)
condition += 1 # this basically means condition=condition+1
print("While loop ended")
the text following the while keyword should return a boolean, here in this case is a numerical comparison which returns a boolean
Hence extending the same logic, we can write an infinite loop by using True instead of the condition statement.
while True:
print("infinite loop")
You can kill infinite loops by killing the python process running, if using a command line, then ctrl+c
would stop the execution.
For loops:
The first while loop functionality can be done using the for loop as below
for egg in range(1, 10):
print(egg)
print("for loop ended")
range()
is a in-built function of Python 3, similar to the print()
function. range()
function creates a list of objects from the start to just before the last object with an increment of 1.
1
2
3
4
5
6
7
8
9
for loop ended
for loop also excels at iterating through lists much better than while loops, here's an example which takes each item off a list and multiplies by 2 and prints it.
eggsList = [1,3,5,7,0,6,12,8,3]
for eachEgg in eggsList:
print(eachEgg*2)
print("for loop ended")
As you can see above the output will be
2
6
10
14
0
12
24
16
6
for loop ended
So the loop's scope is controlled by the four space indentation, if the last print() was also indented the same way we would get the print for every loop.
break
, pass
, for-else
and continue
statements will give you more control over the loops[1][2], but are not used as much. Since we haven't even started to do any coding. Let's revisit those when we need to.
P.S: all the code used in this tutorial is available in github
References:
- https://docs.python.org/3.4/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops
- https://docs.python.org/3.4/tutorial/controlflow.html#pass-statements
No comments:
Post a Comment