如果语句未显示正确的输出

时间:2018-12-28 06:09:51

标签: python

当我猜到正确答案时,此代码永远不会显示祝贺。

例如,如果rand()函数的返回值等于89,而我猜想是正确的89,则程序将返回“ Too high”或“ Too low”,即使情况并非如此。

from random import randint

def rand():
    return randint(1, 100)

print(rand())

choice = "Y"
while choice == "Y":
    x = int(input("Guess the random number: "))
    if x == rand():
        print("The numbers are the same! Congrats!")
    elif x > rand():
        print("Too high")
    elif x < rand():
        print("Too low")
    else:
        print("Nothing")
    choice = input("Continue? Y for yes, N for no. ")

4 个答案:

答案 0 :(得分:0)

rand函数在每次调用时都会生成新的随机数。因此,您需要调用rand函数并将其分配给变量。

rand_no = rand()
print(rand_no)

choice = "Y"
while choice == "Y":
    x = int(input("Guess the random number: "))
    if x == rand_no:
        print("The numbers are the same! Congrats!")
    elif x > rand_no:
        print("Too high")
    elif x < rand_no:
        print("Too low")
    else:
        print("Nothing")
    choice = input("Continue? Y for yes, N for no. ")

答案 1 :(得分:0)

rand函数不会在每次调用时返回相同的值,如果是这种情况,它将是一个非常无用的随机数生成器。

您需要做的是将其称为一次以获取值,然后使用该值,例如:

actual = rand()
choice = "Y"
while choice == "Y":
    x = int(input("Guess the random number: "))
    if x == actual:
        print("The numbers are the same! Congrats!")
    elif x > actual:
        print("Too high")
    elif x < actual:
        print("Too low")
    else:
        print("Nothing")
    choice = input("Continue? Y for yes, N for no. ")

答案 2 :(得分:0)

我认为这是因为您每次比较都调用随机函数。它总是返回一个不同的数字。尝试将其添加到输入下面:

rand_var = rand()

与var进行比较,而不是每次都调用rand。

答案 3 :(得分:0)

您只需要将您的随机变量分配给变量,然后在while循环中将其设置为每次都不同。就是这样。

from random import randint


def rand():
    return randint(1, 100)

choice = "Y"
while choice == "Y":
    num = rand()
    print(num)

    x = int(input("Guess the random number: "))
    if x == num:
        print("The numbers are the same! Congrats!")
    elif x > num:
        print("Too high")
    elif x < num:
        print("Too low")
    else:
        print("Nothing")
    choice = input("Continue? Y for yes, N for no. ")