0% found this document useful (0 votes)
75 views21 pages

Module 3

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
75 views21 pages

Module 3

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 21

Questions and answers

A programmer writes a program and the program asks questions.

A computer executes the program and provides the answers. The program must be able
to react according to the received answers.

Fortunately, computers know only two kinds of answers:

 yes, this is true;


 no, this is false.

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.

Comparison: equality operator


Question: are two values equal?

To ask this question, you use the == (equal equal) operator.

Don't forget this important distinction:

 = is an assignment operator, e.g., a = b assigns a with the value of b ;


 == is the question are these values equal?; a == b compares a and b .

It is a binary operator with left-sided binding. It needs two arguments and checks if they
are equal.

Comparison operators: greater than


You can also ask a comparison question using the > (greater than) operator.

If you want to know if there are more black sheep than white ones, you can write it as follows:

black_sheep > white_sheep # Greater than


True confirms it; False denies it.

Comparison operators: greater than or equal to


The greater than operator has another special, non-strict variant, but it's denoted differently than in classical
arithmetic notation: >= (greater than or equal to).

There are two subsequent signs, not one.

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:

centigrade_outside ≥ 0.0 # Greater than or equal to

Comparison operators: less than or equal to


As you've probably already guessed, the operators used in this case are: the < (less than) operator and its non-
strict sibling: <= (less than or equal to).

Look at this simple example:

current_velocity_mph < 85 # Less than


current_velocity_mph ≤ 85 # Less than or equal to

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).

Making use of the answers


What can you do with the answer (i.e., the result of a comparison operation) you get from the computer?
There are at least two possibilities: first, you can memorize it (store it in a variable) and make use of it later.
How do you do that? Well, you would use an arbitrary variable like this:

answer = number_of_lions >= number_of_lionesses

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 == , !=

Conditional execution: the if statement


If a certain sleepless Python developer falls asleep when he or she counts 120 sheep,
and the sleep-inducing procedure may be implemented as a special function
named sleep_and_dream() , the whole code takes the following shape:

if sheep_counter >= 120: # Evaluate a test expression


sleep_and_dream() # Execute if test expression is
True

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.

Take a look at the following code:

if sheep_counter >= 120:


make_a_bed()
take_a_shower()
sleep_and_dream()
feed_the_sheepdogs()

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.

Feeding the sheepdogs, however, is always done (i.e.,


the feed_the_sheepdogs() function is not indented and does not belong to
the if block, which means it is always executed.)

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.

Conditional execution: the if-


else statement
We started out with a simple phrase which read: If the weather is good, we will go for
a walk.

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

Thus, there is a new word: else - this is a keyword.

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).

The if-else execution goes as follows:

 if the condition evaluates to True (its value is not equal to zero),


the perform_if_condition_true statement is executed, and the conditional
statement comes to an end;
 if the condition evaluates to False (it is equal to zero),
the perform_if_condition_false statement is executed, and the conditional
statement comes to an end.

10-25 minutes

Level of difficulty
Easy/Medium
Objectives
Familiarize the student with:

 using the if-elif-else statement;


 finding the proper implementation of verbally defined rules;
 testing code using sample input and output.

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:

 if the year number isn't divisible by four, it's a common year;


 otherwise, if the year number isn't divisible by 100, it's a leap year;
 otherwise, if the year number isn't divisible by 400, it's a common
year;
 otherwise, it's a leap 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.

Test your code using the data we've provided.


Test Data
Sample input: 2000

Expected output: Leap year

Sample input: 2015

Expected output: Common year

Sample input: 1999

Expected output: Common year

Sample input: 1996

Expected output: Leap year

Sample input: 1580

Expected output: Not within the Gregorian calendar period

year = int(input("Enter a year: "))

if year>1582:

if year %4!=0:

print("Common year")

elif year %100!=0:


print("Leap year")

elif year %400!=0:

print("Commpn year")

else:

print("Leap year")

else:

print("Not within the Gregorian calendar period!")

Key takeaways

1. The comparison (otherwise known as relational) operators are used to compare


values. The table below illustrates how the comparison operators work, assuming
that x = 0 , y = 1 , and z = 0 :

Operator Description Example


== returns True if operands' values are equal, and False otherwise
x != y #
!= returns True if operands' values are not equal, and False otherwise
x != z #

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:

 a single if statement, e.g.:

x = 10

if x == 10: # condition
print("x is equal to 10") # Executed if the
condition is True.

 a series of if statements, e.g.:

x = 10

if x > 5: # condition one


print("x is greater than 5") # Executed if
condition one is True.

if x < 10: # condition two


print("x is less than 10") # Executed if
condition two is True.

if x == 10: # condition three


print("x is equal to 10") # Executed if
condition three is True.

Each if statement is tested separately.


 an if-else statement, e.g.:

x = 10

if x < 10: # Condition


print("x is less than 10") # Executed if the
condition is True.

else:
print("x is greater than or equal to 10") #
Executed if the condition is False.

 a series of if statements followed by an else , e.g.:

x = 10

if x > 5: # True
print("x > 5")

if x > 8: # True
print("x > 8")

if x > 10: # False


print("x > 10")

else:
print("else will be executed")

Each if is tested separately. The body of else is executed if the


last if is False .
 The if-elif-else statement, e.g.:

x = 10

if x == 10: # True
print("x == 10")

if x > 15: # False


print("x > 15")

elif x > 10: # False


print("x > 10")

elif x > 5: # True


print("x > 5")

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.

 Nested conditional statements, e.g.:

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:

 will ask the user to enter an integer number;


 will use a while loop;
 will check whether the number entered by the user is the same as
the number picked by the magician. If the number chosen by the
user is different than the magician's secret number, the user should
see the message "Ha ha! You're stuck in my loop!" and be prompted
to enter a number again. If the number entered by the user matches
the number picked by the magician, the number should be printed
to the screen, and the magician should say the following
words: "Well done, muggle! You are free now."

The magician is counting on you! Don't disappoint him.

secret_number = 777
print(

"""

+================================+

| Welcome to my game, muggle! |

| Enter an integer number |

| and guess what number I've |

| picked for you. |

| So, what is the secret number? |

+================================+

""")

while int(input("Enter secret number!"))!= secret_number:

print("Ha ha ! You're stuck in my loop !")

print("Well done, muggle! You are free now.")

FOR

Looping your code with for


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 .

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.

Take a look at the snippet:

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)

Run the code to check if you were right.

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:

for i in range(2, 8):


print("The value of i is currently", i)

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 last is 7 (although the range() 's second argument is 8 ).


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!"

Use the skeleton we've provided in the editor.

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

# Write a for loop that counts to five.

# Body of the loop - print the loop iteration number and the word "Mississippi".

# Body of the loop - use: time.sleep(1)

# Write a print function with the final message.

for i in range(1,6):

print(i, "Mississippi")

time.sleep(1)

print("Ready or not, here I come!")

The break and continue statements


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.

These two instructions are:

 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.

Both these words are keywords.

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

print("The break instruction:")

for i in range(1, 6):


if i == 3:

break

print("Inside the loop.", i)

print("Outside the loop.")

# 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
Familiarize the student with:

 using the continue statement in loops;


 reflecting real-life situations in computer code.

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.

It can be used with both the while and for loops.

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.

Your program must:

 ask the user to enter a word;


 use user_word = user_word.upper() to convert the word entered by the
user to upper case; we'll talk about the so-called string
methods and the upper() method very soon - don't worry;
 use conditional execution and the continue statement to "eat" the
following vowels A, E, I, O, U from the inputted word;
 print the uneaten letters to the screen, each one of them on a
separate line.

Test your program with the data we've provided for you.

user_word = input("Enter your word: ")

user_word = user_word.upper()

for letter in user_word:


if letter == "A":

continue

elif letter == "E":

continue

elif letter == "I":

continue

elif letter == "O":

continue

elif letter == "U":

continue

else:

print(letter)

You might also like