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
提交
取消