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語句中重復多行代碼。有沒有辦法使 while 語句轉到上一行代碼并從那里運行它,而不是將相同的代碼重新輸入回 while 語句。代碼似乎運行良好,但我希望它盡可能不那么笨拙。謝謝!
1 回答

白豬掌柜的
TA貢獻1893條經驗 獲得超10個贊
我建議進行一些修改。
使用內聯條件語句
<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))
請務必先檢查“Y”或“N”,否則代碼將失敗。eat.upper()
由于 您的代碼與 和 類似,因此還可以使用函數來簡化代碼。eat
day
添加回答
舉報
0/150
提交
取消