简体   繁体   中英

How to repeat code from a certian point when user input is incorrect

I'm new to Python so I'm not really sure on the basics so I understand this is probably a stupid question.

I'm making code where the user inputs a number, and if they get it wrong, I want the code to restart and ask them to guess again till it's right. How do I do this?

print("Let's play a game! Type in a number and see if you guess mine correctly!")
num = input("Type in a number: ")
for x in range (0,1):
    if num == "7":
        print("Correct!")
    else:
        print("Nope, try again!")

(Also I know that a lot of this code is probably wrong.)

You can put it in a while loop:

verified = None
while verified is None:
    num = input("Type in a number: ")
    if num == "7":
        print("Correct!")
        # if answer is good
        verified = True
    else:
        print("Nope, try again!")

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