使用随机库来猜测数字(Python)

时间:2013-12-09 05:49:22

标签: loops python-3.x random

#This program generates random number
#user enters guess
#progam tells user higher, lower or correct based on user input.
import random

def main():
    # Get a random number.
    number = random.randint(1, 101)
    user_guess = int(input("Pick a number between 1 and 100: "))
    userguess = guess(user_guess, number)
    print(userguess)


def guess(num1, num2):
    if num1 > num2:
        return("Lower")
    elif num1 < num2:
        return("Higher")
    else:
        return("Correct")

main()的

我可以让程序生成一个随机数,然后显示更高或更低,但不再显示。它应该再次询问,直到它击中随机,然后显示'正确'

1 个答案:

答案 0 :(得分:1)

您需要一个循环来保持提示,直到猜到正确的答案为止,while(True)一直持续到break;为止。尝试这样的事情。

def guess(num):
    while(True):
        user_guess = int(input("Pick a number between 1 and 100: "))
        if user_guess > num:
            print("Lower\n")
        elif user_guess < num:
            print("Higher\n")
        else:
            print("Correct")
            break;

这将反复向用户询问数字,直到他们正确用以下

替换您的主要方法
def main():
    # Get a random number.
    number = random.randint(1, 101)
    guess(number)

编辑:用True替换为true