Skip to content

文件和結構

程式碼文件和結構

註解符號

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# 註解符號

// 回傳前十名
def get_top10():
    return top10

/* 回傳前十名 */
def get_top10():
    return top10

' 回傳前十名
def get_top10():
    return top10

# 回傳前十名
def get_top10():
    return top10

註解位置

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# 註解位置

01 # rectangle_area(x, y) 矩形面積函式
02 # x 表示「長」
03 # y 表示「寬」
04 # 回傳 x * y 的值
05 def rectangle_area(x, y):
06     comment = "回傳 x * y 的值"
07     return x * y # x * y

"""
# 針對下列敘述,正確的選 Yes,否則選 No
A. 01 到 04 行在語法檢查時將被忽略
B. 02 和 03 行中的井字符號(#)非必填
C. 06 行的字串將被視為注釋(註解)
D. 07 行包含內嵌注釋(註解)
"""

設定與輸出文件字串

1
2
3
4
5
6
7
# 設定與輸出文件字串

def sum_two_numbers(number1, number2):
    """回傳兩個數值相加的和"""
    return number1 + number2

print(sum_two_numbers.__doc__)

大薯的熱量★

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# 大薯的熱量★

# 下一行須完成第一個函式宣告

    name = input("請輸入你的名字: ")
    return name
# 下一行須完成第二個函式宣告

    calories = ords * cals
    return calories
orders = int(input("請輸入本週吃的大薯份數: "))
fries_cals = 543
foodie = get_name()
calories = get_calories(orders, fries_cals)
print(foodie, "本週光是吃大薯就吃到了", calories, "大卡")

加購遊戲點數★

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
# 加購遊戲點數★

"""
函式設計必須符合以下條件:
* 函式名稱為 add_points
* 函式接收兩個參數:目前點數和加購點數
* 函式將加購點數增加到目前點數
* 函式回傳新點數
"""

# 下一行須完成函式宣告

    current += point
    # 下一行須回傳目前累積點數

print(add_points(25, 100))

零與正負整數

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
# 零與正負整數

# n 是負數,回傳 "n 是負數"
# n 不是負數,在條件不成立的情況下,於下一層繼續判斷
# 承上,n 大於 0,則回傳 "n 是負數",否則回傳 "n 是零"

def check_integer(n):
    if n < 0:
        result = f"{n} 是負數"
    else:
        if n > 0:
            result = f"{n} 是正數"
        else:
            result = f"{n} 是零"
    return result

print(check_integer(7))
print(check_integer(0))
print(check_integer(-7))

除法運算元

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# 除法運算元

def divide(numerator=None, denominator=None):
    if numerator is None or denominator is None:
        return '缺少分子或分母'
    elif denominator == 0:
        return '分母不得為 0'
    return numerator / denominator


print(divide())
print(divide(10))
print(divide(10, 0))
print(divide(10, 20))

捷運折扣計算

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
# 捷運折扣計算

# 捷運折扣計算函式
# 12 歲以下小孩和 65 歲以上老人可享半價

def get_discount(kid, elder):
    discount = 0.5
    if not (kid or elder):
        discount = 0
    return discount


kid = elder = False
age = int(input('輸入年齡: '))
price = int(input('輸入票價: '))
if age <= 12:
    kid = True
elif age >= 65:
    elder = True
print(price * (1 - get_discount(kid, elder)))

電影依年齡分級

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 電影依年齡分級

# 年齡未知,輸出字串訊息 "未知"
# 12 歲以下,輸出字串訊息 "普通級"
# 13 歲以上,低於 18 歲,輸出字串訊息 "輔導級"
# 18 歲以上,輸出字串訊息 "限制級"

def get_rating(age):
    rating = ""
    if age == None:
        rating = "未知"
    elif age < 13:
        rating = "普通級"
    elif age < 18:
        rating = "輔導級"
    else:
        rating = "限制級"
    return rating

print(get_rating(18))
print(get_rating(13))
print(get_rating(12))
print(get_rating(None))

電影票價計費

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 電影票價計費

# 18 歲以上,不是學生 -> 190 元
# 6 歲以上,低於 18 歲,不是學生 -> 140 元
# 6 歲以上的學生 -> 80 元
# 低於 6 歲 -> 免費

def ticket_fee(age, is_student):
    fee = 0
    if age >= 6 and is_student == True:
        fee = 80
    if age >= 6 and is_student == False:
        if age < 18:
            fee = 140
        else:
            fee = 190
    return fee

print(ticket_fee(5, False))
print(ticket_fee(6, True))
print(ticket_fee(17, False))
print(ticket_fee(18, False))

九九乘法表

1
2
3
4
5
6
7
8
9
# 九九乘法表

def print_multiplication_table():
    for ri in range(1, 10):
        for ci in range(1, 10):
            print(ci * ri, end=' ')
        print()

print_multiplication_table()

字串字元倒置

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# 字串字元倒置

def reverse_string(astr):
    result = ''
    for i in range(len(astr)-1, -1, -1):
        result += astr[i]
    return result

str1 = reverse_string('apple')
print(str1)
str1 = reverse_string(str1)
print(str1)

str2 = reverse_string('12345')
print(str2)
str2 = reverse_string(str2)
print(str2)

增加庫存★

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 增加庫存★

"""
程式必須符合以下條件:
* 如果沒有為變數 increment 指定值,則 increment 等於 1
* 如果變數 isplus 是 True,那麼 increment 必須加倍

# 程式碼如下:
01 def add_inventory(inventory, isplus, increment):
02     if isplus == True:
03         increment = increment * 2
04     inventory = inventory + increment
05     return inventory
06 increment = 3
07 inventory = 24
08 new_inventory = add_inventory(inventory, True, increment)

# 針對下列敘述,正確的選 Yes,否則選 No
A. 為了符合要求必須將 01 行更改為:
    def add_inventory(inventory, isplus, increment=1):
B. 如果某個參數定義預設值,其右側的任何參數也必須定義預設值
C. 如果只用兩個參數呼叫函式, 則第三個參數的值將為 None
D. 03 行的結果會改變在 06 行中變數 increment 的值
"""

計算各種薪資★

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
# 計算各種薪資★

def get_pay(salary=0, hours=40, h_rate=25, quantity=0, q_rate=0):
    wage = 0
    if quantity > 0:
        return quantity * q_rate
    if salary > 0:
        pass
    if hours > 40:
        wage = (hours - 40) * (1.5 * h_rate)
        return wage + (40 * h_rate)
    else:
        wage = hours * h_rate
        return wage
"""
# 針對下列敘述,正確的選 Yes,否則選 No
A. 呼叫 get_pay() 函式會發生錯誤
B. get_pay(salary=51888) 不會回傳任何值
C. get_pay(quantity=600, q_rate=5) 回傳值為 3000
"""

計算指數★

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
# 計算指數★

def power(n, p):
    """計算並回傳 n 的 p 次方"""
    return n**p

print(power.__doc__)
n = input("n: ")
p = input("p: ")
result = power(n, p)
print(f"{n}{p} 次方 = {result}")

"""
# 針對下列敘述,正確的選 Yes,否則選 No
A. return n**p 造成執行錯誤
B. print(f"{n}的{p}次方 = {result}") 造成執行錯誤
C. 要修正程式的話,兩個 input() 呼叫,外層應該加上 eval() 函式
"""

依年資分配宴會室★

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# 依年資分配宴會室★

def assign_room(employee, year):
    """依年資分配宴會室"""
    if year == 1:
        room = "102"
    elif year == 2:
        room = "106"
    elif year == 3:
        room = "108"
    elif year == 4:
        room = "112"
    elif year == 5:
        room = "116"
    else:
        room = "118"
    print(f"{employee} 請到 {room} 室")
    print()

name1 = input("姓名: ")
year1 = 0
while year1 not in (1, 2, 3, 4, 5, 6):
    year1 = int(input("來公司滿幾年? "))
assign_room(name1, year=year1)

name2 = input("姓名: ")
year2 = 0
while year2 not in (1, 2, 3, 4, 5, 6):
    year2 = int(input("來公司滿幾年? "))
assign_room(name, year)

assign_room("張三", 3)
assign_room(year=6, name="李四")
"""
# 針對下列敘述,正確的選 Yes,否則選 No
A. assign_room(name1, year=year1) 呼叫有錯
B. assign_room(name, year) 呼叫有錯
C. assign_room("張三", 3) 呼叫有錯
D. assign_room(year=6, name="李四") 呼叫有錯
"""

購買機器寵物★

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# 購買機器寵物★

def robot_pet_store(category, color, pet_type=None):
    "輸出機器寵物資訊"
    category_dict = {"dog":"狗", "cat":"貓", "bird":"鳥"}
    color_dict = {"black":"黑", "white":"白", "red":"紅", "yellow":"黃"}
    pet_type_dict = {"home":"居家型", "race":"競賽型"}

    category = category_dict[category]
    color = color_dict[color]
    print(f"你選的是機器{category}")
    if pet_type == None:
        print(f"你選的機器{category}{color}色的")
    else:
        pet_type = pet_type_dict[pet_type]
        print(f"你選的機器{category}{color}色的{pet_type}")

# 輸入設定
category = input("輸入機器寵物種類英文代碼: dog(狗) cat(貓) bird(鳥) > ")
color = input("輸入顏色代碼: black(黑) white(白) red(紅) yellow(黃) > ")
if category == "dog" or category == "cat":
    pet_type = input("輸入型別代碼: home(居家型) race(競賽型) > ")
    robot_pet_store(category, color, pet_type)
else:
    robot_pet_store(category, color)
# 直接設定
robot_pet_store(pet_type="home", color="black", category="cat")
robot_pet_store("bird", color="white")

"""
# 針對下列敘述,正確的選 Yes,否則選 No
A. robot_pet_store() 函式有回傳值
B. robot_pet_store(category, color, pet_type) 呼叫無效
C. robot_pet_store(category, color) 呼叫有錯
D. robot_pet_store(pet_type="home", color="black", category="cat") 呼叫無效
E. robot_pet_store("bird", color="white") 呼叫有錯
"""