5
\$\begingroup\$

I'm a total Python beginner and made a number guessing game as first project. The user has to guess the number the computer is thinking of. Please give me feedback!

print("Guess a number")
import random
x = random.randint(-999, 999)

g1=int(input('Enter your guess:'))

while x != g1:
    if x > g1:
        print("It's Bigger!")
    elif x < g1:
        print("It's smaller")
    g1=int(input('Enter your guess:'))
print ("Contragulations")
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

This is a good start for a beginner. I don't think you are doing anything fundamentally wrong.

It's a good idea to group your imports together near the beginning when possible, to help readers see the dependencies immediately (occasionally, some imports will need to be elsewhere - perhaps because they are only needed if particular conditions hold - but that's pretty unusual).

You should try to attain the habit of using more descriptive names. That will help make your code easier to understand (that's important when you come back to something you wrote six months ago and need to modify it for new requirements). In this case, I suggest target instead of x, and guess instead of g1.

Also in the spirit of readability, add some spaces around the assignment:

guess = int(input('Enter your guess:'))

This statement appears in two places; a principle of programming is to avoid repeating anything non-trivial - summarised as "Don't Repeat Yourself" or DRY (as opposed to WET: "Write Everything Twice"). We can define a simple function like this:

def get_guess():
    return int(input('Enter your guess:'))

and use it:

guess = get_guess()

This might not seem like in improvement, but consider what we want to do with this function. To start with, it's normal to put a space after the computer output, so we change 'Enter your guess:' to 'Enter your guess: '. We only have one place to change, so there's no longer a risk that we miss one and make the behaviour inconsistent.

Slightly more advanced, observe that the user might enter something that's not a number - if that happens, the behaviour isn't very friendly:

Guess a number
Enter your guess: ten
Traceback (most recent call last):
  File "/home/tms/stackexchange/review/283185.py", line 13, in <module>
    guess = get_guess()
  File "/home/tms/stackexchange/review/283185.py", line 7, in get_guess
    return int(input('Enter your guess: '))
ValueError: invalid literal for int() with base 10: 'ten'

We can catch the error and ask to try again:

def get_guess():
    while True:
        try:
            return int(input('Enter your guess: '))
        except ValueError:
            print("Input should be a number from -999 to +999")

Now the advantage of creating a function for this is really starting to pay back!

A way to avoid writing guess = get_guess() twice is to use the Python 3 := assignment operator to assign and use guess together:

while (guess := get_guess()) != target:

We should make the feedback messages consistent (punctuation and capitalisation).

I would also catch a couple of exceptions from the user interaction to exit the program quietly instead of producing backtraces.


Modified program

import random

target = random.randint(-999, 999)

def get_guess():
    while True:
        return int(input('Enter your guess: '))
        try:
            return int(input('Enter your guess: '))
        except ValueError:
            print("Input should be a number from -999 to +999")

if __name__ == '__main__':
    try:        
        print("Guess a number")
        while (guess := get_guess()) != target:
            if target > guess:
                print("It's bigger!")
            elif target < guess:
                print("It's smaller!")
        print("Contragulations")
    except KeyboardInterrupt:
        print(f'\nGiving up - the number was {target}')
    except EOFError:
        print()
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.