如果语句有问题则输入def

时间:2017-11-15 22:48:01

标签: python

当我启动此代码时,我希望它在我的if部分内重新启动def start()并使之成为我可以再次输入1并且它会再次发布但不起作用。我真的不知道为什么,我会很感激帮助。我需要这个答案很快,所以我可以完成我的任务。如果它有助于我在Visual Studio 2017中使用python。

def start():
    print("\nWhat would you like to do?")
    print("1) Call out to someone")
    print("2) Stand up")
    print("3) Touch your head")
    print("4) Sleep\n")
    choice = input("Make your decision!: ")
    return choice

choice = start()

if choice=="1":
    print("You call out")
    print("No one came")
    print(start())


else:
   print("nope")

2 个答案:

答案 0 :(得分:3)

您可以使用while循环。如果你真的想亲自试图解决这个问题,请立即停止阅读,否则:

def start():
    print("\nWhat would you like to do?")
    print("1) Call out to someone")
    print("2) Stand up")
    print("3) Touch your head")
    print("4) Sleep\n")
    choice = input("Make your decision!: ")
    return choice

choice = start()

while choice=="1":
    print("You call out")
    print("No one came")
    choice = start()

print("nope")

只要表达式while计算为choice=="1"True执行后的缩进块。

  1. 函数start的返回值已分配给变量choice(在函数定义之后)。
  2. 如果表达式choice=="1"的计算结果为False(用户输入的除1之外的任何内容),则while循环下的块将不会执行并且程序打印“nope”。
  3. 如果表达式choice=="1"评估为True(用户输入了1),则执行while循环下的块(打印,并分配返回值)函数start的值再次变为choice
  4. 将再次评估while之后的表达式。

答案 1 :(得分:0)

您希望将其余逻辑包装在一个函数中并再次调用它而不是start()

def question():

    def start():
        print("\nWhat would you like to do?")
        print("1) Call out to someone")
        print("2) Stand up")
        print("3) Touch your head")
        print("4) Sleep\n")
        choice = input("Make your decision!: ")

        return choice

    choice = start()

    if str(choice) == "1":
        print("You call out")
        print("No one came")
        question()
    else:
        print("nope")

question()