Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

Advanced Python

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.

Python divides the operators in the following seven groups:


 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators
The explanation and more examples about the operations can be found in Appendix A.
When more than one operator appears in an expression, the order of evaluation depends on the
rules of precedence. Python follows the same precedence rules for its mathematical operators
that mathematics does. The acronym PEMDAS is a useful way to remember the order of
operations:
1. Parentheses have the highest precedence and can be used to force an expression to evaluate in
the order you want.
2. Exponentiation has the next highest precedence.
3. Multiplication and both Division operators have the same precedence, which is higher than
Addition and Subtraction, which also have the same precedence.
4. Addition and Subtraction have the lowest precedence.
Operators with the same precedence are evaluated from left-to-right. The acronym PEDMAS
could mislead you to thinking that division has higher precedence than multiplication, and

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.

Figure 1 Even or Odd

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:

The corresponding flow chart is as follows.

Figure 4 Flow chart of If-Elif-Else


3
elif is an abbreviation of else if. Again, exactly one branch will be executed. There is no limit of
the number of elif statements but only a single (and optional) final else statement is allowed and
it must be the last branch in the statement.

Figure 5 Getting grade with if-elif-else

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

Task 1. Add a text cell “BMI classification”


Task 2. Add a code cell that can output the classification based on the BMI you have
calculated.
4
A framework has already been created for you. You can use it and add three
conditions
to make it work well.

Figure 6 BMI classification framework

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.

Figure 8 I like fruit

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.

Figure 9 Sum of the first n integers

Task 3. Add a text cell “Multiplication of the first n positive integers”


Task 4. Add a code cell that can output the multiplication of the first n positive integers where
n is an integer, obtained from the input. (Hint: You can modify the code in Figure 9.
But
the initial value of s should be 1.)

Figure 10 Task 3 and task 4

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.

Figure 11 Hello World with 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

# num is the number of coins of a particular value you need to pay

# Assuming you have enough $5, $2 and $1 coins

# in your wallet for the payment.

_______ = 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 // 5 # The number of $5 coins needed

if num > _______:

print("You need to pay", num, "$5 coin(s).")

amount = amount % _______ # The amount left to pay after paying $5 coins

if _______ > 0: # You should only if the amount is still greater than zero

num = amount // _______

if num > 0:

print("You need to pay", _______, "$2 coin(s).")

amount = amount _______ _______

if _______ > _______:

print("You need to pay 1 $1 coin.")

10
Figure 13 “How to pay with minimum number of coins” framework

Please input the amount of money you need to pay: 3


You need to pay 1 $2 coin(s).
You need to pay 1 $1 coin.
Please input the amount of money you need to pay: 18
You need to pay 3 $5 coin(s).
You need to pay 1 $2 coin(s).
You need to pay 1 $1 coin.

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

Appendix A. Python Operators

1. Python Arithmetic Operators


Arithmetic operators are used with numeric values to perform common mathematical operations:

Operato Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y


11
2. Python Assignment Operators
Assignment operators are used to assign values to variables:

Operator Example Same As

= 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

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

12
3. Python Comparison Operators

Comparison operators are used to compare two values:

13
4. Python Logical Operators

Logical operators are used to combine conditional statements:

Operator Description Example

Returns True if both


and x < 5 and x < 10
statements are true

Returns True if one of the


or x < 5 or x < 4
statements is true

Reverse the result, returns


not not(x < 5 and x < 10)
False if the result is true

5. Python Identity 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:

Operator Description Example

Returns True if both


is variables are the same x is y
object

Returns True if both


is not variables are not the same x is not y
object

14
6. Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

Operator Description Example

Returns True if a sequence


in with the specified value is x in y
present in the object

Returns True if a sequence


not in with the specified value is x not in y
not present in the object

7. Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

Operator Name Description

& AND Sets each bit to 1 if both bits are 1

| OR Sets each bit to 1 if one of two bits is 1

^ XOR Sets each bit to 1 if only one of two bits is 1

~ NOT Inverts all the bits

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

You might also like