1. 程式人生 > >(第四周)使用者輸入和while迴圈、函式

(第四周)使用者輸入和while迴圈、函式

使用者輸入和while迴圈

7-1 汽車租賃

car = input("Let me see if I can find you a Subaru\n")
print(car)

程式執行後顯示

Let me see if I can find you a Subaru
輸入“interesting”,打印出
interesting

7-2 餐館訂位

num = input("請問有多少人用餐?\n")
num = int(num)
if num <= 8:
    print("這裡有空位")
else :
    print("沒有足夠的空位")
執行程式分別輸入5 和9 ,結果不同
請問有多少人用餐?
5
這裡有空位
紅色為使用者輸入,下同
請問有多少人用餐?
9
沒有足夠的空位

7-3 10 的整數倍

num = input("請輸入一個數字\n")
num = int(num)
if num % 10 == 0:
    print(str(num) + "是10的整數倍")
else :
    print(str(num) + "不是10的整數倍")
執行程式碼分別輸入50和102,結果如下
請輸入一個數字
50
50是10的整數倍
請輸入一個數字
102
102不是10的整數倍

7-5 電影票

while True:
    x = input("請輸入你的年齡\n")
    x = int(x)
    if x < 0:
        print("輸入無效")
    elif x < 3:
        print("你可以免費觀看")
    elif x <= 12:
        print("你的票價為10美元")
    elif x > 12:
        print("你的票價為15美元")
   
執行程式輸入數字:
請輸入你的年齡
2
你可以免費觀看
請輸入你的年齡
5
你的票價為10美元
請輸入你的年齡
11
你的票價為10美元
請輸入你的年齡
13
你的票價為15美元
請輸入你的年齡

函式:

8-1 訊息

def display_message():
    print("我在這章學習了python的函式")

display_message()
執行程式後打印出這句話:
我在這章學習了python的函式


8-9 魔術師:

def show_magicians(names):
    for name in names:
        print(name)
magician = ["Tom", "Jerry", "Mary"]
show_magicians(magician)
程式執行結果
Tom
Jerry
Mary
8-10 了不起的魔術師
def show_magicians(names):
    for name in names:
        print(name)

def make_great(names):
    for i in range(0, len(names)):
        names[i] = "the Great " + names[i]
    
magician = ["Tom", "Jerry", "Mary"]
show_magicians(magician)
make_great(magician)
show_magicians(magician)
執行程式後輸出:
Tom
Jerry
Mary
the Great Tom
the Great Jerry
the Great Mary

8-11 不變的魔術師

def show_magicians(names):
    for name in names:
        print(name)

def make_great(names):
    for i in range(0, len(names)):
        names[i] = "the Great " + names[i]
    return names
    
magician = ["Tom", "Jerry", "Mary"]
show_magicians(magician)
new_magician = make_great(magician[:])
print("Magicians in funtion make_great")
show_magicians(new_magician)
print("Magicians outside funtion make_great")
show_magicians(magician)
執行程式後
Tom
Jerry
Mary
Magicians in funtion make_great
the Great Tom
the Great Jerry
the Great Mary
Magicians outside funtion make_great
Tom
Jerry
Mary