重复循环,直到选择了正确的随机值

时间:2017-12-12 18:56:29

标签: python

我正在尝试制作一个随机选择一个数字的程序,然后你必须猜出这个数字,直到你得到这个数字是正确的。到目前为止它的工作原理让我能猜出一次,然后程序结束,我需要它重复我的输入,直到我猜到正确的数字。

import random
a = random.randint(1,20)
print("My number is somewhere between one and twenty")
b = int(input("What is your guess?: "))
if b == a:
    print("You guessed my number!")
elif b > a:
    print("You're number is too large")
elif b < a:
    print("You're number is too small")     

input("\n\nPress the enter key to exit")

2 个答案:

答案 0 :(得分:1)

你错过了while循环,它会在满足某个条件之前执行。在您的情况下,代码将是这样的:

import random
a = random.randint(1,20)
print("My number is somewhere between one and twenty")
b = 0  # We create the variable b
while b != a:  # This executes while b is not a
    b = int(input("What is your guess?: "))
    if b > a:
        print("Your number is too large")
    elif b < a:
        print("Your number is too small")     
print("You guessed my number!")  # At this point, we know b is equal to a

input("\n\nPress the enter key to exit")

答案 1 :(得分:0)

它正在运作

import random
a = random.randint(1,20)
print("My number is somewhere between one and twenty")
while True: #missing the while loop
    b = int(input("What is your guess?: "))
    if b == a:
        print("You guessed my number!")
        exit()
    elif b > a:
        print("You're number is too large")
    elif b < a:
        print("You're number is too small")