亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

有沒有辦法使此代碼更簡單?我覺得應該有,但我對Python很陌生

有沒有辦法使此代碼更簡單?我覺得應該有,但我對Python很陌生

森欄 2022-08-02 10:49:25
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個贊

我建議進行一些修改。

  1. 使用內聯條件語句 <expression1> if <condition> else <expression2>

  2. 使用字符串格式"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()

由于 您的代碼與 和 類似,因此還可以使用函數來簡化代碼。eatday


查看完整回答
反對 回復 2022-08-02
  • 1 回答
  • 0 關注
  • 84 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號