Python Forum

Full Version: advice
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi. I'm new to Python and have created some code for a game. In the game, the user has 5 attempts to guess a number chosen at random by the computer. I have got it working as I wanted but just want some advice on if there is anything I could do to make it more streamlined and less long winded?
Advice much appreciated:

from time import sleep
from random import randint
player = input('What is your name? ')
print('Hello', player + '!') ; sleep(1)
print("Let's play a game!") ; sleep(2)
print("I'm going to pick a number between 0 and 9.") ; sleep(2)
print("I'll give you 5 guesses to get it right.") ; sleep(2)
print("Good Luck!!") ; sleep(2)
number = (randint(0,9))
pick = int(input('Pick a number between 0 and 9: '))
print('Your guess is:', pick) ; sleep(1)
lives = 5
count = 1 
while pick != number:
    lives -= 1
    if(pick >number):
        print("Sorry that number is too high! Try again! Lives left =", lives) ; sleep(1)
        pick = int(input('Pick a number between 0 and 9: ')) ; sleep(1)
    else:
        print("Sorry that number is too low! Try again! Lives left =", lives)
        pick = int(input('Pick a number between 0 and 9: ')) ; sleep(1)
    count += 1 
    if (count == 5) and(pick != number):
        print('Sorry, you are out of lives! Game over!!') ; sleep(1)
        break
while pick == number:
    if (lives == 1):
        print('Well done! You got it with', lives ,'life left!')
        break
    else:
        print('Well done! You got it with', lives ,'lives left!')
        break
I would redo the while loop like so:

lives = 4
while True:
    pick = int(input('Pick a number between 0 and 9: '))
    if pick == number:
        break
    lives -= 1
    if not lives:
        break
    if(pick > number):
        print("Sorry that number is too high! Try again! Lives left =", lives)
    else:
        print("Sorry that number is too low! Try again! Lives left =", lives)
if lives:
    life_word = 'life' if lives == 1 else 'lives'
    print('Well done! You got it with {} {} left.'.format(lives, life_word))
else:
    print('Sorry, you are out of lives. Game over.')
Lives and count are tracking the same thing, you only need one of them. The above code only asks the question in one place, not three. I took out your sleep calls. I'm not a fan of those. If you really want to keep them in, don't use semi-colons, put them on their own line. I took out the second while loop, and moved the failure message. That simplified the end of game code.

Edit: I changed lives to 4, because 5 is too generous.
I would do something
from random import randint

lives = 5
player = input('What is your name? ')

print(f'Hello {player}')
print("Let's play a game!")
print("I'm going to pick a number between 0 and 9.")
print("I'll give you 5 guesses to get it right.")
print("Good Luck!!")

number = randint(0,9)
for tries in range(1, lives+1):
    pick = int(input('Pick a number between 0 and 9: '))
    if pick == number:
        print(f'Well done! You got it with {lives - tries} lives left!')
        break
    elif pick > number:
        print(f"Sorry, that number is too high!", end=' ')
    else:
        print(f"Sorry, that number is too low!", end =' ')
    if lives - tries > 0:
        print(f'Try again! Lives left = {lives - tries}')
else:
    print('You are out of lives! Game over!!')
And I really don't understand why so many newbies die to add sleep() to slow the code :-)
buran and ichabod801 provided great examples how to improve code.

I would suggest to add input validation mimicking real world scenarios. Currently, if user enters float, letter etc which can't be converted to int program will throw ValueError.

One possible way:

def validate(request):
    """Return allowed input in range 0-9"""
    
    allowed = range(10)
    
    m = ('Expected integer in range 0 - 9 '
         'but input was')
     
    while True:
        answer = input(request)
        try:
            answer = int(answer)
            if answer in allowed:
                return answer
         
        except ValueError:
            print(f'{m} {answer}')
             
        else:
            print(f'{m} {answer}')
Then you can write in game code:

pick = validate('Pick number between 0 and 9: ')