HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Guess a random number between 1 and 100

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
randomnumber100betweenandguess

Problem

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 Lower')
#any recommendations for the game end
print('if you gussed less than 6 times you won')

Solution

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 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 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!

Code Snippets

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

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

    try:
        integer_guess = int(guess):

        ...
    except ValueError:
        ...
rounds = ...
for _ in range(rounds):
    ...
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)

Context

StackExchange Code Review Q#100539, answer score: 6

Revisions (0)

No revisions yet.