# Guess a random number between 1 and 100

I want some recommendations or something I could add to the game. Please tell me what I could do better or what I did wrong. I made this during the time I learned Python.

import random
num = random.randint(1, 100)
while True:
print('Guess a number between 1 and 100')
guess = input()
i = int(guess)
if i == num:
print('You won!!!')
break
elif i < num:
print('Try Higher')
elif i > num:
print('Try Lower')
#any recommendations for the game end
print('if you gussed less than 6 times you won')

• One improvement would be to have the program automatically count the number of tries, so it can tell the user whether they won or lost. – Greg Hewgill Aug 11 '15 at 0:33

# Proper integer conversion

Right now, as it stands, you're just converting any user input to a integer, using the int function. What do you suppose happens if the user enters something like "abc"?

What you need to do is set up a try-except block, like this:

try:
user_integer = input("Enter an integer: ")
user_integer = int(user_integer)
except ValueError:
print("You must enter a valid integer!")


To set up something like this in your code, you'd change your code to something like this:

...

while True:
print("Guess a number between 1 and 100.")
guess = input()

try:
integer_guess = int(guess):

...
except ValueError:
...


# Tracking the number of "rounds"/"tries"

Rather than printing a message saying that if the user got below a certain amount of tries, they win, you can implement it into the code. The easiest way to do this would be to use a for ... in range( ... ) loop, like this:

rounds = ...
for _ in range(rounds):
...


(This has been implemented below, for reference.)

# Design

This is not a very extensible design, again, I'd recommend creating a function that allows you to create custom games, like this:

def number_guessing_game(low, high, rounds):
print("Guess a number between {low} and {high}. You have {rounds} rounds to try and guess correctly.".format(low=low, high=high, rounds=rounds))
number = random.randint(low, high)

for _ in range(rounds):
guess = input("Enter an integer: ")

try:
integer = int(guess)
if integer == number:
print('You won!!!')
return
elif integer < number:
print('Try Higher')
elif integer > number:
print('Try Lower')

except ValueError:
print("You must enter a valid integer.")

print("You didn't guess correctly in {rounds} rounds. You lost.".format(rounds=rounds))


An example function call might look like this:

number_guessing_game(1, 100, 6)


In short, all of your code becomes the following:

import random

def number_guessing_game(low, high, rounds):
print("Guess a number between {low} and {high}. You have {rounds} rounds to try and guess correctly.".format(low=low, high=high, rounds=rounds))
number = random.randint(low, high)

for _ in range(rounds):
guess = input("Enter an integer: ")

try:
integer = int(guess)
if integer == number:
print('You won!!!')
return
elif integer < number:
print('Try Higher')
elif integer > number:
print('Try Lower')

except ValueError:
print("You must enter a valid integer.")

print("You didn't guess correctly in {rounds} rounds. You lost.".format(rounds=rounds))

number_guessing_game(1, 100, 6)


Hope this helps!

• Typing an invalid integer probably shouldn't count towards the 6 guesses. Also I'd reveal the correct number if the player loses. – user3374348 Aug 11 '15 at 10:57
• You should keep the try: block as small as possible as a rule; preferably only containing the operation we are interested in. In this case, the try: except: else: construction, putting the if: elif: elif test in the else clause, would fit well (in the initial example, the input call should be outside the try clause on the same grounds). An alternative to else would be to use continue within the except clause, which also saves an indentation level by an early exit on invalid input (note the above comment on handling non-integer convertable inputs, though). – Daniel Andersson Aug 11 '15 at 14:25
guess = input()
i = int(guess)


Why are you splitting this on to two different lines? You can just merge the int() onto the line above it, and pass input() into it like this:

guess = int(input())


As Greg Hewgill mentioned in the comments, rather than saying this:

print('if you gussed less than 6 times you won')


You should actually count up and tell the user if they won.

This can be done by using a simple counter for how many times the user has made an attempt. Then, every time the code loops (they enter an answer), you just increment the counter:

num = random.randint(1, 100)
attempts = 0
while True:
attempts += 1


Then, at the end of your code and after the loop, you just need to set up some simple conditionals that check the attempts variable:

if attempts < 6:
print("You won!")
else:
print("You lost!")


Then, to take this step further and reduce magic numbers, create a constant at the top of your code that defines the number of attempts at which the user has lost.

That is done like this:

ATTEMPTS_FOR_LOSE = 6


Then, you just substitute the 6 for ATTEMPTS_FOR_LOST in the conditional snippet I showed a little above.