2. Python Programming Review

Yi-Ju Tseng

Review: Introduction to Computer Science 計算機概論

  • Variables, Expressions, and Statements (PY4E Ch2)
  • Conditional Execution (PY4E Ch3)
  • Functions (PY4E Ch4)
  • Iterations (PY4E Ch5)

Variables (PY4E Ch2)

Variable Assignment

  • Use = to assign variables
  • Assignment Statements: Variable name = Value (Fix value/Constants, other variables)

Source

Variable Assignment

var1 = "test" #Assignment statement
var2, var3 = "test2","test3"
print(var1) #Print statement
test
print(var2)
test2
print(var3)
test3
print(var2+var3)
test2test3

Variable Name Rules

  • 不可使用保留字Reserved Words
    • 會變色的基本上都是保留字,如True, False等,在Python有功能的字串
  • 只能由數字0-9字母A-Z a-z,或是底線組成_,且不可以數字開頭
  • 大小寫敏感
  • 建議要是看得懂的字
True
False
False

Data Types 資料型態

  • 文字 (text, string, character)
  • 數值 (numeric)
  • 布林變數 (Boolean, logic)
  • 日期 (date)

文字 (text, string, character)

  • 一般文字,使用單引號雙引號標註,或是使用str(文字內容)宣告
  • 就算內容為數字,只要使用雙引號標注,或是str宣告,即為文字型態(除非有做轉型)
text1 = "abcd"
text2 = "10"
text3 = str("xyz")
text4 = str(100)
print([text1, text2, text3,text4])
['abcd', '10', 'xyz', '100']

數值 (numeric)

包含整數 int與浮點數 float等型態。

整數 int:正數或負數,無小數點

  • 直接指定,或是使用int(數值)宣告整數
  • 數值非整數,則無條件捨去
  • 數值是文字型態,則強迫轉型
int1 = 10
int2 = int(5)
int3 = int(6.7)
int4 = int(6.3)
int5 = int("88")
print([int1, int2, int3, int4, int5])
[10, 5, 6, 6, 88]

數值 (numeric)

包含整數 int與浮點數 float等型態。

浮點數 float:正數或負數,有小數點的數值

  • 直接指定,或是使用float(數值)宣告整數
  • 數值為整數,則自動增加小數點
  • 數值是文字型態,則強迫轉型
float1 = float(10)
float2 = float(6.7)
float3 = float("88.8")
print([float1, float2, float3])
[10.0, 6.7, 88.8]

布林變數 (Boolean, logic)

True or False

a = 1 > 2
print(a)
False
b = 1 < 2
print(b)
True

日期 (date)

Python中並無內建的日期型態,必須使用datetime套件,使用前要記得載入(import)

!pip3 install datetime
import datetime

日期 (date)

當需要用載入套件的功能時,結構為:套件名稱.套件功能或資料類型(可能有多層)

datetime.datetime.now()

  • 第一個datetime為套件名稱
  • 第二個為套件內資料類型,有date, time, datetime等,可查閱文件
  • .now()為更進一步的功能(取得今日的日期物件
today = datetime.datetime.now()
print(today)
2025-02-11 18:26:28.282649

日期 (date)

取得日期後,日期物件有許多內建的功能

  • .year.month
  • 可查閱文件
print(today)
2025-02-11 18:26:28.282649
print(today.year)
2025
print(today.month)
2

日期 (date)

也可直接新增指定日期物件,使用方法為:

  • datetime.date(年,月,日)
  • datetime.datetime(年,月,日,時,分,秒)
  • 時分秒不指定會直接使用預設值 (0時0分0秒)
newdate = datetime.date(2025,1,23)
print(newdate)
2025-01-23
newdatetime = datetime.datetime(2025,1,23,18,45,59)
print(newdatetime)
2025-01-23 18:45:59
newdatetime = datetime.datetime(2025,1,23)
print(newdatetime)
2025-01-23 00:00:00

Data Types 資料型態 - Recap

  • 文字 (text, string, character)
  • 數值 (numeric)
  • 布林變數 (Boolean, logic)
  • 日期 (date)

Conditional Execution (PY4E Ch3)

Operator 運算子

  • +加 / -減 / *乘 / /
  • >大於 / <小於 / ==等於 / !=不等於
  • and且 / or

+加 / -減 / *乘 / /除

int1 = 10
int2 = int(5)
print([int1, int2])
[10, 5]

Numeric Expressions

+

int1 + int2
15

-

int1 - int2
5

*

int1 * int2
50

/

int1 / int2
2.0

>大於 / <小於 / ==等於 / !=不等於

int1 = 10
int2 = int(5)
print([int1, int2])
[10, 5]

>大於

int1 > int2
True

<小於

int1 < int2
False

== 等於

int1 == int2
False

!=不等於

int1 != int2
True

and / or

and

10>5 and 10>1
True
10>5 and 1>5
False

or

10>5 or 10>1
True
10>5 or 1>5
True

Hands-on

  • 宣告一個文字 “15”
  • 宣告一個數字 10
  • 試著相加看看?是否能相加?錯誤訊息的意思是什麼?

if

x = 50
if x < 60:
    print('Slow')
if x > 80:
    print('Great')

#decrease to indicate end of block
print('Learner') 
Slow
Learner

if & else if (elif)

x = 50
if x < 60:
    print('Slow')
elif x > 80:
    print('Great')

print('Learner')
Slow
Learner

if & if vs. if & else if (elif)

x = 40
if x < 50:
    print('Super Slow')
elif x < 60:
    print('Slow')

print('Learner')
Super Slow
Learner

x = 40
if x < 50:
    print('Super Slow')
if x < 60:
    print('Slow')

print('Learner')
Super Slow
Slow
Learner

if & else

x = 4
if x > 2 :
    print('Bigger')
else :
    print('Not bigger')

print('All Done')
Bigger
All Done
x = 1
if x > 2 :
    print('Bigger')
else :
    print('Not bigger')

print('All Done')
Not bigger
All Done

try except

  • You surround a dangerous section of code with try and except

    • If the code in the try works - the except is skipped

    • If the code in the try fails - it jumps to the except section

try except

astr = 'Bob'
try:
    print('Hello')
    istr = int(astr)
    print('There')
except:
    istr = -1

print('Done', istr)
Hello
Done -1
astr = '123'
try:
    print('Hello')
    istr = int(astr)
    print('There')
except:
    istr = -1

print('Done', istr)
Hello
There
Done 123

Hands-on

Write a program to convert score to the grade and print the grade according to the following criteria:

  • >90: A

  • >80 and <=90: B

  • >=60 and <=80: C

  • <60: D

Assign 76 to variable score, check the output

Conditional Execution - Recap

  • Operator 運算子
    • + / - / * / /
    • > / < / == / !=
    • and / or
  • if
  • if & elif & else
  • try except

Function (PY4E Ch4)

Function

Stored and reused steps!

  • Built-in functions
    • print('123'), int('123'), input()
  • Functions from libraries
    • datetime.date(2025,1,23), from datetime library
  • Self-define functions

Function 函數使用

  • Function_name(Argument)
    • print(variable or “value”)
var1 = "test"
print(var1)
test
  • function_name(Argument 1,Argument 2,…)
    • 多個參數用,分隔

Function Definition 設計函數

We define a function using the def reserved word

def function_name(arguments):
  statement 1
  statement 2
  ...

Function Definition 設計函數

def grade(score):
  if score>90:
    print("A")
  elif score>80:
    print("B")
  elif score>=60:
    print("C")
  else:
    print("D")
this_exam = 80
grade(this_exam)
C

Function return value

def grade_ret(score):
  return_grade=""
  if score>90:
    return_grade="A"
  elif score>80:
    return_grade="B"
  elif score>=60:
    return_grade="C"
  else:
    return_grade="D"
  return return_grade
this_exam = 85
r_grade = grade_ret(this_exam)
print(r_grade)
B

Hands-on

Rewrite your pay computation with time-and-a-half for overtime and create a function called computepay which takes two parameters ( hours and rate).

Enter Hours: 45

Enter Rate: 10

Pay: 475.0 (475 = 40 * 10 + 5 * 15)

Function - Recap

  • Function_name(Argument)
  • def function name(arguments):
def function_name(arguments):
  statement 1
  statement 2
  ...

Iteration (PY4E Ch5)

Repeated Steps

  • Loops (repeated steps) have iteration variables that change each time through a loop.
    • Often these iteration variables go through a sequence of numbers.

while

n = 5
while n > 0 :
    print(n)
    n = n - 1
print('Blastoff!')
print(n)
5
4
3
2
1
Blastoff!
0

for loop

for i in [5, 4, 3, 2, 1]:
    print(i)
print('Blastoff!')
5
4
3
2
1
Blastoff!

break

The break statement ends the current loop and jumps to the statement immediately following the loop

i = 0
while i < 5:
    if i == 3:
        break
        # Exit the loop when i is 3
    print(i)
    i += 1
0
1
2

print(0)

print(1)

print(2)

break!

continue

The continue statement ends the current iteration and jumps to the top of the loop and starts the next iteration

for i in range(5):
    if i == 3:
        continue  
        # Skip the rest of the code for i = 3
    print(i)
0
1
2
4

print(0)

print(1)

print(2)

continue!

print(4)

print(5)

Hands-on

Print the following pattern

1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5

Iteration - Recap

  • while
  • for
  • break
  • continue

References

Questions?