Lab 8 - Python 2
Lab 8 - Python 2
In the last lab exercise, we learned basic input, output, assignment functions in Python. In this lab
exercise, we will learn two important statements: condition and loop. Before we learn condition and
loop, let’s first look at more operators in Python.
1. Operators
Besides the mathematics operators, there are more operators. For example, we can use
comparison operator to compare values. The values for such expression with comparison
operators are either True or False.
1
addition is done ahead of subtraction - don’t be misled. Subtraction and addition are at the same
precedence, and the left-to-right rule applies.
Due to some historical quirk, an exception to the left-to-right left-associative rule is the
exponentiation operator **, so a useful hint is to always use parentheses to force exactly the
order you want when exponentiation is involved:
2. Conditionals
In order to write useful programs, we almost always need the ability to check conditions and
change the behavior of the program accordingly. Conditional statements give us this ability. The
simplest form is the if statement.
The Boolean expression after the if statement is called the condition. If it is true, then all the
indented statements get executed. If not, then all the statements indented under the else clause
get executed. The flow chart of an if statement with an else clause is as follows.
Notice that the if statement consists of a header line and a body. The header line begins with the
keyword if followed by a Boolean expression and ends with a colon (:). The indented statements
that follow are called a block. The first unintended statement marks the end of the block.
Of course, we can omit the else clause. In this case, when the condition evaluates to True, the
statements are executed, otherwise the flow of execution continues to the statement after the if.
The flow chart of an if statement with an else clause is as follows.
2
Figure 2 Flow char of If statement Figure 3 Flow chart of If-else statement
Sometimes there are more than two possibilities and we need more than two branches. One way
to express a computation like that is a chained conditional:
Each condition is checked in order. If the first is false, the next is checked, and so on. If one of
them is true, the corresponding branch executes, and the statement ends. Even if more than one
condition is true, only the first true branch executes.
The following table is the the BMI classifcation in Hong Kong. Remember that we have
calculated BMI in the previous lab. In this lab, you need to use if-elif-else to give the
classification.
BMI Range Classification
BMI<18.5 Underweight
18.5<=BMI<23.0 Normal
23.0<=BMI<25.0 Overweight
BMI>=25.0 Obese
3. For Loop
Sometimes, we have to execute some statements for many times. For example, if we want to
print two “Hello, Worlds!”, we can copy the print statement twice in order to print “Hello,
World!” twice. How about printing “Hello, World!” for 10 times? It is tedious if we have to copy
a statement for 1000 times. In this case, we want to repeat some steps for several times, then we
can use for loop.
5
Figure 7 Hello World for 10 times!
For example in Figure 7, the i in the for statement in line 1 is called the loop variable. Line 2 is
the loop body. The loop body is always indented. The indentation determines exactly what
statements are “in the body of the loop”.
Loop variable i changes from 0 to 9 because computer scientists like to count from 0. Since we
do not use the value of i in this example, we can use an underscore to replace i.
Here, range can deliver a sequence of values to the loop variable in the for loop. They start at 0,
and in the above case do not include 10.
If we want to list each item in a list, then we can replace range with a list.
6
On each iteration or pass of the loop, first a check is done to see if there are still more items to be
processed. If there are none left (this is called the terminating condition of the loop), the loop has
finished. If there are items still to be processed, the loop variable is updated to refer to the next
item in the list. This means, in this case, that the loop body is executed here 4 times, and each
time fruit will refer to a different fruit in the list. At the end of each execution of the body of the
loop, Python returns to the for statement, to see if there are more items to be handled, and to
assign the next one to fruit.
We can use the loop variable to calculate the sum of the first n positive integers as shown in
Figure 9. In this case, we want to have loop variables loop from 1 to n. The code in Figure 9
shows how to calculate the sum. In line 1, we initialize a variable called s to be zero. The value
of n is obtained from user’s input. In line 3, we use range(1, n+1) instead of range(n). Because
range(1,n+1) means that i will change from 1 to n.
7
Some test cases can be found as follows
4. While Loop
We can also use another kind of loops, called While Loop. As long as the condition holds, all the
statements in the loop body will be executed.
We can use while loop to do most of works that for loop can do. For example, we can print
“Hello, World!” for 5 times using while loop.
5. Break a loop
If we want to jump out of the loop, what shall we do? We can use break statement to terminate a
for/while loop. For example, we want to add all the consecutive numbers together and stop doing
the summation when the sum first exceeds 100.
8
Figure 12 Break a loop
When i=13, s=91; when i=14, s=105 which is greater than 100 for the first time. Therefore, the if
condition s>100 holds, and the for look will be terminated. We can use break to terminate a for
loop or while loop.
6. For loop V.S. While loop
Now we have learned two kinds of loop: for loop and while loop. Which loop shall we use?
Use a for loop if you know, before you start looping, the maximum number of times
that you’ll need to execute the body. For example, if you’re traversing a list of
elements, you know that the maximum number of loop iterations you can possibly
need is “all the elements in the list”. Or if you need to print the 12 times table, we
know right away how many times the loop will need to run. So any problem like
“iterate this weather model for 1000 cycles”, or “search this list of words”, “find all
prime numbers up to 10000” suggest that a for loop is best.
By contrast, if you are required to repeat some computation until some condition is
met, and you cannot calculate in advance when (of if) this will happen, you’ll need a
while loop.
We call the first case definite iteration—we know ahead of time some definite bounds for what
is needed. The latter case is called indefinite iteration — we’re not sure how many iterations
we’ll need — we cannot even establish an upper bound!
7. Build a practical application “How to pay with minimum number of coins”
Imagine that you are shopping and paying by cash (coins). In your wallet, you have many $5, $2
and $1 coins. Based on the amount of money you need to pay, there are many possible
combinations. For example, you may pay 5 $2 coins or 2 $5 coins for the amount of $10. You
may pay 4 $2 coins or 1 $5 coin, 1 $2 coin and 1 $1 coin for the amount of $8. This program
finds the combination that the total number of coins is minimum for a certain amount of money
to be paid. The idea is that you should pay as many as possible for the largest value of coins and
then second largest and so on.
9
Task 5. Add a text cell “How to pay with minimum number of notes and coins?”
Task 6. Add a code cell that can ask the user to input the amount of money to be paid. The
amount of money should be an integer. Hence, follow the framework in Figure 13 to
finish the program. The program should be able to display the combination which is
the
minimum number of notes and coins for the amount paid. You are welcome to
redesign
the program based your own algorithm. Figure 14 is the sample output.
Task 7. After you have finished all the tasks, share your code by clicking “Share” to get the
shared link. Remember to change your link access to “Anyone on the Internet with this
link can view”. Copy the link and submit it on Moodle. If your link fails to be opened,
you will be given zero mark.
Task 8. Download the .ipynb file of your codes with a filename Python_2_your student ID.
Submit the file to Moodle.
# How to pay with minimum number of coins?
# amount (integer) is the total amount of money (coins) you need to pay
_______ = int(input("Please input the amount of money you need to pay: "))
if amount > _______: # You should pay if the amount is greater than zero
amount = amount % _______ # The amount left to pay after paying $5 coins
if _______ > 0: # You should only if the amount is still greater than zero
if num > 0:
10
Figure 13 “How to pay with minimum number of coins” framework
Figure 134 “How to pay with minimum number of notes and coins” sample output
References
[1] https://www.w3schools.com/python/
[2] Peter Wentworth, Jeffrey Elkner, Allen B. Downey and Chris Meyers. How to Think Like a
Computer Scientist: Learning with Python 3 (3rd edition).
== Equal x == y
!= Not equal x != y
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
12
3. Python Comparison Operators
13
4. Python Logical Operators
Identity operators are used to compare the objects, not if they are equal, but if they are actually
the same object, with the same memory location:
14
6. Python Membership Operators
Zero fill Shift left by pushing zeros in from the right and let the
<<
left shift leftmost bits fall off
Signed Shift right by pushing copies of the leftmost bit in from
>>
right shift the left, and let the rightmost bits fall off
15