Python面向物件作業
1、作業1
"""
作業1
玩個特別無聊的游戲,猜數字,
玩家輸入一個數字與
計算機隨機生成的數字作對比
當兩個值相等時,則說明用戶猜對了
注意:外部不能獲取到計算機隨機生成的值
"""
import random
class GuessNum:
def get_num(self):
n = random.randint(1, 100)
num = int(input("請輸入一個(1-100)之間的數字猜字:"))
if num == n:
print(f"恭喜你猜對了,是:{n}")
else:
while num != n:
if num > n:
print(f"數大了,應該是{n}")
num = int(input("請重新輸入:"))
else:
print(f"數小了,應該是{n}")
num = int(input("請重新輸入:"))
if num == n:
print(f"恭喜你猜對了,是:{n}")
print("游戲結束")
s = GuessNum()
s.get_num()
作業1優化后代碼
import random
class GuessNum(object):
def __init__(self):
self.__rand = random.randint(1, 10)
print(self.__rand)
def guess_num(self):
num = int(input("請輸入1-10的數字:"))
while True:
if num == self.__rand:
print(f"恭喜你猜對了!他是:{self.__rand}")
break
else:
print("輸入錯誤,請從新輸入!")
num = int(input("請輸入1-10的數字:"))
n = GuessNum()
n.guess_num()
優化前代碼不像是個類的基本方法,都可以不用類實作,優化后可以很清楚每個方法的作用
思考:輸入一個數之后,判斷這個數是在這組連續數中前一半還是后一半,每次進行對半判斷,直到找到最終結果,
2、作業2
"""
作業2
創建一個煎餅類 呼叫烹飪時長的方法累計煎餅狀態
如果煎的時間在0-3之間則狀態為生的
如果煎的時間在3-5之間則狀態為半生不熟的
如果煎的時間在5-8之間則狀態為全熟的
當時間超過8分鐘狀態焦了
并且還可以給煎餅添加作料
比如大蔥(hhh),大蒜(hhh)?,烤腸等等
"""
import time
class Cookies:
def __init__(self, minutes): # 定義初始方法
self.cookieTime = minutes
self.State_cooking = ""
def cooking_time(self): # 定義不同烹飪時間取值的方法
if self.cookieTime >= 0 and self.cookieTime < 3:
self.State_cooking = "生的"
elif self.cookieTime >= 3 and self.cookieTime < 5:
self.State_cooking = "半生不熟"
elif self.cookieTime >= 5 and self.cookieTime < 8:
self.State_cooking = "全熟"
elif self.cookieTime >= 8:
self.State_cooking = "糊了"
else:
print("時間錯誤")
return self.State_cooking
minutes = int(time.strftime('%M', time.localtime())[1]) # 呼叫分鐘的個位數
print(minutes)
c = Cookies(minutes) # 實體化Cookies
print(c.cooking_time())
還是沒搞明白怎么加調料、肉什么的,后期逐步完善
作業2優化后代碼:
class Cookies(object):
def __init__(self): # 定義初始方法
self.state_cooking = "生的"
self.cookieTime = 0
self.condiment = [] # 定義串列接收調味品
def __str__(self):
return f"煎餅的狀態:{self.state_cooking},煎餅的時長:{self.cookieTime}分鐘,煎餅的調味品:{self.condiment}"
def cook_condiment(self, food): # 添加調味品用self.condiment接收
self.condiment.append(food)
def cooking_time(self, cookingtime): # 定義不同烹飪時間取值的方法
self.cookieTime += cookingtime
if self.cookieTime >= 0 and self.cookieTime < 3:
self.state_cooking = "生的"
elif self.cookieTime >= 3 and self.cookieTime < 5:
self.state_cooking = "半生不熟"
elif self.cookieTime >= 5 and self.cookieTime < 8:
self.state_cooking = "全熟"
elif self.cookieTime >= 8:
self.state_cooking = "糊了"
c = Cookies() # 實體化Cookies
m = int(input("請輸入分鐘數:"))
cond = input("請加入需要的作料:")
c.cooking_time(m)
c.cook_condiment(cond)
print(c)
請輸入分鐘數:7
請加入需要的作料:牛板筋,青菜,王中王
煎餅的狀態:全熟,煎餅的時長:7分鐘,煎餅的調味品:['牛板筋,青菜,王中王']
作業2優化前,使用了時間作為烹飪時間從0-9分鐘為一個回圈,優點不需要人工干預,每到一個時間獲取分鐘的個位數,進行判斷,適合個位數,但是2位數的分鐘并不適合,以后需要在優化,優化后代碼,直接了當,查看烹飪多長時間可以達到什么效果,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/248510.html
標籤:其他
上一篇:冒泡排序和插入排序傻傻分不清
