简体   繁体   中英

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. In python, a function must be called in order to run. In the code you have provided, the function was declared, but until someone "uses" it, it will just be a definition of the function. In the code I have added, I call the function using guess(2) . 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. 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 .

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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