Python"猜数字"游戏给出意想不到的结

时间:2018-03-11 22:36:19

标签: python

我最近开始学习python,而我的工作中的朋友是一名程序员给了我一个简单的挑战来写一个"猜数字"风格游戏。

所以我想出了如下内容:

import random

print("Hello, welcome to GUESS THE NUMBER game")

run = True


def again():
    global run
    playagain = str(input("Would you like to play again? Type y/n for yes or no: "))
    if playagain == "y":
        run = True
    elif playagain == "n":
        run = False


while run:

    guess = int(input("Guess the number between 1 and 10: "))
    num1 = random.randint(1, 10)

    if guess == num1:
        print("CONGRATULATIONS, YOU HAVE GUESSED THE NUMBER, THE ANSWER WAS " + str(num1))
        again()
    elif guess > num1:
        print("Too high, go lower!")
    elif guess < num1:
        print("Too small, go higher!")

我的问题是,在用户选择再次播放之后,这些数字有时候不会注册并且不会出现问题。例如,你输入5并且它说得太低,但是如果输入6则说得太高了!我似乎不是在处理浮动数字,所以他们应该是完整的,我出错的任何想法?

提前致谢并非常兴奋地了解有关该主题的更多信息

2 个答案:

答案 0 :(得分:1)

您的问题是您每次都要重新生成随机数。

num1 = random.randint(1, 10)

相反,也许把猜测和检查逻辑放在它自己的循环中。

while True:
    guess = int(input("Guess the number between 1 and 10: "))

    if guess == num1:
        print("CONGRATULATIONS, YOU HAVE GUESSED THE NUMBER, THE ANSWER WAS " + str(num1))
        break # leave the while True loop
    elif guess > num1:
        print("Too high, go lower!")
    elif guess < num1:
        print("Too small, go higher!")

again()

答案 1 :(得分:1)

您正在计算循环的每次迭代的随机数。因此每次猜测随机数变化。

导入随机

print("Hello, welcome to GUESS THE NUMBER game")

run = True


def again():
    global run
    playagain = str(input("Would you like to play again? Type y/n for yes or no: "))
if playagain == "y":
    run = True
elif playagain == "n":
    run = False

num1 = random.randint(1, 10)

while run:

    guess = int(input("Guess the number between 1 and 10: "))

    if guess == num1:
        print("CONGRATULATIONS, YOU HAVE GUESSED THE NUMBER, THE ANSWER WAS " + str(num1))
        again()
    elif guess > num1:
        print("Too high, go lower!")
    elif guess < num1:
        print("Too small, go higher!")