-1

Working in Python 3.

I'm still relatively new to Python (only a few weeks worth of knowledge).

The prompt that I was given for the program is to write a random number game where the user has to guess the random number (between 1 and 100) and is given hints of being either too low or too high if incorrect. The user would then guess again, and again until they reach the solution. After the solution, the number of guesses should tally at the end.

import random

def main():

    # initialization
    high = 0
    low = 0
    win = 0
    number = random.randint(1, 100)

    # input
    userNum = int(input("Please guess a number between 1 and 100: "))

    # if/else check
    if userNum > number:
        message = "Too high, try again."
        high += 1
    elif userNum == number:
        message = "You got it correct! Congratulations!"
        win += 1
    else:
        message = "Too low, try again."
        low += 1
    print()
    print(message)

    # loop
   # while message != "You got it correct! Congratulations!":

    # display total
    print()
    print("Number of times too high: ", high)
    print("Number of times too low: ", low)
    print("Total number of guesses: ", (high + low + win))     

main()

I'm struggling to figure out how to make the loop work. I need the random number to be static while the user guesses with inputs. After each attempt, I also need them to be prompted with the correct message from the if/else check.

  • Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – U13-Forward Oct 29 '18 at 03:27

6 Answers6

1

You can just put your guesses in a simple loop:

import random

def main():

    # initialization
    high = 0
    low = 0
    win = 0
    number = random.randint(1, 100)

    while win == 0:
        # input
        userNum = int(input("Please guess a number between 1 and 100: "))

        # if/else check
        if userNum > number:
            message = "Too high, try again."
            high += 1
        elif userNum == number:
            message = "You got it correct! Congratulations!"
            win += 1
        else:
            message = "Too low, try again."
            low += 1
        print()
        print(message)

    # loop
   # while message != "You got it correct! Congratulations!":

    # display total
    print()
    print("Number of times too high: ", high)
    print("Number of times too low: ", low)
    print("Total number of guesses: ", (high + low + win))

main()
John Anderson
  • 35,991
  • 4
  • 13
  • 36
0

You could set 'userNum' to be 0, and encase all the input in a while loop:

userNum = 0

while (userNum != number):

This will continually loop the guessing game until the user's guess equals the random number. Here's the full code:

import random

def main():

    # initialization
    high = 0
    low = 0
    win = 0
    number = random.randint(1, 100)
    userNum = 0

    while (userNum != number):
        # input
        userNum = int(input("Please guess a number between 1 and 100: "))

        # if/else check
        if userNum > number:
            message = "Too high, try again."
            high += 1
        elif userNum == number:


        message = "You got it correct! Congratulations!"
        win += 1
        else:
            message = "Too low, try again."
            low += 1
    print()
    print(message)

    # loop
   # while message != "You got it correct! Congratulations!":

    # display total
    print()
    print("Number of times too high: ", high)
    print("Number of times too low: ", low)
    print("Total number of guesses: ", (high + low + win))


    print("You win")

main()
PL200
  • 741
  • 6
  • 24
0

Any of the other answers will work, but another check you can do for the loop is 'not win', which will stop the loop for any value of win that isn't zero.

 while not win:
    # input
    userNum = int(input("Please guess a number between 1 and 100: "))

    # if/else check
    ...
Alex Leach
  • 118
  • 7
0
import random

def main():

# initialization
high = 0
low = 0
win = 0
number = random.randint(1, 100)

# input

while(True): #Infinite loop until the user guess the number.
    userNum = int(input("Please guess a number between 1 and 100: "))
# if/else check
    if userNum > number:
        message = "Too high, try again."
        high += 1

    elif userNum == number:
        message = "You got it correct! Congratulations!"
        win += 1
        break #Break out of the infinite loop 

    else:
        message = "Too low, try again."
        low += 1
    print(message) ##Display the expected message

print()
print(message)



# display total
print()
print("Number of times too high: ", high)
print("Number of times too low: ", low)
print("Total number of guesses: ", (high + low + win))     


if __name__ == '__main__':
    main()
Franndy Abreu
  • 186
  • 2
  • 12
0

There's so many ways you can go about this kind of task, it's what makes programming epic.

I have written a little something that answers your question, it even has a simple feel to it!

What i've done is done a for loop to give the user a total of range(10) tries. For every guess the user makes, it adds 1 'tries' to 0. In my if statement, all I'm wanting to know is if the guess is the same as the_number and below the number of tries available, you've done it. Otherwise, higher or lower :)

Hope this helps!

import random


print("\nWelcome to the guessing game 2.0")
print("Example for Stack Overflow!\n")

the_number = random.randint(1, 100)
tries = 0

for tries in range(10):
    guess = int(input("Guess a number: "))
    tries += 1

    if guess == the_number and tries <= 10:
        print("\nCongratulations! You've guessed it in", tries, "tries!")
        break
    elif guess < the_number and tries < 10:
        print("Higher...")
        tries += 1
    elif guess > the_number and tries < 10:
        print("Lower...")
        tries += 1
    elif tries >= 11:
        print("\nI'm afraid to haven't got any tries left. You've exceeded the limit.")
Porkchop
  • 1
  • 1
0
import random
def display_title():
    return print("Number Guessing Game")
def play_game():
    cpu_num = random.randint(1, 10)
    user_guess = int(input("Guess a number from 1 to 10:")
    while user_guess != cpu_num:
        print("Try Again")
        user_guess = int(input("Guess a number from 1 to 10:"))
    if user_guess == cpu_num:
        print("Correct!")
def main():
    title = print(display_title())
    game = print(play_game())

    return title, game
print(main())
B1029
  • 1
  • 1
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 22 '22 at 08:59