Module 3
Module 3
A computer executes the program and provides the answers. The program must be able
to react according to the received answers.
You will never get a response like Let me think...., I don't know, or Probably yes, but I don't know
for sure.
To ask questions, Python uses a set of very special operators. Let's go through them one
after another, illustrating their effects on some simple examples.
It is a binary operator with left-sided binding. It needs two arguments and checks if they
are equal.
If you want to know if there are more black sheep than white ones, you can write it as follows:
Both of these operators (strict and non-strict), as well as the two others discussed in the next section,
are binary operators with left-sided binding, and their priority is greater than that shown by == and != .
If we want to find out whether or not we have to wear a warm hat, we ask the following question:
We're going to check if there's a risk of being fined by the highway police (the first question is strict, the
second isn't).
The content of the variable will tell you the answer to the question asked.
The second possibility is more convenient and far more common: you can use the answer you get to make a
decision about the future of the program.
You need a special instruction for this purpose, and we'll discuss it very soon.
Now we need to update our priority table, and put all the new operators into it. It now looks as follows:
Priority Operator
1 +, - unary
2 **
3 * , / , // , %
4 +, - binary
5 < , <= , > , >=
6 == , !=
You can read it as: if sheep_counter is greater than or equal to 120 , then fall asleep
and dream (i.e., execute the sleep_and_dream function.)
We've said that conditionally executed statements have to be indented. This creates
a very legible structure, clearly demonstrating all possible execution paths in the code.
As you can see, making a bed, taking a shower and falling asleep and dreaming are
all executed conditionally - when sheep_counter reaches the desired limit.
Now we're going to discuss another variant of the conditional statement, which also
allows you to perform an additional action when the condition is not met.
Note - there is not a word about what will happen if the weather is bad. We only know
that we won't go outdoors, but what we could do instead is not known. We may want
to plan something in case of bad weather, too.
We can say, for example: If the weather is good, we will go for a walk, otherwise we
will go to a theater.
Now we know what we'll do if the conditions are met, and we know what we'll do if
not everything goes our way. In other words, we have a "Plan B".
Python allows us to express such alternative plans. This is done with a second, slightly
more complex form of the conditional statement, the if-else statement:
if true_or_false_condition:
perform_if_condition_true
else:
perform_if_condition_false
The part of the code which begins with else says what to do if the condition specified
for the if is not met (note the colon after the word).
10-25 minutes
Level of difficulty
Easy/Medium
Objectives
Familiarize the student with:
Scenario
As you surely know, due to some astronomical reasons, years may
be leap or common. The former are 366 days long, while the latter are 365
days long.
Since the introduction of the Gregorian calendar (in 1582), the following
rule is used to determine the kind of year:
Look at the code in the editor - it only reads a year number, and needs to
be completed with the instructions implementing the test we've just
described.
The code should output one of two possible messages, which are Leap
year or Common year , depending on the value entered.
It would be good to verify if the entered year falls into the Gregorian era,
and output a warning otherwise: Not within the Gregorian calendar period .
Tip: use the != and % operators.
if year>1582:
if year %4!=0:
print("Common year")
print("Commpn year")
else:
print("Leap year")
else:
Key takeaways
x > y #
True if the left operand's value is greater than the right operand's value, y > z #
>
and False otherwise
x < y #
True if the left operand's value is less than the right operand's value, y < z #
<
and False otherwise
x >= y #
x >= z #
True if the left operand's value is greater than or equal to the right operand's
≥ y >= z #
value, and False otherwise
x <= y #
x <= z #
True if the left operand's value is less than or equal to the right operand's
≤ y <= z #
value, and False otherwise
2. When you want to execute some code only if a certain condition is met, you can use
a conditional statement:
x = 10
if x == 10: # condition
print("x is equal to 10") # Executed if the
condition is True.
x = 10
x = 10
else:
print("x is greater than or equal to 10") #
Executed if the condition is False.
x = 10
if x > 5: # True
print("x > 5")
if x > 8: # True
print("x > 8")
else:
print("else will be executed")
x = 10
if x == 10: # True
print("x == 10")
else:
print("else will not be executed")
If the condition for if is False , the program checks the conditions of the
subsequent elif blocks – the first elif block that is True is executed. If all the
conditions are False , the else block will be executed.
x = 10
if x > 5: # True
if x == 6: # False
print("nested: x == 6")
elif x == 10: # True
print("nested: x == 10")
else:
print("nested: else")
else:
print("else")
WHILE
Scenario
A junior magician has picked a secret number. He has hidden it in a
variable named secret_number . He wants everyone who run his program to
play the Guess the secret number game, and guess what number he has
picked for them. Those who don't guess the number will be stuck in an
endless loop forever! Unfortunately, he does not know how to complete
the code.
Your task is to help the magician complete the code in the editor in such a
way so that the code:
secret_number = 777
print(
"""
+================================+
+================================+
""")
FOR
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 .
Actually, the for loop is designed to do more complicated tasks - it can "browse"
large collections of data item by item. We'll show you how to do that soon, but right
now we're going to present a simpler variant of its application.
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 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.
import time
# Body of the loop - print the loop iteration number and the word "Mississippi".
for i in range(1,6):
print(i, "Mississippi")
time.sleep(1)
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
break
# continue - example
if i == 3:
continue
LAB
Estimated time
10-20 minutes
Level of difficulty
Easy
Objectives
Familiarize the student with:
Scenario
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.
user_word = user_word.upper()
continue
continue
continue
continue
continue
else:
print(letter)