Lesson 6 - Loops in Python
In the previous exercise, Solved tasks for Python lesson 4-5, we've practiced our knowledge from previous lessons.
In the previous tutorial, Solved tasks for Python lesson 4-5, we learned about conditions in Python. In today's lesson, we're going to introduce you all to loops. After today's lesson, we'll have covered almost all of the basic constructs to be able to create reasonable applications.
Loops
The word loop suggests that something is going to be repeated. If we wanted a program to do something 100 times, we certainly wouldn't write the same code 100x. Instead, we'll put it in a loop. There are several types of loops. We'll explain how to use them, and of course, make practical examples.
The while
loop
The while
loop is the simplest loop in Python. It simply repeats
the commands in the block while the condition is True
. It can
contain an optional else
: branch which will be executed when the
condition is no longer True
. The syntax of the loop is the
following:
while (condition): # commands else: # commands
Let's create a simple example. Most of us know Sheldon from The Big Bang Theory. For those who don't, we'll simulate a situation where a guy knocks on his neighbor's door. He always knocks 3 times and then yells: "Penny!". Our code, without a loop, would look like this:
{PYTHON}
print("Knock")
print("Knock")
print("Knock")
print("Penny!")
However, using loops, we no longer have to copy the same code over and over:
{PYTHON}
i = 0
while (i < 3):
print("Knock")
i += 1
print("Penny!")
Console application
Knock
Knock
Knock
Penny!
We've introduced an auxiliary variable named i
. The loop will
run through 3 times. At the very beginning, i
is set to zero, the
loop then prints "Knock" and increases i
by one. It continues in
the same way with values one and two. Once i
hits three, the
condition i < 3
is no longer True
and the loop
terminates. Loops have the same indentation rules as conditions. Now, we can
simply change value 3
to 10
in the loop declaration.
The command will execute 10x without adding anything else to it. Surely, you now
see that loops are a very powerful tool.
Now, let's put the variable incrementation to use. We'll print the numbers
from one to ten. We want our output to be separated by spaces rather than lines.
Therefore, we'll specify the end
parameter for the
print()
function and set the space character to it.
{PYTHON}
i = 1
while (i <= 10):
print(i, end = ' ')
i += 1
The result:
Console application
1 2 3 4 5 6 7 8 9 10
As you can see, the i
variable has a different value after each
iteration (iteration is one step of the loop). Notice that this time, the loop
doesn't start from zero because we want the initial value to be 1
and the last one to be 10
. Also, keep in mind that almost
everything starts from zero in programming (we'll find out why later).
Sequences
To be able to work with other loops, we'll have to get familiar with sequences first. Sequences in Python are container data structures, i.e. they're variables that can contain multiple items. We've already met and used a container structure (strings). Strings are sequences of characters.
The for
loop
If we wanted to work with all of the elements in a sequence, we'd use the
for
loop. This loop always performs a fixed number of
steps which is equal to the number of the elements in a sequence. Its
syntax is the following:
for item in sequence: # commands else: # commands
The for
loop will go over all the items in a sequence. In each
iteration (each step of the loop), the current item will be copied to the
variable (the item
variable in the example) and execute the
commands.
Let's try it out on a string sequence. We'll print the string variable's characters out on separate lines:
{PYTHON}
word = "Hello"
for character in word:
print(character)
The result:
Console application
H
e
l
l
o
The range()
function
You might have noticed that the for
loop's syntax is a bit nicer
than the while
loop's. We can also use it easily to loop over
numeric indexes which we generate using the range()
function. Let's
print the numbers from 1
to 10
again, this time, using
the for
loop:
{PYTHON}
for i in range(1, 11):
print(i, end = ' ')
The result:
Console application
1 2 3 4 5 6 7 8 9 10
As you can see, the range()
function generated a sequence of
numbers from 1
to 10
. There are 3 ways to call the
range()
function:
range(n)
- Generates a sequence of numbers from0
ton - 1
.range(m, n)
- Generates a sequence of numbers fromm
ton - 1
(This is why we specified 11 in the example above).range(m, n, i)
- Generates a sequence of numbers fromm
and everyi
-th number ton - 1
.
The for
loop would be even faster, in this case, than the
while
loop (if used for the same purpose). The while
loop is used for slightly different things. Typically, we call a method that
returns a logical True
/False
value in the
while
loop's parentheses. We could rewrite the original
for
-loop example to use the while
loop like this:
{PYTHON}
for i in range(3):
print("Knock")
print("Penny!")
Console application
Knock
Knock
Knock
Penny!
Nesting loops
Now, let's print a simple multiplication table that contains multiples of
numbers from 1
to 10
. All we need to do is to declare
a loop that goes from 1
to 10
and multiply the control
variable by the current multiplier:
{PYTHON}
print("Here's a simple multiplication table using loops:")
for i in range(1, 11):
print(i, end = " ")
print()
for i in range(1, 11):
print(i * 2, end = " ")
print()
for i in range(1, 11):
print(i * 3, end = " ")
print()
for i in range(1, 11):
print(i * 4, end = " ")
print()
for i in range(1, 11):
print(i * 5, end = " ")
print()
for i in range(1, 11):
print(i * 6, end = " ")
print()
for i in range(1, 11):
print(i * 7, end = " ")
print()
for i in range(1, 11):
print(i * 8, end = " ")
print()
for i in range(1, 11):
print(i * 9, end = " ")
print()
for i in range(1, 11):
print(i * 10, end = " ")
Console application
Simple multiplication table using loops:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
Notice the empty print()
calls which are used to skip a line.
The program works nicely, but we still wrote a lot. Honestly, we could break it
down even more since all it does is repeat 10 times while increasing the
multiplier. What we'll do is nest the loops (put one inside the other):
{PYTHON}
print("Here's a simple multiplication table using nested loops:")
for j in range(1, 11):
for i in range(1, 11):
print(i * j, end = " ")
print()
Makes a big difference, doesn't it? Obviously, we can't use i
in
both loops since they are nested and would count as a re-declaration. The
variable j
for the outer loop goes through from 1
to
10
. During each iteration of the loop, another inner loop with the
variable i
is executed. As we already know, it writes the multiples
and is multiplied by the variable j
. After each time the inner loop
terminates, we also have to break the line using print()
. You may
try to align the printed rows using the ljust()
method so the
numbers will be printed nicely in columns.
Let's make one more program where we'll practice working with an outer
variable. The application will be able to calculate an arbitrary power for an
arbitrary number. Of course, we could just use the **
operator, but
we'll calculate it on our own for completeness' sake:
{PYTHON}
print("Exponent calculator")
print("===================")
a = int(input("Enter the base: "))
n = int(input("Enter the exponent: "))
result = a
for i in range(n - 1):
result = result * a
print("Result: %d" % (result))
print("Thank you for using our exponent calculator")
I'm sure we all know how powers (exponents) work. Just to be sure, let me
remind that, 2^3 = 2 * 2 * 2
. Therefore, we compute
a^n
by multiplying the number a
by the number
a
for n - 1
times. Of course, the result must be
stored in a variable. Initially, it'll have a value of a
and this
value will be gradually multiplied during the loop. We can see that our variable
result
in the loop body is normally accessible. If, however, we
create a variable in a loop body, this variable will be no longer accessible
after the loop terminates.
Console application
Exponent calculator
==========================
Enter the base: 2
Enter the exponent: 3
Result: 8
Thank you for using our exponent calculator
Now, we know what some practical uses of the for
loop are.
Remember that it has a fixed amount of iterations.
Enhancing our calculator
Let's take our calculator from previous lessons and improve it a little bit. We'll add the ability to enter more math problems. The program will not end immediately. Instead, it'll ask the user whether they wish to calculate another math problem. Here is the original version of the code:
{PYTHON}
print("Welcome to calculator!")
a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))
print("Choose one of the following operations:")
print("1 - addition")
print("2 - subtraction")
print("3 - multiplication")
print("4 - division")
option = int(input(""))
if (option == 1):
result = a + b
elif (option == 2):
result = a - b
elif (option == 3):
result = a * b
elif (option == 4):
result = a / b
if option > 0 and option < 5:
print("result: %f" % (result))
else:
print("Invalid option")
print("Thank you for using our calculator.")
Now, we'll put almost all the code into a while
loop. Our
condition will be that the user enters "yes"
, and we'll
check the content of the variable goOn
. This variable is set to
"yes"
in the beginning because the program has to begin
somehow. Then, we'll assign the user's choice to it:
print("Welcome to calculator!") goOn = "yes" while (goOn == "yes"): a = float(input("Enter the first number: ")) b = float(input("Enter the second number: ")) print("Choose one of the following operations:") print("1 - addition") print("2 - subtraction") print("3 - multiplication") print("4 - division") option = int(input("")) if (option == 1): result = a + b elif (option == 2): result = a - b elif (option == 3): result = a * b elif (option == 4): result = a / b if option > 0 and option < 5: print("result: %f" % (result)) else: print("Invalid option") goOn = input("Would you like to make another calculation? [yes/no]") print("Thank you for using our calculator.")
Console application
Welcome to our calculator
Enter the first number: 12
Enter the second number: 128
Choose one of the following operations:
1 - addition
2 - subtraction
3 - multiplication
4 - division
1
Result: 140.000000
Would you like to make another calculation? [yes/no]
yes
Enter the first number
-10.5
Enter the second number:
Our application can now be used multiple times and is almost complete. Note: this is one of the few codes that cannot be run online since our user bot would have to repeat inputs. In the next lesson, Solved tasks for Python lesson 6, we'll show you how to work with arrays. You've already learned quite a lot! Nothing better than a little noggin exercise, right?
In the following exercise, Solved tasks for Python lesson 6, we're gonna practice our knowledge from previous lessons.
Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.
Download
By downloading the following file, you agree to the license terms
Downloaded 5x (939 B)
Application includes source codes in language Python