0% found this document useful (0 votes)
4 views42 pages

P3 FlowControl

Module 3 covers fundamental Python programming concepts including the Boolean data type, relational operators, decision-making structures (if, if-else), and loops (while, for). It also discusses list manipulation, sorting algorithms, and logical and bitwise operations. Additionally, it introduces membership and identity operators, along with practical examples and exercises related to these topics.

Uploaded by

s112701018.mg12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views42 pages

P3 FlowControl

Module 3 covers fundamental Python programming concepts including the Boolean data type, relational operators, decision-making structures (if, if-else), and loops (while, for). It also discusses list manipulation, sorting algorithms, and logical and bitwise operations. Additionally, it introduces membership and identity operators, along with practical examples and exercises related to these topics.

Uploaded by

s112701018.mg12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Module 3 Topics

 the Boolean data type;


 relational operators;
 making decisions in Python (if, if-else, if-elif,else)
 how to repeat code execution using loops (while, for)
 how to perform logic and bitwise operations in Python;
 lists in Python (constructing, indexing, and slicing; content
manipulation)
 how to sort a list using bubble-sort algorithms;
 multidimensional lists and their applications.

廖文宏 Python Programming 1


Flow Control
 sequential statements  Iteration/loop statements
 Selection statements  for
 if…else…  while
 (cascade) if…elif…else…  (python 不支援 do…while)
 (python 不支援 switch)

廖文宏 Python Programming 2


3.1.1 Relational Operators
 a.k.a Comparison Operators 關係運算子

 get a True/False value

廖文宏 Python Programming 3


Assignment Operators
 指定運算子
= += -= *= /= %= &= ^= |= <<= >>=
 表示將等號右邊的值指定給等號左邊的變數

 e.g.
a = 8;
 e.g.
a = a + 8;
相當於
a += 8;

廖文宏 Python Programming 4


3.1.1.5 if-Condition Statements
 Syntax
if booleanExpression1 : a colon followed by a newline
statements
[elif booleanExpression2 :
statements]
[else:
statements]

 indentation is Python’s way of grouping statements


 even though it may look the same if you use tabs mixed
with spaces, it's important to make all indentations exactly
the same
廖文宏 Python Programming 5
3.1.1.9 if Statements - Example 1
 Example : fine the maximum of two number x,y

if (x<y): if (x<y): max=x


max=x else: max=y
else:
alternate syntax
max=y

廖文宏 Python Programming 6


3.1.1.9 if Statements - Example 2
 Example : find the maximum of three number x,y,z
if (x<y): if (x<z) and (y<z): max=x
if (y<z): max=z max=z if (max<y):
else: max=y elif (x<y): max=y
else: max=y if (max<z):
if (x<z): max=z else: max=z
else: max=x max=x

method I: method II: method III:

which one is best?

廖文宏 Python Programming 7


3.1.1.12 Lab: Leap 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.

廖文宏 Python Programming 8


supplement: immediate if
 e.g. maximum of x,y
max = x if x > y else y
 e.g. maximum of x,y,z
max = (x if x > z else z) if x > y else (y if y > z else z)

廖文宏 Python Programming 9


mis-matched else
 e.g. compute f(x,y) = 𝑥𝑥/𝑦𝑦, 𝑖𝑖𝑖𝑖 𝑦𝑦 ≠ 0 𝑎𝑎𝑎𝑎𝑎𝑎 𝑥𝑥⁄𝑦𝑦 ≥ 0
= (𝑥𝑥 + 𝑦𝑦)2 , otherwise

if (y<>0): if (y<>0):
if (x/y>=0): if (x/y>=0):
f=sqrt(x/y) f=sqrt(x/y)
else: else:
f=sqr(x+y) f=sqr(x+y)

廖文宏 Python Programming 10


3.2.1.1 while Loop 迴圏
 Syntax:
while booleanExpression:
statements
 while repeats the execution as long as the condition
evaluates to True.
 executed zero or more times

 In Python, there is at least one instruction inside the loop


body

廖文宏 Python Programming 11


3.2.1 while Loop
 e.g.
counter = 5
while counter != 0:
print("Inside the loop.", counter)
counter -= 1
print("Outside the loop.", counter)
 infinite loop, .e.g.
while True:
print("I'm stuck inside a loop.")

廖文宏 Python Programming 12


3.2.1.4 for Loop
 sometimes it's more important to count the "turns" of the
loop than to check the conditions.
 e.g. for i in range(100):
print(i)
 e.g. for i in range(10,20):
print(i)

 note: do not modify the control variable i inside the loop


body, even the syntax is allowed. It do not work!
廖文宏 Python Programming 13
3.2.1.4 range()
 the range(start, stop, step) function accepts only integers as
its arguments, and generates immutable sequence of
integers.
 the first argument determines the initial (first) value of

the control variable.


 The second argument shows the first value the control

variable will not be assigned.


 e.g. range(2, 8) generate 6 items, from 2 to 7
 the third argument indicates the step

廖文宏 Python Programming 14


Choose a suitable loop
 for loop: if you know the exact number of times a loop will
be executed
 while loop: if you only know the number of times is greater
than 0
 e.g. compute n!, the for loop is the better choice
 e.g. find the Greatest Common Divisor(GCD,最大公因數)
of two number, a and b are both > 0 (輾轉相除法)
gcd(a,b) = gcd(a-b, b), if a>b
= gcd(a, b-a), if a<b
= a, if a=b
 e.g. gcd(9, 24) = gcd(9, 15) = gcd(9, 6) = gcd(3, 6) = gcd(3, 3) = 3
 while loop is the best choice.
廖文宏 Python Programming 15
Empty Instruction: pass
 loop's syntax (include if, elif, else, while, for) demands at
least one instruction inside the body
 e.g.
for i in range(100): # a do-nothing loop
pass

廖文宏 Python Programming 16


Membership Operators
 in, not in
 test if a sequence is presented in an object

 e.g. 'A' in 'AEIOU' # True


 e.g. 'B' in 'AEIOU' # False
 e.g. 'B' not in 'AEIOU' # True

廖文宏 Python Programming 17


Identity Operators is, is not
 compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location
 e.g.
>>> a = 1
>>> b = a
>>> a is b
True
>>> a = 2
>>> a is b
False

廖文宏 Python Programming 18


Fibonacci Series
 e.g.
# Fibonacci series 𝐹𝐹𝑛𝑛 = 𝐹𝐹𝑛𝑛−1 + 𝐹𝐹𝑛𝑛−2
# the sum of two elements defines the next

fn1, fn2 = 1, 0 fn1, fn2 = 1, 0


while fn1 < 1000: for i in range(20):
print(fn1) print(fn1)
fn1,fn2 = fn1+fn2, fn1 fn1,fn2 = fn1+fn2, fn1

else:
print(fn1)

廖文宏 Python Programming 19


3.2.1.7 break & continue
 break: exits the loop immediately, and unconditionally ends
the loop’s operation;
 continue: jump to next turn and the condition expression is
tested immediately.
 e.g.
from random import random from random import random
while True: while True:
i = random() i = random()
if (i>0.8): break if (i<=0.8): continue
print(i)
print(i) break

廖文宏 Python Programming 20


3.2.1.12 Loop's else
 e.g.
for i in range(5):
print(i)
else:
print("else: ", i)
 The loop’s else branch is always executed once, regardless
of whether the loop has entered its body or not.
 Q: what is the output of the following code?
for i in range(5,1):
print(i)
else:
print("else: ", i)
廖文宏 Python Programming 21
Exercise
 Lab 3.2.1.10, 3.2.1.11, 3.2.1.14,
 Lab 3.2.1.15 - Collatz conjecture 考拉茲猜想
 take any non-negative and non-zero integer number and

name it c0;
 if it's even, evaluate a new c0 as c0 ÷ 2;

 otherwise, if it's odd, evaluate a new c0 as 3 × c0 + 1;

 if c0 ≠ 1, skip to point 2.

廖文宏 Python Programming 22


Exercise: Making Changes
 find all the ways of making changes of n dollars, given 10-,
5-, and 1-dollar coin
=> equivalently, given a non-negative integer n, find all the
non-negative integer solutions of x, y, and z to the equation
10x + 5y + z = n

廖文宏 Python Programming 23


3.3.1.1 Logical Operator 邏輯運算子
 allows us to code complex conditions
 operator truth table 真值表
 and
P Q P and Q P or Q P xor Q not P
 or True True True True False False
 xor True False False True True False
 not False True False True True True
False False False False False True
 e.g. leap year 閏年
if (year%4 == 0) and ((year%100 != 0) or (year%400 == 0)) :
day = 29
else: day = 28
廖文宏 Python Programming 24
Short-Circuit Operation
 and
 iff P is false => P and Q is false without evaluating Q

 or
 iff P is true => P or Q is true without evaluating Q

 e.g. compute f(x,y) = 𝑥𝑥/𝑦𝑦, 𝑖𝑖𝑖𝑖 𝑦𝑦 ≠ 0 𝑎𝑎𝑎𝑎𝑎𝑎 𝑥𝑥⁄𝑦𝑦 ≥ 0


= (𝑥𝑥 + 𝑦𝑦)2 , otherwise
if (y<>0) and (x/y>=0): f=sqrt(x/y)
else: f=sqr(x+y)

if and is complete, then y=0 will result in "divide by zero" error


the order of (y<>0) (x/y>=0) cannot be reversed

廖文宏 Python Programming 25


supplement: Shorthand Logical Statement
 shorthand notation
 x >= 1 and x <= 100

 1 <= x <= 100

 ps:
0, 0.0, empty string、empty list, empty tuple、empty
container, None 都視為 False

廖文宏 Python Programming 26


3.3.1.2 Bitwise Operators 位元運算子
 to manipulate single bits of data
 operands must be integers
 operator
& (ampersand) bitwise conjunction
| (bar) bitwise disjunction
~ (tilde) bitwise negation
^ (caret) bitwise exclusive or (xor)
P Q P&Q P|Q P^Q
1 1 1 1 0
1 0 0 1 1
0 1 0 1 1
廖文宏 0 0 0 0 0 Python Programming 27
3.3.1.3 Logic versus Bit operations
 i = 15
j = 22
 log = i and j # 22 / True

versus
 bit = i & j # 6

廖文宏 Python Programming 28


3.3.1.4 deal with single bit
 Check the state of bit
x&1=x
 reset the bit
x&0=0
 set the bit
x|1=1
 negate bit
x ^ 1 = ~x

廖文宏 Python Programming 29


3.3.1.5 shifting operator
 << shift of all the digits to the left and filling the resulting
gap with zero.
 >> shift of all the digits to the right and filling the resulting
gap with sign bit.(sign bit extension)
e.g. -1 >> 1

 this is applied only to integer values, and you mustn’t use


floats as arguments for it.

廖文宏 Python Programming 30


3.4 Lists 串列
 multiple value literal
 The most versatile compound data types is the list, which
can be written as a list of comma-separated values (items)
between square brackets, e.g.
>>> squares = [1, 4, 9, 16, 25]
 The elements inside a list may have different types. Some
of them may be integers, others floats, and yet others may
be lists.
 List is a collection of elements, but each element is a scalar.

廖文宏 Python Programming 31


3.4.1.2 Lists
 lists can be indexed and sliced
 elements in a list are always numbered starting from zero.

 e.g. square[0] is first element of list square


 All slice operations return a new list containing the
requested elements
 Lists also support operations like concatenation
 nest lists, e.g.
>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
廖文宏 Python Programming 32
3.4.1.4 Removing elements from a list
 e.g. remove second element from list numbers
del numbers[1]
 list’s length will be reduced by one

 Note: del is an instruction, not a function.

廖文宏 Python Programming 33


3.4.1.5 Negative Index
 An element with an index equal to -1 is the last one in the
list.
 Similarly, the element with an index equal to -2 is the one
before last in the list.

廖文宏 Python Programming 34


3.4.1.8 Adding elements to a list
 e.g. Append a new element to the end of the existing list.
numbers.append(4)
 e.g. Insert a new element 4 to the second position (index 1)
of the existing list.
numbers.insert(1, 4)
 all the existing elements that occupy locations to the right of
the new element (including the one at the indicated
position) are shifted to the right, in order to make space for
the new element.
 list’s length will be increase by one

廖文宏 Python Programming 35


3.4.1.10 List Iteration
 iterates over the items of any sequence (a list or a string)
 e.g.
list = [1,4,9,16,25]
sum=0
for i in range(len(list)):
sum += list[i]
print(sum)
 e.g.
words = ['cat', 'window', 'defenestrate']
for w in words:
print(w, len(w))

廖文宏 Python Programming 36


3.5.1 Sorting of List
 Bubble Sort
 The elements of the list gradually move to their proper

location in the list, like bubbles rising in water.


 Comparing adjacent elements from left to right. If the

leftmost element in the pair is less than the rightmost


element, the pair will remain in that order. If the
rightmost element is less than the leftmost element, then
swap the two elements.
This cycle repeats from beginning to end until a cycle in
which no more swap occurs.
 list built-in method: sort()

廖文宏 Python Programming 37


3.6.1 List Assignment
 The assignment: list1 list2 = list1
list2 = list1
copies the name of the array, not its
contents.
 Lists (and many other complex Python
entities) are stored in different ways than
ordinary (scalar) variables.
 You could say that:
10 20 30
 the name of an ordinary variable is the

name of its content;


 the name of a list is the name of a

memory location where the list is stored.


廖文宏 Python Programming 38
3.6.1.2 List Slice
 list[start:end]
A slice of this form makes a new (target) list, taking
elements from the source list – the elements of the indices
from start to end-1.
 e.g.
list = [10, 8, 6, 4, 2]
new_list = list[1:3]
print(new_list) # output [10, 8]
 del slice
 e.g. del list[1:3]

廖文宏 Python Programming 39


supplement: List Methods
 .append(x) - Adds an element at the end of the list
 .insert(i, x) - Adds an element at the specified position
 .extend(iterable) - Add the elements of a list (or any
iterable), to the end of the current list
 .count(x) - number of elements with the specified value
 .index(x[, i, [j]]) - index of the first element with the
specified value
 .pop(i) - Removes the element at the specified position
 .remove(x) - Removes the item with the specified value
 .reverse() - Reverses the order of the list
 .sort([key [,reverse]]) - Sorts the list
廖文宏 Python Programming 40
3.7.1 More Lists
 e.g. squares = [ x ** 2 for x in range(10) ]
 produces a ten-element list filled with squares of ten

integer numbers starting from zero


[1, 4, 9, …, 81]
 e.g. twos = [ 2 ** i for i in range(8) ]
 creates an eight-element array containing the first eight

powers of two
[1, 2, 4, 8, 16, 32, 64, 128]
 e.g. odds = [x for x in squares if x % 2 != 0 ]
 makes a list with only the odd elements of the squares

list.
廖文宏 Python Programming 41
3.7.1.2 Multuple Dimension List
 two dimension list, e.g.
board = []
for i in range(8)
row = [0 for i in range(8)]
board.append(row)

廖文宏 Python Programming 42

You might also like