How to repeat a section of the program until the input is correct?

后端 未结 3 1595
抹茶落季
抹茶落季 2020-12-04 01:25

I want my code to be repeated until the player guesses correctly.

ghuess=input("state a number between 1-100")
if ghuess>number:
    print "         


        
相关标签:
3条回答
  • 2020-12-04 01:41

    This is normally approached with a while loop:

    while True:
        ... # do your thing
        if finished: # are we done here?
            break # leave
    ... # execution resumes here after break
    
    0 讨论(0)
  • 2020-12-04 01:51

    For a solution without a break:

    isFound = False
    while not isFound:
        ghuess=input("state a number between 1-100")
        if ghuess>number:
            print "too high try again!"
        elif ghuess<number:
           print "too low try again!"
        else:
            isFound = True
            print "well done! ghuess you have won.."
            time.sleep(1)
            print "3"
            time.sleep(1)
            print "2"
            time.sleep(1)
            print "1"
            time.sleep(1)
            print prize
    
    0 讨论(0)
  • 2020-12-04 01:53

    Add a while-loop there. This means you're looping the question again infinitely until you've reached a satisfactory result.

    while True:
        ghuess=input("state a number between 1-100")
        if ghuess>number:
            print "too high try again!"
        elif ghuess<number:
            print "too low try again!"
        else:
            # Jackpot, exit the loop.
            break
    print "well done! ghuess you have won.."
    time.sleep(1)
    print "3"
    time.sleep(1)
    print "2"
    time.sleep(1)
    print "1"
    time.sleep(1)
    print prize
    
    0 讨论(0)
提交回复
热议问题