猿问

有没有办法使此代码更简单?我觉得应该有,但我对Python很陌生

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 语句。代码似乎运行良好,但我希望它尽可能不那么笨拙。谢谢!


森栏
浏览 71回答 1
1回答

白猪掌柜的

我建议进行一些修改。使用内联条件语句&nbsp;<expression1> if <condition> else <expression2>使用字符串格式"Today is {}".format(date)所以你可以写s&nbsp;=&nbsp;"eat"&nbsp;if&nbsp;eat.upper()&nbsp;==&nbsp;"Y"&nbsp;else&nbsp;"skip"&nbsp;if&nbsp;eat.upper()&nbsp;==&nbsp;"N"&nbsp;else&nbsp;"" print("I&nbsp;predict&nbsp;you&nbsp;will&nbsp;{}&nbsp;breakfast".format(s))请务必先检查“Y”或“N”,否则代码将失败。eat.upper()由于 您的代码与 和 类似,因此还可以使用函数来简化代码。eatday
随时随地看视频慕课网APP

相关分类

Python
我要回答