简体   繁体   English

新手问题。 猜一个数字 - 代码不起作用

[英]Newbie question. Guess a number - code not working

    import random

    def guess(x):
random_number = random.randint(1, x)
guess = 0
while guess != random_number:
    guess = int(input(f"Guess a number between 1 and {x}: "))
    if guess > random_number:
        print(f"{guess} is incorrect, try lower!")
    elif guess < random_number:
        print(f"{guess} is incorrect, try higher!")


print(f"congratulations, you have guessed {random_number} correctly!")

Please help with this code, I have no idea why it's just not working.请帮忙处理这段代码,我不知道为什么它不起作用。 Been trying for a few hours.尝试了几个小时。 I see no issue with it, but then again, I am a newbie.我认为它没有问题,但话又说回来,我是新手。

The following code works correctly -以下代码正常工作 -

import random


def guess(x):
    random_number = random.randint(1, x)
    guess = 0
    while guess != random_number:
        guess = int(input(f"Guess a number between 1 and {x}: "))
        if guess > random_number:
            print(f"{guess} is incorrect, try lower!")
        elif guess < random_number:
            print(f"{guess} is incorrect, try higher!")

    print(f"congratulations, you have guessed {random_number} correctly!")


def main():
    guess(2)


if __name__ == '__main__':
    main()

The only change is that the function is called.唯一的变化是调用了 function。 In python, a function must be called in order to run.在 python 中,必须调用 function 才能运行。 In the code you have provided, the function was declared, but until someone "uses" it, it will just be a definition of the function.在您提供的代码中,声明了 function,但在有人“使用”它之前,它只是 function 的定义。 In the code I have added, I call the function using guess(2) .在我添加的代码中,我使用guess(2)调用 function 。 You may use it with other parameters:)您可以将其与其他参数一起使用:)

Please note that a big potential bug in the code is the fact the you use a variable with the same name of the function.请注意,代码中一个很大的潜在错误是您使用了与 function 同名的变量。 This is a very bad idea and may cause many issues.这是一个非常糟糕的主意,可能会导致很多问题。 So a fix for this would be to change the variable guess to something like current_guess .因此,解决此问题的方法是将变量guess更改为current_guess之类的东西。

So here it would be -所以这里就是——

import random


def guess(x):
    random_number = random.randint(1, x)
    current_guess = 0
    while current_guess != random_number:
        current_guess = int(input(f"Guess a number between 1 and {x}: "))
        if current_guess > random_number:
            print(f"{current_guess} is incorrect, try lower!")
        elif current_guess < random_number:
            print(f"{current_guess} is incorrect, try higher!")

    print(f"congratulations, you have guessed {random_number} correctly!")


def main():
    guess(2)


if __name__ == '__main__':
    main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM