Python Note 8
Python Note 8
03/01/2024
Let's look at another example employing the while loop. Follow the
comments to find out the idea and the solution.
odd_numbers = 0
even_numbers = 0
# 0 terminates execution.
while number != 0:
# Check if the number is odd.
if number % 2 == 1:
# Increase the odd_numbers counter.
odd_numbers += 1
else:
# Increase the even_numbers counter.
even_numbers += 1
# Read the next number.
number = int(input("Enter a number or type 0 to stop: "))
# Print results.
print("Odd numbers count:", odd_numbers)
print("Even numbers count:", even_numbers)
The condition that checks if a number is odd can be coded in these equivalent
forms, too:
counter = 5
while counter != 0:
print("Inside the loop.", counter)
counter -= 1
print("Outside the loop.", counter)
This code is intended to print the string "Inside the loop." and the value
stored in the counter variable during a given loop exactly five times. Once
the condition has not been met (the counter variable has reached 0 ), the loop
is exited, and the message "Outside the loop." as well as the value stored
in counter is printed.
But there's one thing that can be written more compactly - the condition of
the while loop.
counter = 5
while counter:
print("Inside the loop.", counter)
counter -= 1
print("Outside the loop.", counter)
Is it more compact than previously? A bit. Is it more legible? That's disputable.
REMEMBER
Don't feel obliged to code your programs in a way that is always the shortest
and the most compact. Readability may be a more important factor. Keep
your code ready for a new programmer.
LAB
Estimated time
15 minutes
Level of difficulty
Easy
Objectives
Scenario
Your task is to help the magician complete the code in the editor in such a
way so that the code:
EXTRA INFO
By the way, look at the print() function. The way we've used it here is
called multi-line printing. You can use triple quotes to print strings on
multiple lines in order to make text easier to read, or create a special text-
based design. Experiment with it.
secret_number = 777
print("""
+================================+
+================================+
""")
Answer:
while True:
# Ask the user to guess the secret number
user_guess = int(input("""Enter an integer number to guess the secret
number:"""))
Another kind of loop available in Python comes from the observation that
sometimes it's more important to count the "turns" of the loop than to
check the conditions.
Imagine that a loop's body needs to be executed exactly one hundred times.
If you would like to use the while loop to do it, it may look like this:
i = 0
while i < 100:
# do_something()
i += 1
It would be nice if somebody could do this boring counting for you. Is that
possible?
Of course it is - there's a special loop for these kinds of tasks, and it is
named for .
for i in range(100):
# do_something()
pass
There are some new elements. Let us tell you about them:
the for keyword opens the for loop; note - there's no condition after it;
you don't have to think about conditions, as they're checked internally,
without any intervention;
any variable after the for keyword is the control variable of the loop;
it counts the loop's turns, and does it automatically;
the in keyword introduces a syntax element describing the range of
possible values being assigned to the control variable;
the range() function (this is a very special function) is responsible for
generating all the desired values of the control variable; in our
example, the function will create (we can even say that it will feed the
loop with) subsequent values from the following set: 0, 1, 2 .. 97, 98,
99; note: in this case, the range() function starts its job from 0 and
finishes it one step (one integer number) before the value of its
argument;
note the pass keyword inside the loop body - it does nothing at all; it's
an empty instruction - we put it here because the for loop's syntax
demands at least one instruction inside the body (by the way
- if , elif , else and while express the same thing)
Our next examples will be a bit more modest in the number of loop
repetitions.
Take a look at the snippet below. Can you predict its output?
for i in range(10):
print("The value of i is currently", i)
Note:
the loop has been executed ten times (it's the range() function's
argument)
the last control variable's value is 9 (not 10 , as it starts from 0 , not
from 1 )
The range() function invocation may be equipped with two arguments, not
just one:
In this case, the first argument determines the initial (first) value of the
control variable.
The last argument shows the first value the control variable will not be
assigned.
Note: the range() function accepts only integers as its arguments, and
generates sequences of integers.
Can you guess the output of the program? Run it to check if you were right
now, too.
The first value shown is 2 (taken from the range() 's first argument.)
The range() function may also accept three arguments - take a look at the
code in the editor.
Can you tell us how many lines will appear in the console and what values
they will contain?
You should be able to see the following lines in the console window:
Do you know why? The first argument passed to the range() function tells us
what the starting number of the sequence is (hence 2 in the output). The
second argument tells the function where to stop the sequence (the function
generates numbers up to the number indicated by the second argument, but
does not include it). Finally, the third argument indicates the step, which
actually means the difference between each number in the sequence of
numbers generated by the function.
Note: if the set generated by the range() function is empty, the loop won't
execute its body at all.
Just like here - there will be no output:
Note: the set generated by the range() has to be sorted in ascending order.
There's no way to force the range() to create a set in a different form when
the range() function accepts exactly two arguments. This means that
the range() 's second argument must be greater than the first.
Let's have a look at a short program whose task is to write some of the first
powers of two:
power = 1
for expo in range(16):
print("2 to the power of", expo, "is", power)
power *= 2
The expo variable is used as a control variable for the loop, and indicates the
current value of the exponent. The exponentiation itself is replaced by
multiplying by two. Since 20 is equal to 1, then 2 × 1 is equal to 2 1, 2 × 21 is
equal to 22, and so on. What is the greatest exponent for which our program
still prints the result?
Run the code and check if the output matches your expectations.
LAB
Estimated time
5-15 minutes
Level of difficulty
Very easy
Objectives
Scenario
Do you know what Mississippi is? Well, it's the name of one of the states and
rivers in the United States. The Mississippi River is about 2,340 miles long,
which makes it the second longest river in the United States (the longest
being the Missouri River). It's so long that a single drop of water needs 90
days to travel its entire length!
The word Mississippi is also used for a slightly different purpose: to count
mississippily.
If you're not familiar with the phrase, we're here to explain to you what it
means: it's used to count seconds.
The idea behind it is that adding the word Mississippi to a number when
counting seconds aloud makes them sound closer to clock-time, and therefore
"one Mississippi, two Mississippi, three Mississippi" will take approximately an
actual three seconds of time! It's often used by children playing hide-and-seek
to make sure the seeker does an honest count.
Your task is very simple here: write a program that uses a for loop to "count
mississippily" to five. Having counted to five, the program should print to the
screen the final message "Ready or not, here I come!"
EXTRA INFO
Note that the code in the editor contains two elements which may not be fully
clear to you at this moment: the import time statement, and
the sleep() method. We're going to talk about them soon.
For the time being, we'd just like you to know that we've imported
the time module and used the sleep() method to suspend the execution of
each subsequent print() function inside the for loop for one second, so that
the message outputted to the console resembles an actual counting. Don't
worry - you'll soon learn more about modules and methods.
Answer:
import time
# Start counting
for i in range(1, 6): # Range from 1 to 5
print(f"{i} Mississippi")
time.sleep(1) # Wait for a second
So far, we've treated the body of the loop as an indivisible and inseparable
sequence of instructions that are performed completely at every turn of the
loop. However, as developer, you could be faced with the following choices:
it appears that it's unnecessary to continue the loop as a whole; you
should refrain from further execution of the loop's body and go further;
it appears that you need to start the next turn of the loop without
completing the execution of the current turn.
Python provides two special instructions for the implementation of both these
tasks. Let's say for the sake of accuracy that their existence in the language is
not necessary - an experienced programmer is able to code any algorithm
without these instructions. Such additions, which don't improve the
language's expressive power, but only simplify the developer's work, are
sometimes called syntactic candy, or syntactic sugar.
break - exits the loop immediately, and unconditionally ends the loop's
operation; the program begins to execute the nearest instruction after
the loop's body;
continue - behaves as if the program has suddenly reached the end of
the body; the next turn is started and the condition expression is
tested immediately.
Now we'll show you two simple examples to illustrate how the two instructions
work. Look at the code in the editor. Run the program and analyze the output.
Modify the code and experiment.
# break - example
# continue - example
print("\nThe continue instruction:")
for i in range(1, 6):
if i == 3:
continue
print("Inside the loop.", i)
print("Outside the loop.")
LAB
Estimated time
10-20 minutes
Level of difficulty
Easy
Objectives
Scenario
Don't print any of the words entered by the user. Use the concept of
conditional execution and the break statement.
while True:
user_enter = input("Enter a word as the secret exit word: ")
if user_enter == "chupacabra":
break
LAB
Estimated time
10-20 minutes
Level of difficulty
Easy
Objectives
The continue statement is used to skip the current block and move ahead to
the next iteration, without executing the statements inside the loop.
Your task here is very special: you must design a vowel eater! Write a
program that uses:
a for loop;
the concept of conditional execution (if-elif-else)
the continue statement.
Test your program with the data we've provided for you.
LAB
Estimated time
5-15 minutes
Level of difficulty
Easy
Objectives
Your task here is even more special than before: you must redesign the (ugly)
vowel eater from the previous lab (3.1.2.10) and create a better, upgraded
(pretty) vowel eater! Write a program that uses:
a for loop;
the concept of conditional execution (if-elif-else)
the continue statement.
Test your program with the data we've provided for you.
Both loops, while and for , have one interesting (and rarely used) feature.
We'll show you how it works - try to judge for yourself if it's usable and
whether you can live without it or not.
In other words, try to convince yourself if the feature is valuable and useful, or
is just syntactic sugar.
Take a look at the snippet in the editor. There's something strange at the end
- the else keyword.
i=1
while i < 5:
print(i)
i += 1
else:
print("else:", i)
As you may have suspected, loops may have the else branch too,
like if s.
Can you guess the output? Run the program to check if you were right.
Modify the snippet a bit so that the loop has no chance to execute its body
even once:
i = 5
while i < 5:
print(i)
i += 1
else:
print("else:", i)
The while 's condition is False at the beginning - can you see it?
Run and test the program, and check whether the else branch has been
executed or not.
for loops behave a bit differently - take a look at the snippet in the editor and
run it.
for i in range(5):
print(i)
else:
print("else:", i)
i = 111
for i in range(2, 1):
print(i)
else:
print("else:", i)
The loop's body won't be executed here at all. Note: we've assigned
the i variable before the loop.
When the loop's body isn't executed, the control variable retains the value it
had before the loop.
Note: if the control variable doesn't exist before the loop starts, it
won't exist when the execution reaches the else branch.
Now we're going to tell you about some other kinds of variables. Our current
variables can only store one value at a time, but there are variables that
can do much more - they can store as many values as you want.
LAB
Estimated time
20-30 minutes
Level of difficulty
Medium
Objectives
Scenario
Listen to this story: a boy and his father, a computer programmer, are playing
with wooden blocks. They are building a pyramid.
# The loop exits when there are not enough blocks to complete the
next layer.
# At this point, 'height' is the height of the last completed layer.
LAB
Estimated time
20 minutes
Level of difficulty
Medium
Objectives
Scenario
The hypothesis says that regardless of the initial value of c0 , it will always go
to 1.
Hint: the most important part of the problem is how to transform Collatz's idea
into a while loop - this is the key to success.