Skip to content

決策和迴圈

使用決策和迴圈進行流程控制

品牌英文大小寫

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# 品牌英文大小寫

brand_name = input("輸入品牌英文名字: ")

if brand_name.upper() == brand_name:
    print("全部大寫")
elif brand_name.lower() == brand_name:
    print("全部小寫")
else:
    print('大寫小寫都有')

串列內容比較

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# 串列內容比較

alist = [1, 2, 3]
blist = ["1", "2", "3"]
print('alist:', alist)
print('blist:', blist)
if alist == blist:
    print("兩個串列內容相同")
else:
    print("兩個串列內容不同")

成績平均積點

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
# 成績平均積點

# 分數範圍    成績等第
# 90 ~ 100    A
# 80 ~  89    B
# 70 ~  79    C
# 60 ~  69    D
#  0 ~  59    F

score = int(input("輸入分數: "))
if score >= 90:
    grade = 'A'
elif score >= 80:
    grade = 'B'
elif score >= 70:
    grade = 'C'
elif score >= 60:
    grade = 'D'
else:
    grade = 'F'
print("成績等第:", grade)

調整分數

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# 調整分數

# 下列是調整分數的程式:
# 若 score 輸入 75 且 rank 輸入 5
# score 將調整為幾分?

score = int(input('score: '))
rank = int(input('rank: '))

if score > 80 and rank >= 3:
    score += 10
if score > 70 and rank > 3:
    score += 5
else:
    score -= 5

print(score)

整數的位數

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# 整數的位數

N = int(input("輸入 1 個整數: "))
digits = 0
if N > 0:
    if N < 10:
        digits = 1
    elif N < 100:
        digits = 2
    elif N < 1000:
        digits = 3
    if digits == 0:
        print("大於 3 位數")
    else:
        print(f"{digits} 位數")
elif N <= 0:
    print("不判斷小於等於 0 的整數")

租車費用計算

 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
# 租車費用計算

"""
程式設計必須符合以下條件:
* 每天費用 100 塊
* 晚上 11 點以後歸還,加收一天費用
* 起租日是星期日,可享 10% 的折扣
* 起租日是星期三,可享 20% 的折扣
"""

rate = 100
is_ontime = input("是否在晚上 11 點以前歸還(輸入 y 或 n): ")
days = int(input("租用天數: "))
day_from = input("星期幾開始租(輸入星期的英文): ").capitalize()

# 是否加收一天費用
if is_ontime == "n":
    days += 1
# 起租日是否享有折扣
if day_from == "Sunday":
    total = days * rate * 0.9
elif day_from == "Wednesday":
    total = days * rate * 0.8
else:
    total = days * rate
print(f"租車費用: ${int(total)}")

比較兩個數字

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
# 比較兩個數字

01 n1 = eval(input("輸入第1個數: "))
02 n2 = eval(input("輸入第2個數: "))
03 if n1 = n2:
04     print("數字1等於數字2")
05 if n1 <= n2:
06     print("數字1比數字2小")
07 if n1 > n2:
08     print("數字1比數字2大")
09 if n1 <> n2:
10     print("數字1不等於數字2")
"""
# 針對下列敘述,正確的選 Yes,否則選 No
A. 03 行:不正確的比較運算
B. 06 行:只有 n1 小於 n2 時才會輸出
C. 08 行:只有 n1 大於 n2 時才會輸出
D. 09 行:不正確的比較運算
"""

無此房型

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# 無此房型

room_list = {
    1: '單人房',
    2: '雙人房',
    4: '家庭房'
}

room_type = input('房型編號: ')
if room_type in room_list:
    print(room_list[room_type])
else:
    print('無此房型')

本週早餐優惠

 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
# 本週早餐優惠

import datetime
daily_specials = ("燒肉蛋餅", "鮪魚蛋餅", "燒肉三明治", "鮪魚三明治")
weekend_specials = ("豬排漢堡", "雞排漢堡", "牛肉漢堡")
# 取得今天日期
now = datetime.datetime.now()
# 調整測試日期
now += datetime.timedelta(days=1)
print(now)
print(now.strftime("%A")) # 星期全寫
print(now.strftime("%B")) # 月份全寫
print(now.strftime("%W")) # 當年週次
print(now.strftime("%Y")) # 年份4碼
weekday = now.strftime("%A")
print("本週早餐優惠,今天供應:")
if weekday in ("Friday", "Saturday", "Sunday"):
    print("==週末優惠==")
    print(*weekend_specials)
else:
    print("==平日優惠==")
    print(*daily_specials)
print(f"星期代碼 {now.weekday()}")
days_left = 6 - now.weekday()
print(f"本週優惠剩 {days_left} 天")

星號字母 E

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# 星號字母 E

letterE = ""
for ri in range(1, 6):
    for ci in range(1, 5):
        if ri % 2 == 1:
            letterE += "*"
        elif ci == 1:
            letterE += "*"
    letterE += "\n"
print(letterE)

員工加薪

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# 員工加薪

salary_list = [
    760000, 580000, 460000, 487000,
    810000, 385000, 412000, 660000,
]
# 以 for 迴圈逐一讀取所有薪資
for i in range(len(salary_list)):
    if salary_list[i] >= 600000:
        continue
    # 低於 60 萬的薪資,加薪 6%
    salary_list[i] = (salary_list[i] * 1.06)
    print(f'員工編號: {i+1}  加薪後的薪資: {salary_list[i]}')

猜數字遊戲

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 猜數字遊戲

from random import randint
# 電腦從 1 到 10 選一個數字,存到 target
target = randint(1, 10)
# 設定最多猜測次數,存到 limit
limit = 3
# 猜測的次數
i = 1

print(f"從 1 到 10 猜一個數字,最多能猜 {limit} 次")
while i <= limit:
    guess = int(input("輸入數字: "))
    if guess > target:
        print("比答案大!")
    elif guess < target:
        print("比答案小!")
    else:
        print("恭喜猜對!")
        break
    i += 1
    print()

檢查學號

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# 檢查學號

student_id = "nobody"
while student_id != "":
    is_valid = False
    student_id = input("輸入學號(ddd-dd-dd): ")
    sid = student_id.split('-')
    if len(sid) == 3:
        p1 = sid[0]
        p2 = sid[1]
        p3 = sid[2]
        if len(p1) == 3 and len(p2) == 2 and len(p3) == 2:
            if p1.isdigit() and p2.isdigit() and p3.isdigit():
                is_valid = True
        print(student_id, is_valid)

搜尋目標數

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
# 搜尋目標數

import random

nlist = list(range(10))
print(nlist)
random.shuffle(nlist)
print(nlist)

i = 0
while (i < 10):
    print(nlist[i])
    if nlist[i] == 5:
        break
    else:
        i += 1

質數判斷★★

1
2
3
4
5
6
# 質數判斷★★

"""
★ 輸入 1 個整數,存到變數 N,輸出 N 是否為質數
★ 輸入 2 個整數,存到變數 A 和 B,輸出 A 到 B 之間的所有質數
"""

尋找數字★★

1
2
3
4
5
6
# 尋找數字★★

"""
★ 將 10 個隨機整數放到串列,輸出最大值和最小值
★ 輸入 1 個整數 N,從隨機整數串列中找出比 N 還要大且最接近 N 的數
"""