'Number Guessing Game (Python)
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.
Solution 1:[1]
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()
Solution 2:[2]
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()
Solution 3:[3]
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
...
Solution 4:[4]
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()
Solution 5:[5]
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.")
Solution 6:[6]
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())
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | PL200 |
Solution 2 | John Anderson |
Solution 3 | Alex Leach |
Solution 4 | Franndy Abreu |
Solution 5 | Porkchop |
Solution 6 | B1029 |