简体   繁体   中英

input for def in if statement trouble

When i start this code i want it to restart def start() inside my if part and make it so i can input 1 again and itll post it again but that doesnt work. I really dont know why and i would appreciate the help. I need this answered fairly quickly so i can finish my assignment. If it helps im using python in visual studio 2017.

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")

You could use a while loop. If you really want to try to figure the assignment out by yourself, stop reading now, otherwise:

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")

The indented block after while gets executed as long as the expression choice=="1" evaluates to True .

  1. The return value of function start is assigned to the variable choice (right after your function defintion).
  2. If the expression choice=="1" evaluates to False (anything other than 1 was entered by the user), the block under while loop won't get executed and the program prints "nope".
  3. If the expression choice=="1" evalutes to True (1 was entered by the user), the block under the while loop will be executed (print, and assign the return value of function start to the variable choice again).
  4. The expression after the while will be evaluated again.

You'll want to wrap the rest of the logic in a function and call it at the end again instead of 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM