1. 程式人生 > >Python課本第七章課後習題選做

Python課本第七章課後習題選做

7-1 汽車租賃 :編寫一個程式,詢問使用者要租賃什麼樣的汽車,並列印一條訊息,如 “Let me see if I can find you a Subaru” 。

car = input('What car are you looking for: ')
print('Let me see if I can find you a {}.'.format(car))
What car are you looking for: Benz
Let me see if I can find you a Benz.

7-3 10 的整數倍 :讓使用者輸入一個數字,並指出這個數字是否是 10 的整數倍。
num = input('Please input a number: ')
if int(num)%10 == 0:
    print('{} can be divisible by 10.'.format(num))
else:
    print('{} can not be divisible by 10.'.format(num))
Please input a number: 100
100 can be divisible by 10.

7-5 電影票 :有家電影院根據觀眾的年齡收取不同的票價:不到 3 歲的觀眾免費; 3~12 歲的觀眾為 10 美元;超過 12 歲的觀眾為 15 美元。請編寫一個迴圈,在其中詢問使用者的年齡,並指出其票價。

while True:
    age = int(input('Please input your age( 0 to quit ): '))
    if age == 0:
        break
    if age < 3:
        print('Free')
    elif age < 12:
        print('$10')
    else:
        print('$15')
Please input your age( 0 to quit ): 1
Free
Please input your age( 0 to quit ): 5
$10
Please input your age( 0 to quit ): 30
$15
Please input your age( 0 to quit ): 0

7-7 無限迴圈 :編寫一個沒完沒了的迴圈,並執行它(要結束該迴圈,可按 Ctrl +C ,也可關閉顯示輸出的視窗)。

while True:
    age = input('Please input your age: ')
Please input your age: 1
Please input your age: 2
Please input your age: 0
Please input your age: Traceback (most recent call last):
  File "blog.py", line 2, in <module>
    age = input('Please input your age: ')
KeyboardInterrupt

7-8 熟食店 :建立一個名為 sandwich_orders 的列表,在其中包含各種三明治的名字;再建立一個名為 finished_sandwiches 的空列表。遍歷列表 sandwich_orders ,對於其中的每種三明治,都列印一條訊息,如 I made your tuna sandwich ,並將其移到列表 finished_sandwiches 。所有三明治都製作好後,列印一條訊息,將這些三明治列出來。
sandwich_orders = [ 'bacon', 'egg', 'chicken' ]
finished_sandwiches = []

while sandwich_orders:
    current_sandwiches = sandwich_orders.pop()
    print('I made your {} sandwich.'.format(current_sandwiches))
    finished_sandwiches.append(current_sandwiches)

for sandwich in finished_sandwiches:
    print(sandwich)
I made your chicken sandwich.
I made your egg sandwich.
I made your bacon sandwich.
chicken
egg
bacon