def life(): print("You wake up") eat = input("are you hungry? Please Enter y or n.") if eat.upper() == "Y": print("I predict you will eat breakfast") elif eat.upper() == "N": print("I predict you will skip breakfast") while eat.upper() not in ("Y","N"): print("input not accepted") eat = input("are you hungry? Please Enter y or n.") if eat.upper() == "Y": print("I predict you will eat breakfast") elif eat.upper() == "N": print("I predict you will skip breakfast") print("You leave the house") day = input("is it cloudy? please enter y or n")life()我覺得沒有必要在while語(yǔ)句中重復(fù)多行代碼。有沒有辦法使 while 語(yǔ)句轉(zhuǎn)到上一行代碼并從那里運(yùn)行它,而不是將相同的代碼重新輸入回 while 語(yǔ)句。代碼似乎運(yùn)行良好,但我希望它盡可能不那么笨拙。謝謝!
1 回答
白豬掌柜的
TA貢獻(xiàn)1893條經(jīng)驗(yàn) 獲得超10個(gè)贊
我建議進(jìn)行一些修改。
使用內(nèi)聯(lián)條件語(yǔ)句
<expression1> if <condition> else <expression2>使用字符串格式
"Today is {}".format(date)
所以你可以寫
s = "eat" if eat.upper() == "Y" else "skip" if eat.upper() == "N" else ""
print("I predict you will {} breakfast".format(s))請(qǐng)務(wù)必先檢查“Y”或“N”,否則代碼將失敗。eat.upper()
由于 您的代碼與 和 類似,因此還可以使用函數(shù)來(lái)簡(jiǎn)化代碼。eatday
添加回答
舉報(bào)
0/150
提交
取消
