如何让用户重复回答,直到用户做对了?

时间:2017-01-07 17:04:09

标签: python

它要求用户猜测数字,但我需要用户能够回答它们才能正确使用。所以他们可以放弃。

enter image description here

3 个答案:

答案 0 :(得分:1)

要在条件不正确时执行某些操作,请使用 while 循环

while user_input != random_number:
    # feedback
    ## ... as you were...
    # and ask for another guess
    user_input = input("What is your guess?")

答案 1 :(得分:1)

使用while循环连续重复代码,如果猜测匹配,则从循环中关闭break

from random import randrange
random_number = randrange(101)

while True:
    print("see how many guess it takes to guess the maic number")
    user = input("what is your guess?")
    if user == random_number:
        print("well done!")
        break
    else:
        print("Wrong!Try again!")
        continue

答案 2 :(得分:1)

这是我的高低游戏代码。您可以相应地进行更改。

import random
print ("HIGH LOW GAME : GUESS THE NUMBER")
t=True
while t:
    count=0
    s=random.random()
    s=int(s*100)
    while True:
        try:            
            x=int(input("Give me your guess : "))
        except ValueError:
            continue
        if(x==s):
            print("You got it !!. No of tries",count)
            break           
        elif(x<s):
            print("Low")
            count=count+1
        else:
            print("High")
            count=count+1

    t=bool(input("Press Enter to Quit Or Press any other character then Enter to play again"))