Search code examples
pythonpython-3.xminify

Is there any way to minify this code further?


Here I have a block of python script. It's a simple guessing game. I was wondering, how far can I boil this down? Are there any more tricks that I can employ to remove some extraneous code, aside from importing modules?

from random import randint
n = randint(1,20)
print("I'm thinking of a number 1-20. Keep guessing until you get it!")
while True:
    try:
        g = int(input(""))
    except(ValueError):
        print("INPUT MUST BE AN INTEGER!")
    else:
        if g == n:
            print("YOU WIN!")
            exit()
        if g > n:
            print("Too high!")
        else:
            print("Too low!")

Solution

  • Looks OK. You can't really make it much shorter, but a little more readable with a get_number function that handles getting user input. In addition, instead of using exit you could just break your loop.

    Once Assignment Expressions hit with Python 3.8, you can even get rid of that break:

    from random import randint
    
    def get_number():
        'ask for an integer until user provides an integer'
        while True:
            try:
                g = int(input('enter integer: '))
                return g
            except ValueError:
                print('INPUT MUST BE AN INTEGER!')
    
    secret = random.randint(1, 20)
    while (g := get_number()) != secret:
        if g > n:
            print('too high!')
        else:
            print('too low!')
    
    print('YOU WIN!')