Before we can go into the details of the loops we need to learn about two constructs that modify the loops’ control flow. These are break and continue. Let’s see how they work in general and then with examples in the sections about the loops themselves.
Break
The break statement, as its name suggests, breaks out of the loop. Most of the time it's within a conditional block to prevent the loop if it shouldn't be continued anymore.
while / for some_condition:
execute_this
do_this
break
this_does_not_executed
this_neither
else:
this_is_leaved_behind
this_too
|
Continue
The Parallel to the break statement you can tell the loop to continue the execution at the head again. This means any other statement behind the continue statement does not get executed, however, the loop continues until the condition in the loop’s head evaluates to False. In this case, the else block of the loop is executed when the loop finished.
while / for some_condition:
execute_this
do_this
continue
this_does_not_executed
this_neither
else:
this_is_executed_at_the_end
this_too
|
Now we are ready to take a look at the loops themselves with examples. Are you ready? Why not?.
for loops
for variable in sequence:
statement_1
statement_2
...
statement_n
else:
else_statement_1
else_statement_2
...
else_statement_m
|
Naturally, the else block is optional as only one statement is required in the body of the for loop.
>>> for m in menu:
... print(m)
... else:
... print("What do you want?")
...
eggs
sausage
bacon
spam
What do you want?
|
Range
In the example above it seems really bothersome to define the list of numbers every time again-and-again. there has to be some construct that leverages this from the developer. And there it is the range function.The function requires one parameter: the stop value; and two optional parameters: start and stop.
If the only stop is provided then the range function generates a range from the number 0 until the stop number (the stop number is not included) with the step of 1.
>>> for i in range(10):
... print(i)
...
0
1
2
3
4
5
6
7
8
9
|
As you can see in the example above the numbers are printed from 0 to 9 with a step of 1.
If the start parameter is provided then the range function creates a range between the start and the stop number (again, the stop number is exclusive).
If the start number is greater or equal than the stop number then the loop is not executed.
>>> for i in range(15,20):
... print(i)
...
15
16
17
18
19
>>> for i in range(25,10):
... print(i)
...
|
>>> for i in range(1,10,2):
... print(i)
...
1
3
5
7
9
>>> for i in range(10,1,-1):
... print(i)
...
10
9
8
7
6
5
4
3
2
|
As you can see, the range function is used to execute the loop a finite amount of time.
for loop with break and continue
Now we can know the basics of a for loop let’s add the already known control-flow modifications: break and continue.As I have told you previously if you use to break the whole loop is terminated. Do you remember the sample for the loop from the beginning of this section? Now lets us add a conditional to it to break when the element we iterate through is “spam”:
>>> menu = ['eggs', 'sausage', 'bacon', 'spam']
>>> for m in menu:
... if m == 'spam':
... continue
... print(m)
... else:
... print("What do you want?")
...
eggs
sausage
bacon
What do you want?
>>> menu = ['eggs', 'sausage', 'bacon', 'spam']
>>> for m in menu:
... continue
... print(m)
... else:
... print("What do you want?")
...
What do you want?
|
As you can see, the main difference between continue and break is in the flow of the loop: the first one jumps back and iterates over the remaining elements, the second one terminates the whole loop.
for loop with side-effects
Naturally, you can have side-effects when using a for loop with a list. That’s because the collection you iterate over is not immutable so you can change its value during the loop — which can result in unexpected behavior. Let’s see an example:
>>> l = ['eggs']
>>> for e in l:
... if e == 'eggs':
... l += ['sausage']
... if e == 'sausage':
... l += 'spam'
... print(e)
...
eggs
sausage
s
p
a
m
>>> l
['eggs', 'sausage', 's', 'p', 'a', 'm']
|
As you can see we modified the list during the execution of the for loop so when the loop finished and returned to the head for evaluation it found new elements in the list so the loop continued to execute.
To avoid this we can use a copy of the list to iterate over in the loop:
>>> l = ['eggs']
>>> for e in l[:]:
... if e == 'eggs':
... l += ['sausage']
... if e == 'sausage':
... l += 'spam'
... print(e)
...
eggs
|
while loops
The while loop is designed to execute the loop’s body an indefinite amount of time until a condition is reached. the for loop you can execute the loop’s body only a finite amount of times (depending on the list or the range you provide to it).
And because the while loop needs a conditional statement you can easily create an infinite loop (as seen in the introduction to loops).
Let’s see how a while loop is built up:
while condition_evaluates_to_True:
statement_1
statement_2
...
statement_n
else:
else_statement_1
else_statement_2
...
else_statement_m
|
>>> i = 0
>>> while i < 10:
... i += 1
... else:
... print("Finished loop, i has the value of ", i)
...
Finished loop, i has the value of 10
|
The main usage of a while loop is in games or applications with user interaction for example where you need to get a specific type of input (for example a number) or want to execute logic until the game ended. Let’s see a simple example where we ask the user for numeric input.
1
2
3
4
5
6
7
8
9
|
while True:
try:
a = int(input('Enter a number: '))
except ValueError:
print("This was not a number!")
continue
break
print("You entered: ", a)
|
As you can see in this example, if the user does not enter a number then the application prints out “This was not a number!” and because of the continued statement, it executes the loop again. If the input can be converted to a number then the break statement terminates the endless while loop. If you run the application you might get something like this:
Enter a number: enter
This was not a number!
Enter a number: a
This was not a number!
Enter a number: number
This was not a number!
Enter a number: 23j
This was not a number!
Enter a number: 42
You entered: 42
while loop with break and continue
Naturally, these are just basic examples with break and continue, most of the time you use them in a conditional expression.
Post A Comment:
0 comments: