Variable issue with my python guessing game - python

I'm making a guessing game where you have the option of an easy medium and hard mode but when I adjusted my code so that the display changes from 100 to 1,000,000 I get an error saying:
File "C:/Users/Zach Hirschman/AppData/Local/Programs/Python/Python35-32/GuessGame.py", line 38, in main
if guess > randomNumber:
UnboundLocalError: local variable 'randomNumber' referenced before assignment
I can't seem to figure out how I can fix this, any help would be appreciated.
"""
Zach Hirschman
12/20/2017
GuessGame.py
This program asks the user to guess a number
"""
import random
def main():
difficulty = input("Enter a difficulty level: 'easy','medium', or 'hard'
: ")
print("At any time, type 'hint' to get a hint")
if difficulty == "easy":
randomNumber = random.randint(1,100)
elif difficulty == "medium":
randumNumber = random.randint(1,10000)
elif difficulty == "hard":
randomNumber = random.randint(1,1000000)
found = False
while not found:
if difficulty == "easy":
guess = int(input("Guess a number between 1 and 100"))
if guess > randomNumber:
print("Too high")
elif guess == randomNumber:
print("Thats correct!!")
found = True
else :
print("Too Low")
elif difficulty == "medium":
guess = int(input("Guess a number between 1 and 10000"))
if guess > randomNumber:
print("Too high")
elif guess == randomNumber:
print("Thats correct!!")
found = True
else :
print("Too Low")
elif difficulty == "hard":
guess = int(input("Guess a number between 1 and 1000000"))
if guess > randomNumber:
print("Too high")
elif guess == randomNumber:
print("Thats correct!!")
found = True
else :
print("Too Low")
x = input("would you like to play again? Type 'yes' or 'no': ")
if x == "yes":
main()
else:
print("See you later!")
main()

I think it was just a scoping issue. For randomNumber variable to be available in the while loop, the while loop has to be within the same function that the variable is declared in (eg. main()): then they have the same "scope".
Initialising randomNumber before the if statements is not needed and will make no difference. That is usually done before for or while loops (as you did with found = False). randomNumber was not being initialised because it depended on "difficulty", which was out of scope.
Note that after defining it, the function has to be called by main(). In your code main() wasn't running, only the ifs/while parts were as they were written outside the function.
import random
def main():
difficulty = input("Enter a difficulty level: 'easy','medium', or 'hard' : ")
print("At any time, type 'hint' to get a hint")
if difficulty == "easy":
randomNumber = random.randint(1,100)
elif difficulty == "medium":
randomNumber = random.randint(1,10000)
elif difficulty == "hard":
randomNumber = random.randint(1,1000000)
found = False
while not found:
if difficulty == "easy":
guess = int(input("Guess a number between 1 and 100"))
if guess > randomNumber:
print("Too high")
elif guess == randomNumber:
print("Thats correct!!")
found = True
else :
print("Too Low")
main()
The other options are:
moving everything out of the function, which will work fine by gets complicated for longer programs
adding a return value to main() and binding it to randomNumber. This would also require the same for the difficulty variable, so would be better to refactor into multiple smaller functions.
Finally, randomNumber had a typo - that didn't cause the problem though.

Another approach which simplifies a little your solution:
import random
difficulty_thresholds = {
"easy" : 100,
"medium" : 10000,
"hard" : 1000000
}
wants_to_continue = True
while wants_to_continue:
difficulty = input("Enter a difficulty level: 'easy','medium', or 'hard': ")
maximum_number = difficulty_thresholds.get(difficulty, 100)
randomNumber = random.randint(1, maximum_number)
found = False
while not found:
guess = int(input("Guess a number between 1 and {}: ".format(maximum_number)))
if guess > randomNumber:
print("Too high")
elif guess == randomNumber:
print("That's correct!!!")
found = True
else:
print("Too Low")
do_we_continue = input("Would you like to play again? Type 'yes' or 'no': ")
wants_to_continue = do_we_continue == "yes"
print("See you later!")

Related

How can I stop my game from generating a new number while it's running?

I'm a beginner python developer. I've been experimenting with the random module and decided to create a guessing game. Problem is, Whenever the user inputs a guess, a new number is generated.
You can find this in the "run" loop. Here's the code.
import random
from time import sleep
print(""" Number Guessing Game
Type 'Quit' To Exit The Game
Choose a Level:
(1)Easy
(2)Medium
(3)Hard
""")
run = True
def play_game():
play_game.choice = input("> ")
print("\nGuess The Number!\n")
return play_game.choice
play_game()
while run:
if play_game.choice == "1":
r = random.randint(1, 10)
guess = int(input("> "))
if guess == r:
print("You Won!")
break
elif guess > r:
print("Too High!\nGuess Again.")
elif guess < r:
print("Too Low!\nGuess Again.")
elif play_game.choice == "2":
r = random.randint(1, 50)
print("\nGuess The Number!")
if r == guess:
print("You Won!")
break
elif guess > r:
print("Too High!\nGuess Again.")
elif guess < r:
print("Too Low!\nGuess Again.")
elif play_game.choice == "3":
r = random.randint(1, 100)
print("\nGuess The Number!\n")
if r == guess:
print("You Won!")
break
elif guess > r:
print("Too High!\nGuess Again.")
elif guess < r:
print("Too Low!\nGuess Again.")
elif play_game.choice.upper() == "QUIT":
print("See You Later!")
sleep(1)
break
else:
print("Unknown Command!\nTry Again")
Could you please help me figure out what's wrong? Thanks!
Make a variable called generated and only generate it if it is false. When you generate your number, set it to true
Your code:
run = true
generated = false
while run:
if play_game.choice == "1":
if not(generated): # ADD THIS
r = random.randint(1, 10)
generated = true # ADD THIS
print(r)
guess = int(input("> "))
if guess == r:
print("You Won!")
break
elif guess > r:
print("Too High!\nGuess Again.")
elif guess < r:
print("Too Low!\nGuess Again.")
elif play_game.choice == "2":
if not(generated):
r = random.randint(1, 50)
generated = true
print("\nGuess The Number!")
if r == guess:
print("You Won!")
break
elif guess > r:
print("Too High!\nGuess Again.")
elif guess < r:
print("Too Low!\nGuess Again.")
elif play_game.choice == "3":
if not(generated):
r = random.randint(1, 100)
generated = true
print("\nGuess The Number!\n")
if r == guess:
print("You Won!")
break
elif guess > r:
print("Too High!\nGuess Again.")
elif guess < r:
print("Too Low!\nGuess Again.")
elif play_game.choice.upper() == "QUIT":
print("See You Later!")
sleep(1)
break
else:
print("Unknown Command!\nTry Again")
Or even better, you can generate the number before the run loop with the if/elif and then have a univerasal run loop, as you have the same code for guessing.
# *ask for gamemode*
r = 0
if choice == "1":
r = random.randint(1, 10)
elif choice == "2":
r = random.randint(1, 50)
elif choice == "3":
r = random.randint(1, 100)
print("\nGuess The Number!\n")
while run:
guess = int(input("> "))
if r == guess:
print("You Won!")
break
elif guess > r:
print("Too High!\nGuess Again.")
elif guess < r:
print("Too Low!\nGuess Again.")
Depends on what you want to do. Here is the use case I understand from your question and the code:
generate a random number named "r"
acquire guess input (variable is named "guess") from the user
if r == guess, stop the game
if r != guess, ask another guess and return to step 2
Hence, you need to change the following:
The variable "r" should be before the while loop, that is, r = random.randint(..,..) should be before the line while run:. The argument in randint should be decided according to the level, but, again, before the while loop!
once the user has found r, that is, when guess == r, then you should set variable run to False.
Let me know if you manage to find a solution, otherwise I can send you a detailed script.
I propose this code:
import random
level = input(""" Number Guessing Game
Type 'Quit' To Exit The Game
Choose a Level:
(1)Easy
(2)Medium
(3)Hard
""")
print("\nGuess The Number!\n")
run = True
if level == "1":
r = random.randint(1, 10)
elif level == "2":
r = random.randint(1, 50)
elif level == "3":
r = random.randint(1, 100)
else:
raise ValueError("incorrect level")
while run:
guess = int(input("> "))
if guess == r:
print("You Won!")
run = False
elif guess > r:
print("Too High!\nGuess Again.")
elif guess < r:
print("Too Low!\nGuess Again.")

Counting Game Try/Except and calculating the users attempts

I am creating a python random counting game. I'm having some difficulties with certain parts. Can anyone here review my code? I'm having difficulty with trying to implement a try/except and a tries function that counts the user's attempts. I also have to verify that the number is a legitimate input and not a variable. So far I've gotten this far and its coming along good. I just need alittle help ironing out a few things. Thanks guys you rock.
Here is the code below:
import random
def main():
start_game()
play_again()
tries()
print("Welcome to the number guessing game")
print("I'm thinking of a number between 1 and 50")
def start_game():
secret_number = random.randint(1,50)
user_attempt_number = 1
user_guess = 0
while user_guess != secret_number and user_attempt_number < 5:
print("---Attempt", user_attempt_number)
user_input_text = input("Guess what number I am thinking of: ")
user_guess = int(user_input_text)
if user_guess > secret_number:
print("Too high")
elif user_guess < secret_number:
print("Too low")
else:
print("Right")
user_attempt_number += 1
if user_guess != secret_number:
print("You ran out of attempts. The correct number was"
+str(secret_number)+ ".")
def play_again():
while True:
play_again = input("Do you want to play again?")
if play_again == 'yes':
main()
if play_again =='no':
print("Thanks for playing")
break
def tries():
found= False
max_attempts=50
secret_number = random.randint(1, 50)
while tries <= max_attempts and not found:
user_input_text = start_game()
user_guess_count=+1
if user_input_text == secret_number:
print("It took you {} tries.".format(user_guess_count))
found = True
main()
Try this method:
def play_game():
print("Enter the upper limit for the range of numbers: ")
limit = int(input())
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
count = 1 #new line
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
count = count+

Python "Guess The Number" game giving unexpected results

i recently started learning python and my friend from work who is a programmer gave me a simple challenge to write a "guess the number" style game.
So i came up with something as follows:
import random
print("Hello, welcome to GUESS THE NUMBER game")
run = True
def again():
global run
playagain = str(input("Would you like to play again? Type y/n for yes or no: "))
if playagain == "y":
run = True
elif playagain == "n":
run = False
while run:
guess = int(input("Guess the number between 1 and 10: "))
num1 = random.randint(1, 10)
if guess == num1:
print("CONGRATULATIONS, YOU HAVE GUESSED THE NUMBER, THE ANSWER WAS " + str(num1))
again()
elif guess > num1:
print("Too high, go lower!")
elif guess < num1:
print("Too small, go higher!")
My problem is that after the user has chosen to play again, the numbers sometimes dont register and go out of whack. For example you input 5 and it says too low, but if you input 6 it says too high! I don't seem to be dealing in float numbers so they should be whole, any ideas where i went wrong?
Thanks in advance and very excited to learn more on the subject
Your problem is that you're regenerating the random number every time.
num1 = random.randint(1, 10)
Instead, maybe put the guess and check logic inside it's own loop.
while True:
guess = int(input("Guess the number between 1 and 10: "))
if guess == num1:
print("CONGRATULATIONS, YOU HAVE GUESSED THE NUMBER, THE ANSWER WAS " + str(num1))
break # leave the while True loop
elif guess > num1:
print("Too high, go lower!")
elif guess < num1:
print("Too small, go higher!")
again()
You are calculating the random number on each iteration of the loop. Therefore every time you guess the random number changes.
import random
print("Hello, welcome to GUESS THE NUMBER game")
run = True
def again():
global run
playagain = str(input("Would you like to play again? Type y/n for yes or no: "))
if playagain == "y":
run = True
elif playagain == "n":
run = False
num1 = random.randint(1, 10)
while run:
guess = int(input("Guess the number between 1 and 10: "))
if guess == num1:
print("CONGRATULATIONS, YOU HAVE GUESSED THE NUMBER, THE ANSWER WAS " + str(num1))
again()
elif guess > num1:
print("Too high, go lower!")
elif guess < num1:
print("Too small, go higher!")

NameError: guesses not defined

I'm just starting out on python and I'm wondering exactly why my variable guesses is not defined. I feel as if it's a indentation issue but once I change the indentation I usually come upon a syntax error any help understanding this issue would be greatly appreciated.
import random
def game():
guesses = []
secret_num = random.randint(1, 10)
while len(guesses) < 5:
try:
guess = int(input("Guess a number between 1 and 10 "))
except ValueError:
print("{} isn't a number!".format(guess))
else:
if guess == secret_num:
print("You got it! My number was {}".format(secret_num))
break
elif guess < secret_num:
print("My number is higher than {}".format(guess))
else:
print("My number is lower tha {}".format(guess))
guesses.append(guess)
else:
print("You didn't get it my secret number was {}".format(secret_num))
play_again = input("Do you want to play again? Y/N")
if play_again.lower() != 'n':
game()
else:
print("Bye thanks for playing!")
This doesn't throw any errors on my computer. Note you'll have to call the game() function if you want to actually run the code.
import random
def game():
guesses = []
secret_num = random.randint(1, 10)
while len(guesses) < 5:
try:
guess = int(input("Guess a number between 1 and 10 "))
except ValueError:
print("{} isn't a number!".format(guess))
else:
if guess == secret_num:
print("You got it! My number was {}".format(secret_num))
break
elif guess < secret_num:
print("My number is higher than {}".format(guess))
else:
print("My number is lower tha {}".format(guess))
guesses.append(guess)
else:
print("You didn't get it my secret number was {}".format(secret_num))
play_again = input("Do you want to play again? Y/N")
if play_again.lower() != 'n':
game()
else:
print("Bye thanks for playing!")
game() # to run the code

Python program that allows user to restart or exit it

I want this program to allow users to restart the game when they are through or exit it if they do not want to play the game again, but I cant figure out how to do it. Can you please help me with the code that makes the program do that?
Please correct me if I mistype the code below.
Below is the code of the game I have written using python:
import random
secret_number = random.randrange(1, 101)
guess = 0
tries = 0
while guess != secret_number:
guess = int(input("Guess a number: "))
tries = tries + 1
if guess < secret_number:
print("Too low!")
elif guess > secret_number:
print("Too high!")
else:
print("You got it!")
print("Number of tries: ", tries)
userInput = input("Enter 'R' to restart or 'X' to exit").capitalize()
if userInput == "R":
#code to restart the game goes here
elif gameReply == "X":
#code to exit the game goes here
Your indentation was wrong.
You can try to use a smaller random.randrange() while you are testing your program.
After the game finishes, what do you want to do if user inputs, say, hello? In the following program, you basically continue if it is not x or X and play again.
Here is the fixed version:
import random
import sys
while True: # outer game loop
print('Welcome to the game.')
secret_number = random.randrange(1, 5)
guess = 0
tries = 0
while guess != secret_number:
guess = int(input("Guess a number: "))
tries = tries + 1
if guess < secret_number:
print("Too low!")
elif guess > secret_number:
print("Too high!")
else:
print("You got it!")
print("Number of tries: ", tries)
userInput = input("Enter 'R' to restart or 'X' to exit").capitalize()
if userInput == "X":
print('Goodbye.')
sys.exit(-1) # exits the program
To restart the game: Well, you can declare a function that initializes the game, and then you call it if you want to restart.
To exit:
sys.exit()
I have a similar game already coded: you can have a look at it HERE. It was my first python code
For restart, you can just set tries to zero and continue since you are in a loop.
if userInput == "R":
tries = 0
continue
For exit, sys.exit() is a winner.
elif gameReply == "X":
sys.exit()
You can use sys.exit() to stop the script and wrap your code into a method so you can call it again when the user wants to restart. Also, use raw_input rather than input as input is expecting Python code.
For example:
import random
import sys
def my_game():
secret_number = random.randrange(1, 101)
guess = 0
tries = 0
while guess != secret_number:
guess = int(input("Guess a number: "))
tries = tries + 1
if guess < secret_number:
print("Too low!")
elif guess > secret_number:
print("Too high!")
else:
print("You got it!")
print("Number of tries: ", tries)
userInput = raw_input("Enter 'R' to restart or 'X' to exit").capitalize()
if userInput == "R":
my_game()
elif userInput == "X":
sys.exit()
my_game()

Categories