巨量資料探勘與應用
Big Data Mining and Applications
Basic Python Programming I
李建樂
Chien-Yueh Lee, Ph.D.
Assistant Professor
Master Program in Artificial Intelligence
Innovation Frontier Institute of Research for Science and Technology
Department of Electrical Engineering
National Taipei University of Technology
Feb. 24, 2025
Outline
◆ Part 1:Data Types, Variables, and Operators
◆ Part 2:Numeric and String Processing
◆ Part 3:Program Control and Logic
Part 1:Data Types, Variables, and Operators
◆ Simple Data Types
◆ Data Containers
◆ Variables
◆ Constants
◆ Operators
◆ Input & Output
S i m p l e D a t a Ty p e s
N u m e r i c D a t a Ty p e s
◆ int: Represents integers without a decimal part, e.g., 10, -53,
1000000
◆ float:Represents floating-point numbers with a decimal part, e.g.,
3.14159、-123.45、1.5E-3 (1.5×10-3), 2e3 (2.0×103)
◆ complex:Represents complex numbers, with the imaginary part
indicated by j or J, e.g., 2 + 1j or 2 + 1J
◆ bool:Represents Boolean values, which are a subtype of int, with
only two possible values, True (1) and False (0)
>>> print(2e3) >>> print(0b1010) #Binary (Base-2) Representation: Equivalent to 1×23 + 0×22 + 1×21 + 0×20
2000.0 10
>>> print(1 < 2) >>> print(0o107) #Octal (Base-8) Representation: Equivalent to 1×82 + 0×81 + 7×80
True 71
>>> print(1 > 2) >>> print(0x41) #Hexadecimal (Base-16) Representation: Equivalent to4×161 + 1×160
False 65
St r i n g Ty p e
◆ Python uses the str type to handle text data. A string is a sequence of characters
arranged in order, including letters, numbers, and symbols.
◆ There are three ways to define a string in Python:
• Single quotes ('): e.g., 'Python programming'
• Double quotes ("): e.g., "Python程式設計"
• Triple single quotes (''') or triple double quotes (""") for multiple lines: e.g.,
'''1st line >>> print("""Sunday
... Monday
2nd line''' or ... Tuesday""")
"""1st line Sunday
Monday
2nd line""" Tuesday
Data Containers
Data Containers
◆ list (List): A sequence of ordered elements that can be modified.
>>> [1, 3.14, 1+2j, 'NTUT’] #A list with 4 elements
[1, 3.14, (1+2j), 'NTUT']
◆ tuple (Tuple): A sequence of ordered elements that cannot be modified (immutable).
>>> (1, 3.14, 1+2j, 'NTUT') #A tuple with 4 elements
(1, 3.14, (1+2j), 'NTUT')
◆ set (Set): An unordered collection of unique elements that can be modified.
>>> {'NTUT', 1, 3.14, 1+2j, 'NTUT'}
#A set with 4 elements (duplicate "NTUT" is removed)
{(1+2j), 1, 3.14, 'NTUT'}
◆ dict (Dictionary): A collection of key-value pairs, where keys are unique, unordered, and
the content can be modified. >>> {'Language': 'Python', 'Version': '3.13'}
#A dictionary with 2 key-value pairs
{'Language': 'Python', 'Version': '3.13'}
Va r i a b l e s
Va r i a b l e s a n d N a m i n g R u l e s
◆ Variable:A name composed of letters or symbols that stores data for reuse
◆ Naming Rules:
• A variable name must start with a letter (A-Z, a-z) or an underscore (_).
• It can be followed by letters, numbers (0-9), or underscores.
• Case-sensitive: The terms Student and student are regarded as distinct variables.
• Reserved words: Cannot use Python's keywords, built-in constants, functions, or
class names as variable names.
• Best Practices: Use meaningful English words for variable names. Although
Python 3 supports Chinese variable names, it is not recommended to use them.
studentID class
_studentID MyEmail@ID
studentName 7Eleven
student_name !my_name
myCar1 my Car
Constants
Python Keywords and Built-in Constants
◆ Keywords: Reserved words in Python that serve specific purposes and
cannot be used as variable names.
and as assert async await break class continue
def del elif else except finally for from
global if import in is lambda nonlocal not
or pass raise return try while with yield
◆ Constants: Meaningful names that retain a fixed value throughout the
program and cannot be modified.
◆ Common Built-in Constants in Python:
• True (Boolean True, equivalent to 1)
• False (Boolean False, equivalent to 0)
• None (Represents "nothing" or the absence of a value)
Va r i a b l e A s s i g n m e n t i n P y t h o n
◆ Use the assignment operator (=) to assign a value to a variable.
◆ If a variable is assigned multiple times, the latest assignment takes precedence.
◆ Chained assignment: Python allows assigning the same value to multiple
variables simultaneously. >>> PI = 3
>>> PI = 3.14
>>> PI = 'π'
>>> my_University = 'NTUT'
>>> print(my_University) >>> print(PI)
NTUT π
>>> my_Program = '"AI" Program'
>>> print(my_Program) >>> A = B = C = 1
"AI" Program >>> print(A, B, C)
1 1 1
>>> X, Y, Z = 1, 3.14, "Hello"
>>> print(X, Y, Z)
1 3.14 Hello
Operators
Arithmetic Operators in Python
◆ Plus (+):a + b ◆Integer Division (//) (Returns the quotient as an
>>> 1.234 + 5.678 integer, discarding the decimal part)
6.912 >>> 7 // 3
2
◆ Minus (-):a - b
>>> 1.456 - 5.456 ◆Modulo (%) (Returns the remainder)
-4.0
>>> 12.5 % 5
2.5
◆ Multiplication (*):a * b
>>> 10 * 0.5 ◆Exponentiation (**) (Power calculation)
5.0
>>> 9 ** 2
81
◆ Floating-point Division (/) (Returns a decimal result) >>> 9 ** 0.5
3.0
>>> 7 / 3
2.3333333333333335
Comparison Operators in Python
Operator Syntax Description Example Result
Greater than a > b Returns True if a is greater than b, otherwise False. 18 + 3 > 18 True
Less than a < b Returns True if a is less than b, otherwise False. 18 + 3 < 18 False
Greater than or equal to a >= b Returns True if a is greater than or equal to b, otherwise False. 18 + 3 >= 21 True
Less than or equal to a <= b Returns True if a is less than or equal to b, otherwise False. 18 + 3 <= 21 True
Equal to a == b Returns True if a is equal to b, otherwise False. 21 + 5 == 18 + 8 True
Not equal to a != b Returns True if a is not equal to b, otherwise False. 21 + 5 != 18 + 8 False
>>> 10 == 10 >>> 10 <= 10 < 0
True False
>>> 10 == 11 >>> 10 <= 10 < 11
False True
>>> "jack" == "jack" >>> ['a', 'b', 'c'] == ['a', 'b', 'c']
True True
>>> "Tom" == "tom" >>> [1, 2] != [1, 2, 3]
False True
Assignment Operators in Python
Operator Syntax Description Equivalent to
Assignment a = b Assigns the value of b to a. a=b
Addition Assignment a += b Adds b to a and assigns the result to a. a=a+b
Subtraction Assignment a -= b Subtracts b from a and assigns the result to a. a=a-b
Multiplication Assignment a *= b Multiplies a by b and assigns the result to a. a=a*b
Division Assignment a /= b Divides a by b (floating-point division) and assigns the result to a. a=a/b
Integer Division Assignment a //= b Performs integer division and assigns the result to a. a = a // b
Modulo Assignment a %= b Calculates the remainder of a ÷ b and assigns it to a. a=a%b
Exponentiation Assignment a **= b Raises a to the power of b and assigns the result to a. a = a ** b
>>> a = 1 >>> a = 1 >>> a, b, c = 5, 10, 15
>>> b = 2 >>> b = 2 >>> a *= b #a = a * b
>>> a, b = b, a >>> a += b #a = a + b = 1 + 2 >>> print(a)
>>> print(a) >>> print(a) 50
2 3 >>> c %= 4 #c = c % 4
>>> print(b) >>> print(c)
1 3
>>> a = b = c = [0, 1, 2]
Multiple Assignment
>>> b[0] = 99
>>> c = [30, 40, 50]
>>> print(a, b, c)
[99, 1, 2] [99, 1, 2] [30, 40, 50]
>>> a = b = c = 3
>>> print(a, b, c) >>> x = [0, 1, 2]
333 >>> y = x
>>> b = 4; c = 5 >>> y[0] = 99
>>> print(a, b, c) >>> print(x, y)
345 [99, 1, 2] [99, 1, 2]
In-Place Modification Pitfall with Lists in Multiple Assignment
>>> a = b = c = [0, 1, 2]
>>> c = c + [97, 98, 99]
>>> b += [3, 4, 5]
>>> print(a, b, c)
[0, 1, 2, 3, 4, 5] [0, 1, 2, 3, 4, 5] [0, 1, 2, 97, 98, 99]
Logical Operators
◆ and: The syntax is a and b. If both values are True, it returns True; otherwise, it returns False.
◆ or: The syntax is a or b. If both values are False, it returns False; otherwise, it returns True.
◆ not: The syntax is not a. If a is True, it returns False; otherwise, it returns True.
>>> 5 > 4 and 3 > 2
True
>>> 5 > 4 and 3 < 2
X Y X and Y X Y X or Y False
True True True True True True X not X >>> 5 > 4 or 3 < 2
True False False True False True True False True
>>> 5 < 4 or 3 < 2
False True False False True True False True False
False False False False False False >>> not 5 > 4
False
>>> not 5 < 4
True
Simplified Notation for Comparison Operators
◆ If multiple comparison expressions have a transitive relationship (遞移關係) and are
connected by and, the "and" can be omitted for a more concise notation.
>>> x, y, z = 3, 6, 9
>>> x < y and y < z
True
>>> x < y < z
True
>>> x < y and y > z
False
>>> x < y > z
False
>>> x == y and y < z
False
>>> x == y < z
False
Operator precedence (優先權)
Operator Description
High () Parentheses
a ** b Exponentiation
+a, -a Plus, Minus signs
a * b, a / b, a // b, a % b Multiplication, division, integer division, modulus
a + b, a - b Addition, subtraction
>, <, >=, <=, ==, != Comparison operations
not a Logical NOT
a and b Logical AND
Low a or b Logical OR
Input & Output
Output
◆ The built-in print() function in Python can be used to display a specified
string on the screen. The syntax is as follows:
print(value, …, sep = ' ', end = '\n', file = sys.stdout)
>>> print("I", "love", "Python")
I love Python
>>> print("I", "love", "Python", sep="@")
I@love@Python
>>> print("I", "love", "Python", end="~~~")
I love Python~~~
>>> Program = "Python"
>>> print("I", "love", Program)
I love Python
Input
◆ The built-in input() function in Python is used to receive user input. The
syntax is as follows:
input(prompt = None)
>>> PI = 3.14
>>> radius = eval(input("Please enter the radius of the circle: "))
Please enter the radius of the circle: 10
>>> print("The area of the circle with radius ", radius, "is: ", PI * radius * radius)
The area of the circle with radius 10 is 314.0
Part 2:Numeric and String Processing
◆ Numeric Processing
◆ String Processing
Numeric Processing
B u il t- i n N u m er i c F u n ct io n s
◆ abs(x) ◆ hex(x) >>> abs(-1) >>> hex(41)
1 '0x29'
>>> min(-2, -1, 0, 1, 2) >>> oct(41)
◆ min(x1, x2 [, x3…]) ◆ oct(x) -2 '0o51'
>>> max(-2, -1, 0, 1, 2) >>> bin(41)
◆ bin(x)
◆ max(x1, x2 [, x3…]) 2 '0b101001'
>>> int('123')
123
◆ int(x) >>> int(-1.23)
-1
◆ round(x [, precision]) >>> round(-3.6)
-4
>>> round(3.1415926, 4)
◆ pow(x, y) 3.1416
>>> pow(2, 10)
◆ float(x) 1024
>>> float('1.23')
1.23
◆ complex(x) >>> complex('1+2j')
(1+2j)
Mathematical Functions
◆ The math module provides some mathematical constants and functions.
◆ Before using the math module, it must be imported using the import statement.
>>> import math >>> math.sqrt(2) #√2 >>> math.log(2) #ln2
>>> math.pi 1.4142135623730951 0.6931471805599453
3.141592653589793 >>> math.exp(2) #e2 >>> math.log(2, 2)
>>> math.e 7.38905609893065 #log22
2.718281828459045 1.0
Constants math.pi, math.e, math.nan, math.inf
math.ceil(x), math.fabs(x), math.factorial(x), math.floor(x),
Numerical calculations
math.gcd(x, y), math.exp(x), math.log(x[, base]), math.sqrt(x)
Numerical checks math.isfinite(x), math.isinf(x), math.isnan(x)
Angles and radians math.degrees(r), math.radians(d)
math.cos(r), math.sin(r), math.tan(r), math.acos(r),
Trigonometric functions
math.asin(r), math.atan(r)
Random Functions
◆ The built-in random module in Python provides functions for generating
random numbers.
◆ Similarly, before using the random module, it must be imported using
the import statement. >>> import random
>>> random.randint(1, 3)
◆ Commonly used functions include: 2
• random.randint(x, y) >>> random.randint(1, 3)
3
• random.random() >>> random.random()
0.3833900666509351
• random.shuffle(L) >>> random.random()
0.10141547871240342
>>> L = [1, 2, 3, 4, 5]
>>> random.shuffle(L)
>>> print(L)
[2, 3, 5, 4, 1]
Str ing Proce ssin g
B ui l t- i n Str i ng F un cti o ns & Es ca pe C h ar ac te r s
◆ Common built-in string functions: ◆ Common escape characters include:
• len(s) >>> len('Python程式設計') Escape Character Definition
10 \' Single quote (')
• str(n) >>> str(-3.6)
'-3.6' \" Double quote (")
\\ Backslash (\)
◆ For some symbols that cannot be directly
\n Newline
displayed on the screen, such as adding a \t Tab
single quote in a string, a backslash \ can be \b Backspace
used for escaping. This is called an escape >>> print("cell_11\tcell_12\ncell_21\tcell_22")
cell_11 cell_12
character. cell_21 cell_22
>>> print('That's a good idea!') >>> print('That\'s a good idea!')
File "<stdin>", line 1 That's a good idea!
print('That's a good idea!')
^ >>> print(r'That\'s a good idea!')
SyntaxError: invalid syntax That\'s a good idea!
Using Operators
◆ The + operator can be used to ◆ The == operator can be used to compare
concatenate strings. whether two strings are equal.
>>> str1 = 'Welcome to ' >>> print('abc' == 'ABC')
>>> str2 = 'NTUT' False
>>> print(str1 + str2) >>> print('ABC' == 'ABC')
Welcome to NTUT True
◆ The * operator can be used to repeat a ◆ The in operator can be used to check if a
string. specific string exists.
>>> str3 = '因為很重要,所以說三次。\n' ◆ The not in operator can be used to check
>>> print(str3 * 3)
因為很重要,所以說三次。 if a specific string does not exist.
因為很重要,所以說三次。
>>> print('He' in 'Hello')
因為很重要,所以說三次。
True
>>> print('He' not in 'Hello')
False
Retrieving Python Object Inform ation
◆ In Python, all data are objects, and an object's type is defined by a class. For
example, an integer belongs to the int class.
◆ A class acts as a blueprint for objects, defining their data (attributes) and
functions (methods) that operate on them.
◆ Each object in Python has an ID, type, and value. We can use the following
functions to retrieve this information:
• type(x) >>> x = 100 >>> type('-3.6')
>>> type(x) <class 'str'>
• id(x) <class 'int'>
• print(x) >>> id(x)
1573412672
>>> print(x) >>> type(-3.6)
100 <class 'float'>
Indexing & Slicing Operators
◆ To access a specific character in a string variable, use the indexing
operator with square brackets [n].
Index 0 1 2 3 4 5 6 7 8 9
Content P y t h o n 程 式 設 計
Index -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
◆ To extract a substring, use the slicing operator [start:end] to specify the
index range.
>>> str4 = 'Python程式設計' >>> str4[-1] >>> str4[2:5] >>> str4[1:]
>>> str4[0] '計' 'tho' 'ython程式設計'
'P' >>> str4[-10] >>> str4[3:7] >>> str4[:-1]
>>> str4[1] 'P' 'hon程' 'Python程式設'
'y' >>> str4[-10:-1] >>> str4[:]
>>> str4[9] 'Python程式設' 'Python程式設計'
'計'
St ring Co nvers io n Me tho ds
◆ str.upper(s) ◆ str.capitalize(s)
◆ str.lower(s) ◆ str.title(s)
◆ str.swapcase(s) ◆ str.split(s)
◆ str.replace(old, new) ◆ str.join(L)
>>> print('Apple'.upper()) >>> print('apple'.capitalize())
APPLE Apple
>>> print(str.lower('iPhone16')) >>> print('apple watch'.title())
iphone16 Apple Watch
>>> print('iPhone16'.swapcase()) >>> print('You work very hard!'.split())
IpHONE16 ['You', 'work', 'very', 'hard!']
>>> print('iPhone15'.replace('5', '6 Pro')) >>> print('a,b,c,d,e'.split(','))
iPhone16 Pro ['a', 'b', 'c', 'd', 'e']
>>> print(' '.join(['You', 'work', 'very', 'hard!']))
You work very hard!
>>> print(','.join(['a', 'b', 'c', 'd', 'e']))
a,b,c,d,e
S t r i n g Te s t i n g M e t h o d s
◆ str.isalpha(s) ◆ str.isupper(s)
◆ str.isdigit(s) ◆ str.islower(s)
◆ str.isalnum(s) ◆ str.isspace(s)
>>> print('iPhone'.isalpha()) ◆ str.istitle(s)
True
>>> print(str.isalpha('iPhone')) >>> print('iphone16'. isupper())
True False
>>> print('iphone16'. islower())
>>> print(str.isalpha('iPhone16')) True
False >>> print('APPLE'.lower().islower())
>>> print(str.isdigit('iPhone16')) True
False >>> print(" \t\r\n".isspace())
>>> print(str.isdigit('123')) True
True >>> print(" \t\r\nA".isspace())
>>> print('iPhone16'.isalnum()) False
True >>> print('Python Programming'.istitle())
>>> print('iPhone16 Pro'.isalnum()) True
False
Substring Search Methods
◆ str.count(s) ◆ str.find(s)
◆ str.startswith(s) ◆ str.rfind(s)
◆ str.endswith(s)
>>> x = "WowWowWowWowWow" Content W o w W o w W o w W o w W o w
>>> print(x.count("Wow"))
1 1 1 1 1
5 Index 0 1 2 3 4 5 6 7 8 9
0 1 2 3 4
>>> print(x.startswith("Wow"))
True
>>> print(x.startswith("Ha")) >>> print(x.find("Wow"))
False 0
>>> print(x.endswith("Wow")) >>> print(x.rfind("Wow"))
True 12
>>> print(x.endswith("Ha"))
False
M e th od s fo r Re mov in g S pe ci fi e d
Characters or Whitespace
◆ str.strip([chars])
◆ str.lstrip([chars])
◆ str.rstrip([chars])
>>> str5 = " abc \t\r\n" >>> str6 = "www.ntut.edu.tw/"
>>> print(str5.strip()) >>> print(str6.lstrip("www."))
abc ntut.edu.tw/
>>> print(str6.rstrip("/"))
www.ntut.edu.tw
St ring Fo rma tt i ng M et hods
◆ str.ljust(width) >>> "abc".ljust(10)
'abc '
◆ str.rjust(width) >>> "abc".rjust(10)
' abc'
◆ str.center(width) >>> "abc".center(10)
' abc '
◆ str.zfill(width) >>> "-42".zfill(5)
'-0042'
◆ str.format(args)
U s i n g s t r. f o r m a t ( a r g s ) f o r St r i n g I n t e r p o l a t i o n
◆ Without specifying positions, arguments are arranged in order.
>>> '{} {} {}'.format('I', 'love', 'Python')
'I love Python'
◆ Specifying positions to retrieve strings.
>>> '{1} {0} {2}'.format('love', 'I', 'Python')
'I love Python'
◆ Specifying variable names to retrieve strings.
>>> '{sub} {verb} {obj}'.format(verb='love', sub='I', obj='Python')
'I love Python'
Co mparis on of St ring Int erpo lat ion M et ho ds
◆ str.format(args)
>>> item, price, count = "iPhone 16 Pro", 36900, 2
>>> print("Purchase {:s} * {:d}, total {:,} TWD".format(item, count, count*price))
Purchase iPhone 16 Pro * 2, total 73,800 TWD
◆ Python 2 method (also available in Python 3):
>>> item, price, count = "iPhone 16 Pro", 36900, 2
>>> print("Purchase %s * %d, total %d NTD" % (item, count, count*price))
Purchase iPhone 16 Pro * 2, total 73800 NTD
◆ f-strings (Python 3.6+ available)
>>> item, price, count = "iPhone 16 Pro", 36900, 2
>>> print(f"Purchase {item} * {count}, total {count*price:,} NTD")
Purchase iPhone 16 Pro * 2, total 73,800 NTD
U s i n g s t r. f o r m a t ( a r g s ) f o r St r i n g I n t e r p o l a t i o n
◆ Keep two decimal places ◆ Pad with "X" on the right, width ◆ Center-align (pad with spaces
>>> '{:.2f}'.format(3.14159) 4 on both sides, width 10)
'3.14' >>> '{:X<4d}'.format(1) >>> '{:^10d}'.format(12)
'1XXX' ' 12 '
◆ Keep two decimal places
with a sign ◆ Pad with "X" on both sides, ◆ Scientific notation
>>> '{:+.2f}'.format(3.14159) width 4 >>> '{:.2e}'.format(1000000000)
'+3.14' >>> '{:X^4d}'.format(10) '1.00e+09'
>>> '{:-.2f}'.format(-1) 'X10X'
◆ Thousand separator
'-1.00' ◆ Right-align (pad with spaces on >>> '{:,}'.format(1000000)
◆ No decimal the left, width 10) '1,000,000'
>>> '{:.0f}'.format(3.14159) >>> '{:>10d}'.format(12)
◆ Percentage format
'3' ' 12'
>>> '{:.2%}'.format(0.5)
◆ Pad with zeros on the left, ◆ Left-align (pad with spaces on
'50.00%'
width 3 the right, width 10)
>>> '{:0>3d}'.format(7) >>> '{:<10d}'.format(12)
'007' '12 '
Part 3:Program Control and Logic
◆ Flowchart ◆ Advanced selection structures
◆ Basic program structures • Multi-branch if … elif … else
• Sequential structure • Nested if
• Selection structure (if … else) ◆ Advanced loop structures
• Loop structure (for & while) • Nested for loops
◆ Choosing between for and ◆ Break and continue statements
while loops
◆ Using a for loop to iterate over
a list
Flowchar t
Purpose of a Flowchart
◆ Summarizes the program flow in a graphical representation.
◆ Allows planning of program logic before writing code.
◆ Provides an overview of the program's logical structure, serving as a
visual aid for discussing the flow with others.
Co mm on Fl o wc har t Sym bol s
Symbol Name Meaning
Start or End Indicates the beginning or end of a program
Flow direction Shows the direction of the process flow
Processing step Represents a specific task to be performed
Input or Output Represents data input or result output
Single document Input or output in document form
Input or output involving multiple
Multiple documents
documents
Decision making Evaluates a condition and directs the flow
Same-page connector Connects flow within the same page
Cross-page connector Connects flow between different pages
Flowchar t Example
Start
Enter the
purchase amount
Is it over Yes
2000 TWD?
20% discount
No
Print the final
amount
End
Flowchar t Example
Start
Enter the score
No Yes
Is it ≥60?
Print "Failed" Print "Pass"
End
Bas ic Prog ram Stru ctu res
Basic Program Structures
◆ Sequential structure
• A program structure that executes statements one by one in order.
◆ Selection structure
• Used to check a condition and execute different statements based on whether
the result is True or False.
• Python supports selection structures using if.
◆ Loop structure
• Used to repeatedly execute certain statements.
• Python supports loop structures using for and while.
Basic Program Structures
◆ Selection and loop structures often need to check whether a
condition is True or False.
◆ Generally, the following values are considered False, while all other
values are considered True:
• False
• None
• Numeric values equal to zero, such as 0, 0.0, 0j
• '' (empty string), [ ] (empty list), ( ) (empty tuple), { } (empty set)
S eque nti a l St ruct ure
For a program that converts Celsius to Fahrenheit, the steps are:
1. User inputs the Celsius temperature. Start
2. Multiply the input value by 9/5, then plus 32.
Inputs the Celsius
3. Display the calculated result. temperature
F = C * 9/5 + 32
Print the
variable F
End
S el e ct io n Struc ture
◆ Single-branch selection (if) condition
(條件式)
if condition:
statement(s) True (是)
False (否)
... statement(s)
(一個或多個敘述)
The statement block is indented
using 4 spaces or 1 tab.
◆ Two-way selection (if … else) …
condition
if condition: (條件式)
statements1
... True (是) False (否)
else: statements1 statements2
statements2 (敘述1) (敘述2)
...
…
S el e ct io n Struc ture - i f
◆ Example steps for a program that inputs a purchase amount:
Start
1. User inputs the purchase amount
2. Check if the amount exceeds 2000 TWD Enter the
purchase amount
3. If it exceeds 2000 TWD, apply a 20% discount
4. Print the final payable amount Is it over Yes
2000 TWD?
20% discount
No
Print the final
amount
End
S el e ct io n Struc ture - i f … el se
◆ Example steps for a program that determines whether a score is passing:
1. User inputs the score Start
2. Check if the score is greater than or equal to 60
3. If the score is ≥60, print "PASS"
Enter the score
4. Otherwise, print "Failed"
No Yes
Is it ≥60?
Print "Failed" Print "Pass"
End
Comparison Operators
◆ >= is called a comparison operator and is used
to determine whether the result on the left is
greater than or equal to the result on the right.
◆ A comparison operator returns a Boolean value
(i.e., True or False).
◆ Other comparison operators:
• Greater than: >
• Equal to: == Checking for equality uses two equal signs (==),
• Less than: < while a single equal sign (=) is used for variable assignment.
• Less than or equal to: <=
• Not equal to: !=
Logical Operators
X Y X and Y
◆ and operator: True True True
• Returns True only if both conditions are true True False False
• If the first condition is False, the second condition is False True False
not evaluated. False False False
◆ or operator X Y X or Y
◆ Returns True if at least one of the conditions is true True True True
◆ If the first condition is True, the second condition is True False True
not evaluated. False True True
False False False
True and True False or True
Lo op Struc ture s - fo r
Check if there are
◆ The for loop uses a control variable to limit the elements in the iterable
number of loop executions and is also known as a object
counting loop.
◆ It can use an iterable object as the control variable True
to repeatedly execute program statements. Extract one element
and assign it to var
◆ In each iteration, the for loop retrieves an element False
from the iterable object until all elements have var
been processed. Statement1
for var in iterator:
statement1
... Statement2
[else:
statement2
...] Outside statements
outside statements
Iterable Objects
◆ Using range() as an iterable object 0
1
>>> for i in range(5): 2
... print(i) 3
4
◆ Using a list as an iterable object
>>> list1 = [15, 20, 33, 7, 8]
>>> sum = 0
>>> for i in list1: Summation = 83
... sum = sum + i
...
>>> print("Summation = ", sum)
◆ Using a str (string) as an iterable object
>>> str1 = "Hello World"
>>> for s in str1: H-e-l-l-o- -W-o-r-l-d-
... print(s, end="-")
The range() Function
◆ Used to generate a sequence of integers within a specified range:
◆ range(start, [end, step])
• start:The starting value (inclusive), defaults to 0 if not specified.
• end:The ending value (exclusive).
• step:The increment value, defaults to 1 if not specified.
>>> r = range(5) >>> print(list(range(2,5)))
>>> print(r) [2, 3, 4]
range(0, 5) >>> print(list(range(0, 15, 5)))
[0, 5, 10]
>>> print(list(range(0, 10, 3)))
>>> print(list(r)) [0, 3, 6, 9]
[0, 1, 2, 3, 4] >>> print(list(range(0, -10, -2)))
[0, -2, -4, -6, -8]
Lo op Struc ture s - whi le
◆ The while loop is executed based on whether the
condition is met and is also known as a Condition
conditional loop. (條件式)
◆ When entering a while loop, the condition is first
checked. If it evaluates to True, the loop body True (是)
statements are executed. False
◆ After each execution of the statements, the Statement1
(否)
(敘述1)
condition is rechecked. When the condition
becomes False, the loop is exited.
while condition: Statement2
statement1 (敘述2)
...
[else:
statement2 Outside statements
...] (迴圈外的敘述)
outside statements
Use a Conditional Statement to
Create a while Loop
◆ Use a while loop to print 0, 1, 2, 3, 4
>>> i = 0
>>> while i < 5:
... print(i)
... i += 1 #i = i + 1
...
0
1
2
3
4
Use a Conditional Statement to
Create a while … else Loop
◆ Ask users to enter the English word for "Apple"
◆ If the input is incorrect, prompt them to re-enter it until they get it right.
◆ When they answer correctly, print "Correct" and end the program.
What to do if you accidentally
enter an infinite loop?
◆ When using a while loop, avoid falling into an "infinite loop."
◆ If the program accidentally enters an infinite loop:
• In Python shell: Use Ctrl + C to forcefully interrupt the program.
• In Jupyter Notebook: Use the interrupt kernel function to stop
the program.
Choosing Between for &
while Loops
Choosing Between for & while Loops
◆ Characteristics of the for loop:
• Iterates over a specific range and sequentially retrieves elements from an iterable
object.
• When the data has a well-defined range, the for loop is generally preferred.
◆ Characteristics of the while loop:
• Executes based on a conditional statement; the loop continues running while the
condition is True and exits when it becomes False.
• When the data does not have a clear range but requires repetition based on a
condition, the while loop is generally preferred.
◆ These are not strict rules or guidelines—what matters most is writing clear,
understandable, and concise code.
Choosing Between for & while Loops
#Use a for loop to calculate the #Use a while loop to calculate
sum of numbers from 1 to 100. the sum of numbers from 1 to 100.
1 >>> sum = 0 1 >>> sum = 0
2 >>> for i in range(1, 101): 2 >>> counter = 1
3 ... sum += i 3 >>> while counter <= 100:
4 >>> print(sum) 4 ... sum += counter
5 ... counter += 1
6 >>> print(sum)
Using a for Loop to Iterate
Over a List
Me th od s fo r Re adi n g a Li s t U s i n g a fo r L o op
◆ Method 1: Directly retrieve elements from the list
◆ Method 2: Using range(len(L))
◆ Method 3: Using enumerate(L) to retrieve both index and value
Methods for Reading a List Using a for Loop
◆ Method 1: Directly retrieve elements from the list
• Used when all elements in the list need to be accessed sequentially.
Methods for Reading a List Using a for Loop
◆ Method 2: Using range(len(L))
• First, use the len(L) function to calculate the number of elements in the list.
• Then, use the range() function to generate corresponding index values.
• This method allows access to both the index and the elements.
• Useful for applying conditions based on index values to filter elements.
Methods for Reading a List Using a for Loop
◆ Method 3: Using enumerate(L) to retrieve both index and value
• The enumerate() function pairs each element in a list, tuple, or string with its
index.
• Commonly used with a for loop to access both the index and the element at
the same time.
Advanced Selection
Str uct ures
Advanced Selection Structures –
if … elif … else
◆ The elif keyword is a shorthand for "else if".
◆ The elif block can have zero, one, or multiple occurrences.
◆ The else block is optional and can appear at most once.
◆ Unlike single-branch if or two-way if … else, which
if condition1:
handle only one condition, the multi-branch if … elif … statements1
elif condition2:
else structure can handle multiple conditions. statements2
elif condition3:
statements3
...
else:
statementsN
Advanced Selection Structures –
if … elif … else
condition1 statements1
(條件式1) (敘述1)
True (是)
False (否)
condition2 statements2
(條件式2) (敘述2)
True (是)
False (否)
condition3 statements3
(條件式3) True (是) (敘述3)
False (否)
… …
statementsN
(敘述N)
A Multi-branch if … elif … else Example
◆Write a grade conversion program based on the
following conditions:
• 90 and above: Excellent
• 80–89: Grade A
• 70–79: Grade B
• 60–69: Grade C
• Below 59: Failed
Advanced Selection Structure – Nested if
◆An if … else statement can contain another if … else statement
inside it.
◆Proper indentation is crucial to avoid logical errors (bugs).
◆While there is no depth limit, excessive if condition1:
statements1
nesting can make code hard to read. else:
if condition2:
In such cases, consider using multi-branch statements2
else:
if … elif … else instead. if condition3:
statements3
else:
statementsN
...
Comparison of two ways
#if … elif … else #Nested if
score= int(input('Input a score (0~100):')) score= int(input(' 'Input a score (0~100):'))
if score >= 90: if score >= 90:
print('Excellent') print('Excellent')
elif score >= 80: else:
print('Grade A') if score >= 80:
elif score >= 70: print('Grade A')
print('Grade B') else:
elif score >= 60: if score >= 70:
print('Grade C') print('Grade B')
else: else:
print('Failed') if score >= 60:
print('Grade C')
else:
print('Failed')
A d v a n c e d L o o p St r u c t u r e s
Advanced Selection Structures –
Nested for Loop
Can an element be
retrieved from iterable
◆A for loop contains one or more for loops object 1?
True
inside it. Retrieve an element var1
from iterable object 1
False var1
◆Each time the outer for loop executes
Statements1
once, it re-enters the inner for loop.
for var1 in iterator1: Can an element be False
retrieved from iterable
object 2?
statements1
... True
for var2 in iterator2: Retrieve an element var2
from iterable object 2
statements2 var2
...
Statements2
outside statements
Outside statements
Nested for Loop Example
◆Use a nested for loop to generate the 9×9 multiplication table.
b r e a k & c o n t i n u e St a t e m e n t s
The bre a k St at em ent
◆The break statement immediately exits the loop, regardless of its
position in the loop.
The bre a k St at em ent
◆When used in a nested for loop, break
only exits the loop where it is located.
◆Since break forcibly terminates the
loop rather than satisfying the normal
exit condition, any corresponding else
block of the loop will not execute.
The c ont inue Sta te me nt
◆The continue statement halts execution of the remaining code in the current
loop iteration and returns to the beginning of the loop to start the next
iteration.
◆Unlike break, which exits the loop entirely, continue performs two actions:
• Stops execution of the remaining code in the current iteration.
• Jumps to the beginning of the loop and continues execution.
H ow to subm it the assignment?
1 檔案命名HW##_學號
2 將Code改為Markdown
3 將題目以Markdown格式輸入至Cell中並執行
Markdown參考語法:
https://www.markdownguide.org/basic-syntax/
7
下載成…
4 適時給予程式碼註解
選擇.ipynb格式
5 顯示執行結果 8
6 將notebook存檔
HW1-1
◆ Enter two point coordinates (x₁, y₁) and (x₂, y₂), then calculate
and print the distance between them. The input values can
be integers or floats.
Hint:𝐷 = (𝑥2 − 𝑥1)2 + (𝑦2 − 𝑦1)2
HW1-2
◆ Use the math module to calculate the following:
1. Calculate the area of a circle with a radius of 10 using math.pi.
2. Find the value of cos(60°).
3. Compute the square root of 7.
4. Determine the greatest common divisor (GCD/最大公因數) of 616
and 1331.
HW1-3
◆ Given x = log 2 and y = log 3, calculate:
z = 10(x+2y+3)
Then, round the result to the nearest integer and print it.
HW1-4
◆ Given a DNA sequence as the variable "seq" shown below, calculate
the following:
1. Sequence length
2. Counts of A, T, G, and C
3. GC content using the formula:
𝐶𝑜𝑢𝑛𝑡 𝑜𝑓 𝐺 + 𝐶𝑜𝑢𝑛𝑡 𝑜𝑓 𝐶
GC content = × 100%
𝑆𝑒𝑞𝑢𝑒𝑛𝑐𝑒 𝑙𝑒𝑛𝑔𝑡ℎ
seq =
'ATGTTTGTTTTTCTTGTTTTATTGCCACTAGTCTCTAGTCAGTGTGTTAATCTTACA
ACCAGAACTCAATTACCCCCTGCATACACTAATTCTTTCACACGTGGTGTTTATTA
CCCTGACAAAGTTTTCAGATCCTCAGTTTTACATTCAACTCAGGACTTGTTCTTAC
CTTTCTTTTCCAATGTTACTTGGTTCCATGCTATACATGTC'
HW1-5
◆ Assume a type of cell divides every minute, following this pattern:
• 1st division → 2 cells
• 2nd division → 4 cells
• 3rd division → 8 cells
• …and so on, doubling each time.
Write a program to calculate how many minutes it takes for the total
number of cells to reach 1,000,000.
HW1-6
◆Write a program to find and display all prime numbers (質數) between
2 and 100.
• Note: A prime number is a natural number greater than 1 that is only
divisible by 1 and itself.
• Hints:
1. Use a nested for loop
2. Use break to optimize the loop
HW1-7
• Enter a positive integer and perform prime factorization (質因數分解) on
the number.
Example: