1. 程式人生 > >[python 作業] [第五週]

[python 作業] [第五週]

9-1 餐館:建立一個名為 Restaurant 的類,其方法init()設定兩個屬性:
restaurant_name 和 cuisine_type。建立一個名為 describe_restaurant()的方法和一個
名為 open_restaurant()的方法,其中前者列印前述兩項資訊,而後者列印一條訊息,
指出餐館正在營業。
根據這個類建立一個名為 restaurant 的例項,分別列印其兩個屬性,再呼叫前述
兩個方法。

程式碼:

class Restaurant():
    def __init__(self, restaurant_name, cuisine_type)
:
self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type def describe_restaurant(self): print("Restaurant Nmae: " + self.restaurant_name) print("Cuisine Type: " + self.cuisine_type) def open_restaurant(self): print("Restaurant is open, welconme!"
) my_res = Restaurant("Great Fire", "HotPot") print(my_res.restaurant_name) print(my_res.cuisine_type, end='\n\n') my_res.describe_restaurant() print() my_res.open_restaurant()

測試結果:

Great Fire
HotPot

Restaurant Nmae: Great Fire
Cuisine Type: HotPot

Restaurant is open, welconme!

9-2 三家餐館:根據你為完成練習 9-1 而編寫的類建立三個例項,並對每個例項調
用方法 describe_restaurant()。
and
9-10 匯入 Restaurant 類:將最新的 Restaurant 類儲存在一個模組中。在另一個文
件中,匯入 Restaurant 類,建立一個 Restaurant 例項,並呼叫 Restaurant 的一個方法,
以確認 import 語句正確無誤。

程式碼:

from Restaurant import Restaurant

res_a = Restaurant("Great Fire", "HotPot")
res_b = Restaurant("YangXiaoXian", "Desert")
res_c = Restaurant("MacDonald", "Fast food")
res_a.describe_restaurant()
print()
res_b.describe_restaurant()
print()
res_c.describe_restaurant()
print()

測試結果:

Restaurant Nmae: Great Fire
Cuisine Type: HotPot

Restaurant Nmae: YangXiaoXian
Cuisine Type: Desert

Restaurant Nmae: MacDonald
Cuisine Type: Fast food

9-4 就餐人數:在為完成練習 9-1 而編寫的程式中,新增一個名為 number_served
的屬性,並將其預設值設定為 0。根據這個類建立一個名為 restaurant 的例項;列印有
多少人在這家餐館就餐過,然後修改這個值並再次列印它。
新增一個名為 set_number_served()的方法,它讓你能夠設定就餐人數。呼叫這個
方法並向它傳遞一個值,然後再次列印這個值。
新增一個名為 increment_number_served()的方法,它讓你能夠將就餐人數遞增。
呼叫這個方法並向它傳遞一個這樣的值:你認為這家餐館每天可能接待的就餐人數。

程式碼:

class Restaurant():
    def __init__(self, restaurant_name, cuisine_type, number_served=0):
        self.restaurant_name = restaurant_name
        self.cuisine_type = cuisine_type
        self.number_served = number_served

    def describe_restaurant(self):
        print("Restaurant Nmae: " + self.restaurant_name)
        print("Cuisine Type: " + self.cuisine_type)

    def open_restaurant(self):
        print("Restaurant is open, welconme!")

    def set_number_served(self, num):
        self.number_served = num
        return self.number_served

    def increment_number_served(self, add):
        self.number_served += add
        return self.number_served


my_res =  Restaurant("Great Fire", "HotPot", 2)
print('Number served: ' + str(my_res.number_served))
my_res.increment_number_served(5)
print('Number served(after update): ' + str(my_res.number_served))
my_res.increment_number_served(200)
print('Number served(a day): ' + str(my_res.number_served))

測試結果:

Number served: 2
Number served(after update): 7
Number served(a day): 207

9-6 冰淇淋小店:冰淇淋小店是一種特殊的餐館。編寫一個名為 IceCreamStand 的
類,讓它繼承你為完成練習 9-1 或練習 9-4 而編寫的 Restaurant 類。這兩個版本的
Restaurant 類都可以,挑選你更喜歡的那個即可。新增一個名為 flavors 的屬性,用於
儲存一個由各種口味的冰淇淋組成的列表。編寫一個顯示這些冰淇淋的方法。建立一個
IceCreamStand 例項,並呼叫這個方法。

程式碼:

from Restaurant import Restaurant

class IceCreamStand(Restaurant):
    def __init__(self, restaurant_name, cuisine_type, number_served=0, flavors=['milk', 'matcha', 'durian', 'chocolate']):
        super().__init__(restaurant_name, cuisine_type, number_served=0)
        self.flavors = flavors

    def show_flavors(self):
        print("All the Ice Cream flavors we can offer:\n", self.flavors)

my_res = IceCreamStand('Pretty Ice', 'Ice Cream', 50)
my_res.show_flavors()

測試結果:

All the Ice Cream flavors we can offer:
 ['milk', 'matcha', 'durian', 'chocolate']

10-1 Python 學習筆記:在文字編輯器中新建一個檔案,寫幾句話來總結一下你至
此學到的 Python 知識,其中每一行都以“In Python you can”打頭。將這個檔案命名為
learning_python.txt,並將其儲存到為完成本章練習而編寫的程式所在的目錄中。編寫一
個程式,它讀取這個檔案,並將你所寫的內容列印三次:第一次列印時讀取整個檔案;
第二次列印時遍歷檔案物件;第三次列印時將各行儲存在一個列表中,再在 with 程式碼
塊外列印它們。

程式碼:

with open ('learning_python.txt', 'r') as lp:
    print(lp.read(), end='\n\n')

with open ('learning_python.txt', 'r') as lp:
    for line in lp:
        print(line, end='')
    print('\n')

with open ('learning_python.txt', 'r') as lp:
    ls = []
    for line in lp:
        ls.append(line)
    for x in ls:
        print(x, end='')

測試結果:

In Python you can use 'range()' to generate lists quickly.
In Python you can use 'strip()' to get rip of blank spaces.
In Pyhont you can use 'type()' to know the type of the variable.

In Python you can use 'range()' to generate lists quickly.
In Python you can use 'strip()' to get rip of blank spaces.
In Pyhont you can use 'type()' to know the type of the variable.

In Python you can use 'range()' to generate lists quickly.
In Python you can use 'strip()' to get rip of blank spaces.
In Pyhont you can use 'type()' to know the type of the variable.

10-4 訪客名單:編寫一個 while 迴圈,提示使用者輸入其名字。使用者輸入其名字後,
在螢幕上列印一句問候語,並將一條訪問記錄新增到檔案 guest_book.txt 中。確保這個
檔案中的每條記錄都獨佔一行。

程式碼:

while True:
    name = input('Please input your name(q to quit): ')
    if name.lower() == 'q':
        break
    else:
        with open('guest_book.txt', 'a') as gb:
            gb.write(name+'\n')

輸入:

Please input your name(q to quit): Andy
Please input your name(q to quit): Bill
Please input your name(q to quit): Cary
Please input your name(q to quit): Denny
Please input your name(q to quit): Edward
Please input your name(q to quit): q

輸出(guest_book.txt):

Andy
Bill
Cary
Denny
Edward

10-6 加法運算:提示使用者提供數值輸入時,常出現的一個問題是,使用者提供的是
文字而不是數字。在這種情況下,當你嘗試將輸入轉換為整數時,將引發 TypeError 異
常。編寫一個程式,提示使用者輸入兩個數字,再將它們相加並列印結果。在使用者輸入的
任何一個值不是數字時都捕獲 TypeError 異常,並列印一條友好的錯誤訊息。對你編寫
的程式進行測試:先輸入兩個數字,再輸入一些文字而不是數字。

程式碼:

a = int(input('Please input num 1: '))
b = input('Please input num 2: ')
try:
    c = a + b
except TypeError:
    c = int
print('num c = ', c)

測試結果:

Please input num 1: 1
Please input num 2: 2
num c =  3

10-11 喜歡的數字:編寫一個程式,提示使用者輸入他喜歡的數字,並使用
json.dump()將這個數字儲存到檔案中。再編寫一個程式,從檔案中讀取這個值,並打
印訊息“I know your favorite number! It’s _.”。

程式碼1:

import json

favorite_num = input("What's your favorite number: ")

file_name = 'favorite_number.txt'
with open(file_name, 'w') as f_obj:
    json.dump(favorite_num, f_obj)

測試結果1:

What's your favorite number: 11

程式碼2:

import json

file_name = 'favorite_number.txt'

with open(file_name, 'r') as f_obj:
    temp = json.load(f_obj)
    print("I know your favorite number! It's " + temp)

測試結果2:

I know your favorite number! It's 11