We will continue Flow Control Statements from the last unit, with loops.
Loops
When we want to do something a few times, we can simply repeat the statement. Lets say we want to print 0,1,2,3,4.
print(0)
print(1)
print(2)
print(3)
print(4)
That is okay when you only want to repeat 2 to 3 times, but it will get tedious if we want to count to 100. In Python, we can use loops to repeat statements. First, let's look at the while loop.
While Loop
We can execute a block of code over and over again with a while
statement. As long as the condition of the while
statement is True
, the code will be executed. In code, a while
statement always consists of the following:
while
keyword- A condition (that evaluates to 'True' or
False
) - A colon (:)
- An indented block, starting from the next line
Example:
count = 0
while(count<5):
print(count)
count = count +1
What do you think the code will output?
0
1
2
3
4
The result is the same, but we didn't have to write so many lines of codes.
The while loop executes dependent on the boolean value generate from the expression inside the parentheses (). As long as the condition is true, the while loop will execute the statements inside the block; otherwise, the while loop will stop. After every loop, it will evaluate the condition again to see if it's still true, and go through another round of execution.
Let's break down the while loop step by step:
Loop #1: at the first time we run the program, count is 0, so the condition count < 5 will return true. It will execute the statements inside the indented block. Print to console and add 1 to count.
Loop #2: count is now 1, and the condition count < 5 is still true. Print to console and add 1 to count.
Loop #3: count is now 2, and the condition count < 5 is still true. Print to console and add 1 to count.
Loop #4: count is now 3, and the condition count < 5 is still true. Print to console and add 1 to count.
Loop #5: count is now 4, and the condition count < 5 is still true. Print to console and add 1 to count.
Loop #6: count is now 5, and the condition count < 5 is false, so the program stops here.
For Loop
In the while
loop, the condition keeps executing until its False
. What if we want to execute the condition only a few number of times? For these situations, we use the for
loop. In code, a for
loop consists of:
- The
for
keyword - A variable name
- The
in
keyword - A call to the
range()
method - A colon (:)
- An indented block, starting from the next line
Example:
for i in range(0,5):
print(i)
The output is the same as the code above, for while
loop.
DO IT YOURSELF: Try to write what happenes after each pass (or after each loop) in the program.
There is something new here, that we haven't touched upon yet. The range()
function. Some functions can be called with multiple arguments separated by a comma, and range()
is one of them. This lets you change the integer passed to range()
to follow any sequence of integers, including starting at a number other than zero.
for i in range(10,12):
print(i)
This will print 10,11
The first argument in range()
will be the point where the loop starts. It ends at the second argument, but doesn't include it for the operations. Hence, range(10,12)
prints 10 and then 11, and then stops at 12.
INTERESTING: The
range()
function can also be called with three arguments. The first two arguments will be the start and stop values, and the third will be the step argument. The step is the amount that the variable is increased by after each iteration. Try it yourself! (Example:range(1,10,2)
)
Lets move on two more important things we need to learn, the break
and continue
statements. They will give us more flexibility in using loops for our tasks.
The break
statement
Lets consider a case where you wish to stop the loop at a certain point during the execution. For example, if you are looking for a number in a list of numbers, and you find it, you would want to stop the program there, in order to save time and computational resources. The loop statements we have learnt so far are unable to do this in a simple way, hence we study the break
statement.
If the execution reaches a break
statement, it immediately exits the loop’s clause. In code, a break
statement simply contains the break keyword.
Example:
for i in range(0,15):
if i == 5:
print("Found")
break
The program above will print Found
when it finds 5 in the range(0,15)
and then breaks out of the loop. As an exercise, try using the same peice of code in your compiler and see the result.
The continue
statement
Similar to break
statements, continue
statements are used inside a loop. When the program execution reaches a continue
statement, the program execution immediately jumps back to the start of the loop and reevaluates the loop’s condition.(This is also what happens when the execution reaches the end of the loop.)
IMPORTANT: If you are trapped in an infinite loop, example: while True: print("Hello") Make sure to use
CTRL-C
orCOMMAND-C
to stop the program. This will send aKeyboardInterrupt
error and cause the program to stop immediately.
Example:
while True:
print('Who are you?')
name = input()
if name != 'Alan':
continue
print('Hello, Alan. What is the password? (It is a kind of meat)')
password = input()
if password == 'chicken':
break
print('Access granted.')
In the program above, we are taking the input as an input, asking for the password, and if they are right, then we grant access. For the first part of code, we check if the name is Alan or not, and if it isn't, we ask them to retry. This is done using the continue
statement. The program won't execute further and start from the beginning. Later on, if the password is wrong, then we break
the loop to prevent access.