This question already has answers here:
Using global variables in a function
(25 answers)
Closed last year.
I keep receiving the following error when running the code
UnboundLocalError: local variable 'winner' referenced before assignment
The following is my code
# Create a Number Guessing Game
humannum = int(input("Enter a number from 1 - 10> "))
computernum = random.randint(1,10)
Winner = False
def winner(): # How to allow the user to try again
while Winner != True:
print("Your answer was not correct, please try again")
print(humannum)
def calculator(): # This is to calculate, who wins the game
if humannum == computernum:
print(f'The computer number was {computernum}')
print(f'Your number was {humannum}')
print("")
print("Therefore You have won ! ")
winner = True
elif humannum <= computernum:
print("Your number was larger than the computer")
winner()
elif humannum >= computernum:
print("Your number was larger than the computers")
winner()
calculator()
I am not sure why this is happening when I believe I have my variable winner referenced above me calling it which is below in the calculator function.
I refactored your code, removed extra functions and added a guess counter so that the user knows how many attempts are left.
import random
num = random.randint(1,10)
def num_guess():
attempts = 3
while attempts > 0:
attempts -= 1
try:
userGuess = int(input("Enter a number between 1 and 10: "))
except ValueError:
print("Invalid input. Try again.")
continue
if attempts > 0:
if userGuess == num:
print("You guessed the number!!")
break
elif userGuess < num:
print(f"The number is too low.\nYou have {attempts} attempts left.")
elif userGuess > num:
print(f"The number is too high.\nYou have {attempts} attempts left.")
else:
print("You did not guess the number.\Thanks for playing!")
num_guess()
In the calculator() method you wrote winner = True, not Winner. The issue is the variable names do not exactly match.
To use a global variable inside a function, we need to declare it using global.
Modified code:
import random
# Create a Number Guessing Game
humannum = int(input("Enter a number from 1 - 10> "))
computernum = random.randint(1, 10)
Winner = False
def reply_game(): # How to allow the user to try again
global Winner, humannum
while Winner != True:
print("Your answer was not correct, please try again")
humannum = int(input("Enter a number from 1 - 10> "))
calculator()
def calculator(): # This is to calculate, who wins the game
global humannum, computernum, Winner
if humannum == computernum:
print(f'The computer number was {computernum}')
print(f'Your number was {humannum}')
print("")
print("Therefore You have won ! ")
Winner = True
elif humannum <= computernum:
print("Your number was smaller than the computer")
reply_game()
elif humannum > computernum:
print("Your number was larger than the computers")
reply_game()
calculator()
Output:
Enter a number from 1 - 10> >? 3
Your number was smaller than the computer
Your answer was not correct, please try again
Enter a number from 1 - 10> >? 4
Your number was smaller than the computer
Your answer was not correct, please try again
Enter a number from 1 - 10> >? 6
The computer number was 6
Your number was 6
Therefore You have won !
References:
Why am I getting an UnboundLocalError when the variable has a value?
Related
So this is my random number guessing program I made. It asks the user to input two numbers as the bound, one high and one low, then the program will choose a number between those two. The user then has to try and guess the number chosen by the program. 1) How do I get it to ask the user if they would like to play again and upon inputting 'yes' the program starts over, and inputting 'no' the program ends? 2) How do I create an error trap that tells the user "Hey you didn't enter a number!" and ends the program?
def main(): # Main Module
print("Game Over.")
def introduction():
print("Let's play the 'COLD, COLD, HOT!' game.")
print("Here's how it works. You're going to choose two numbers: one small, one big. Once you do that, I'll choose a random number in between those two.")
print("The goal of this game is to guess the number I'm thinking of. If you guess right, then you're HOT ON THE MONEY. If you keep guessing wrong, than you're ICE COLD. Ready? Then let's play!")
small = int(input("Enter your smaller number: "))
large = int(input("Enter your bigger number: "))
print("\n")
return small, large
def game(answer):
c = int(input('Input the number of guesses you want: '))
counter = 1 # Set the value of the counter outside loop.
while counter <= c:
guess = int(input("Input your guess(number) and press the 'Enter' key: "))
if answer > guess:
print("Your guess is too small; you're ICE COLD!")
counter = counter + 1
elif answer < guess:
print("Your guess is too large; you're still ICE COLD!")
counter = counter + 1
elif answer == guess:
print("Your guess is just right; you're HOT ON THE MONEY!")
counter = c + 0.5
if (answer == guess) and (counter < c + 1):
print("You were burning hot this round!")
else:
print("Wow, you were frozen solid this time around.", "The number I \
was thinking of was: " , answer)
def Mystery_Number(a,b):
import random
Mystery_Number = random.randint(a,b) # Random integer from Python
return Mystery_Number # This function returns a random number
A,B = introduction()
number = Mystery_Number(A,B) # Calling Mystery_Number
game(number) # Number is the argument for the game function
main()
You'd first have to make game return something if they guess right:
def game(answer):
guess = int(input("Please put in your number, then press enter:\n"))
if answer > guess:
print("Too big")
return False
if answer < guess:
print("Too small")
return False
elif answer == guess:
print("Your guess is just right")
return True
Then, you'd update the 'main' function, so that it incorporates the new 'game' function:
def main():
c = int(input("How many guesses would you like?\n"))
for i in range(c):
answer = int(input("Your guess: "))
is_right = game(answer)
if is_right: break
if is_right: return True
else: return False
Then, you'd add a run_game function to run main more than once at a time:
def run_game():
introduction()
not_done = False
while not_done:
game()
again = input('If you would like to play again, please type any character')
not_done = bool(again)
Finally, for error catching, you'd do something like this:
try:
x = int(input())
except:
print('That was not a number')
import sys
sys.exit(0)
import random
import time
def closest_num(GuessesLog, CompNum):
return GuessesLog[min(range(len(GuessesLog)), key=lambda g: abs(GuessesLog[g] - CompNum))]
GameModeActive = True
while GameModeActive:
Guesses = None
GuessesLog = []
while not isinstance(Guesses, int):
try:
Guesses = int(input("How many guesses do you have?: "))
except ValueError:
print("Please enter a whole number")
print(" ")
CompNum = random.randint(1,99)
print(CompNum)
Players = None
while not isinstance(Players, int):
try:
Players = int(input("How many players are there?: "))
except ValueError:
print("Please enter a whole number")
print(" ")
NumberOfPlayers = []
for i in range(Players):
NumberOfPlayers.append(i+1)
NumberOfGuesses = []
for i in range(Guesses):
NumberOfGuesses.append(i+1)
print(NumberOfGuesses)
print(NumberOfPlayers)
print(len(NumberOfGuesses))
print(len(NumberOfPlayers))
for Guess in NumberOfGuesses:
if Guess != len(NumberOfGuesses):
print("ITS ROUND {}! GET READY!".format(Guess))
print(" ")
PlayersForRound = NumberOfPlayers
for Player in PlayersForRound:
print("It is Player {}'s Turn >>>".format(Player))
print(PlayersForRound)
print(NumberOfPlayers)
PlayerEntry = None
while not isinstance(PlayerEntry, int):
try:
PlayerEntry = int(input("Enter guess number {}: ".format(Guess)))
print(" ")
except ValueError:
print("Please enter a whole number")
print("CALCULATING YOUR RESULT!")
time.sleep(1)
print("***5***")
time.sleep(1)
print("***4***")
time.sleep(1)
print("***3***")
time.sleep(1)
print("***2***")
time.sleep(1)
print("***1***")
if PlayerEntry == CompNum:
print("Congratulations player {}, you have successfully guessed the number on round {}!".format(Player, Guess))
print(" ")
NumberOfPlayers.pop(Player-1)
if len(NumberOfPlayers) == 1:
print("Only {} Player remains".format(len(NumberOfPlayers)))
PlayersForRound
elif len(NumberOfPlayers) > 1:
print("Only {} Players remain".format(len(NumberOfPlayers)))
continue
elif PlayerEntry < CompNum:
print("Your guess was too low!")
print(" ")
GuessesLog.append(PlayerEntry)
continue
elif PlayerEntry > CompNum:
print("Your guess was too high!")
print(" ")
GuessesLog.append(PlayerEntry)
continue
if Guess == len(NumberOfGuesses):
print("ITS ROUND {}! THIS IS THE LAST ROUND! GOOD LUCK!".format(Guess))
print(" ")
print(NumberOfGuesses)
print(NumberOfPlayers)
print(len(NumberOfGuesses))
print(len(NumberOfPlayers))
PlayersForRound = NumberOfPlayers
for Player in PlayersForRound:
print("It is Player {}'s Turn >>>".format(Player))
PlayerEntry = None
while not isinstance(PlayerEntry, int):
try:
PlayerEntry = int(input("Enter guess number {}: ".format(Guess)))
print(" ")
except ValueError:
print("Please enter a whole number")
print("CALCULATING YOUR RESULT!")
time.sleep(1)
print("***5***")
time.sleep(1)
print("***4***")
time.sleep(1)
print("***3***")
time.sleep(1)
print("***2***")
time.sleep(1)
print("***1***")
if PlayerEntry == CompNum:
print("Congratulations player {}, you have successfully guessed the number on round {}!".format(Player, Guess))
print(" ")
NumberOfPlayers.pop(Player-1)
if len(NumberOfPlayers) == 1:
print("Only {} Player remains".format(len(NumberOfPlayers)))
elif len(NumberOfPlayers) > 1:
print("Only {} Players remain".format(len(NumberOfPlayers)))
continue
elif PlayerEntry < CompNum:
print("Your guess was too low!")
print(" ")
GuessesLog.append(PlayerEntry)
continue
elif PlayerEntry > CompNum:
print("Your guess was too high!")
print(" ")
GuessesLog.append(PlayerEntry)
continue
print("The closest guess was ", closest_num(GuessesLog, CompNum))
print(" ")
while True:
Answer = input("Would you like to play again? Y/N: ")
if Answer.lower() not in ('y', 'n'):
print("Please enter either Y for Yes, or N for No.")
else:
break
if Answer == 'y':
GameActiveMode = True
elif Answer == 'n':
GameActiveMode = False
print("Thankyou for playing ;)")
break
holdCall = str(input("Holding the console, press enter to escape."))
In my above code, when there are multiple players and multiple guesses(Rounds) then it works fine unless someone successfully guesses the code. If the code is guessed the code deletes the correct record from the player list. But for some reason fails to iterate over the rest of the list or if the correct guess comes from the second user it skips the next player altogether and moves onto the next round.
I have absolutely no idea why. Anyone have any ideas? Thanks in advance.
For example, if you run this in console and then have 3 guesses with 3 users, on the first player you guess incorrectly. On the second you guess correctly, it skips player 3 and goes straight to round 2. Despite only remove player 2 from the list after a correct guess.
Or if you guess it correctly the first time around it skips to the 3rd player?
You are keeping track of players in the current round using a list of player numbers. So, if you start with three players, PlayersForRound will start as [1,2,3].
You then proceed to loop over this list to give each player their turn by using for Player in PlayersForRound. However, PlayersForRound and NumberOfPlayers are the exact same list (not a copy), so when you remove a player from one, it is removed from both.
Once a player guesses correctly, you remove them from the list you were looping over with NumberOfPlayers.pop(Player-1). For example if the second player guesses correctly, you remove their "index" from the list and the resulting list is now [1,3].
However, because Python is still looping over that same list, player 3 never gets their turn, because their "index" is now in the position where the "index" of player 2 was a moment ago.
You should not modify the list you're looping over, this will result in the weird behaviour you are seeing. If you want to modify that list, you could write a while loop that conditionally increases an index into the list and checks whether it exceeds the length of the list, but there are nicer patterns to follow to achieve the same result.
As for naming, please refer to https://www.python.org/dev/peps/pep-0008/ - specifically, your variables like PlayersForRound should be named players_for_round, but more importantly, you should name the variables so that they mean what they say. NumberOfPlayers suggests that it is an integer, containing the number of players, but instead it is a list of player numbers, etc.
The selected bits of your code below reproduce the problem, without all the fluff:
# this line isn't in your code, but it amounts to the same as entering '3'
Players = 3
NumberOfPlayers = []
for i in range(Players):
NumberOfPlayers.append(i+1)
PlayersForRound = NumberOfPlayers
for Player in PlayersForRound:
# this line is not in your code, but amounts to the second player guessing correctly:
if Player == 2:
NumberOfPlayers.pop(Player-1)
if Player == 3:
print('this never happens')
# this is why:
print(PlayersForRound, NumberOfPlayers)
When you pop the list, you intervene in the for loop. Here, you can play with this and see yourself.
players = 3
player_list = []
for p in range(players):
player_list.append(p + 1)
for player in player_list:
print(player)
if player == 2:
print("popped:",player_list.pop(player-1))
Output
1
2
popped: 2
Im getting a syntax error for elif option ==2:. I was wondering what I need to do to fix it. I followed the pseudocode my professor gave us but it still won't run. I'm wondering if I shouldn't have used elif or maybe something about the indentation is off.
import random
print("Welcome to the guess my number program")
while True:
print("1. You guess the number")
print("2. You type a number and see if the computer can guess it")
print("3. Exit")
option = int(input("Please enter your number here: "))
if option ==1:
#generates a random number
mynumber = random.randint(1,11)
#number of guesses
count = 1
while True:
try:
guess = int(input("Guess a number between 1 and 10:"))
while guess < 1 or guess > 10:
guess = int(input("Guess a number between 1 and 10:")) # THIS LINE HERE
except:
print("Numbers Only")
continue
#prints if the number you chose is too low and adds 1 to the counter
if guess < mynumber:
print("The number you chose is too low")
count= count+1
#prints if the number you chose is too high and adds 1 to the counter
elif guess > mynumber:
print("The number you choose is too high")
count = count+1
#If the number you chose is correct it will tell you that you guessed the number and how many attempts it took
elif guess == mynumber:
print("You guessed it in " , count , "attempts")
break
elif option == 2:
number = int(input("Please Enter a Number: "))
count = 1
while True:
randomval = random.randint(1,11)
if (number < randomval):
print("Too high")
elif (number > randomval):
print("Too low")
count = count+1
elif (number==randomval):
print("The computer guessed it in" + count + "attempts. The number was" + randomval)
break
else:
break
The problem is simple. There is no continuity between if option == 1 and elif option == 2, because of the in between while loop. What you have to do is remove the el part of elif option == 2 and just write if option == 2.
I haven't tested the whole program myself. But at a glance, this should rectify the problem.
Please comment if otherwise.
I have the following code for a random number guessing game:
import random
number = random.randint(1,100)
name = input('Hi, Whats your name?')
print ("Well", name, "i am thinking of a number between 1 and 100, take a guess")
guess1 = input()
if guess1 == number:
print ("Good job, you got it!")
while guess1 != number:
if guess1 > number:
print ('your guess is too high')
if guess1 < number:
print ('your guess is too low')
which throws the error that > or < cannot be used between str and int.
What should I do so it doesn't trigger that error?
There are two errors in your code.
You need to convert the input for guess1 from a string (by default) to an integer before you can compare it to the number (an integer).
The while loop will never stop since you are not letting the user input another value.
Try this:
import random
number = random.randint(1,100)
name = input('Hi, Whats your name?')
print ("Well", name, "i am thinking of a number between 1 and 100, take a guess")
guess1 = int(input()) # convert input from string to integer
while guess1 != number:
if guess1 > number:
print ('your guess is too high. Try again.')
elif guess1 < number:
print ('your guess is too low. Try again.')
guess1 = int(input()) # asks user to take another guess
print("Good job, you got it!")
You can make use of a while loop here - https://www.tutorialspoint.com/python/python_while_loop.htm
The logic should be:
answer_is_correct = False
while not answer_is_correct :
Keep receiving input until answer is correct
I hope this works for you:
import random
myname = input('Hello, what is your name?')
print('Well',myname,'am thinking of a number between 1 and 100')
number = random.randint(1,100)
guess = 0
while guess < 4:
guess_number = int(input('Enter a number:'))
guess += 1
if guess_number < number:
print('Your guess is to low')
if guess_number > number:
print('Your guess is to high')
if guess_number == number:
print('Your guess is correct the number is',number)
break
if guess == 4:
break
print('The number i was thinking of is',number)
from random import randint
print("you wanna guess a number between A to B and time of guess:")
A = int(input("A:"))
B = int(input("B:"))
time = int(input("time:"))
x = randint(1, 10)
print(x)
while time != 0:
num = int(input("Enter: "))
time -= 1
if num == x:
print("BLA BLA BLA")
break
print("NOPE !")
if time == 0:
print("game over")
break
Code in Python 3 for guessing game:
import random
def guessGame():
while True:
while True:
try:
low, high = map(int,input("Enter a lower number and a higher numer for your game.").split())
break
except ValueError:
print("Enter valid numbers please.")
if low > high:
print("The lower number can't be greater then the higher number.")
elif low+10 >= high:
print("At least lower number must be 10 less then the higher number")
else:
break
find_me = random.randint(low,high)
print("You have 6 chances to find the number...")
chances = 6
flag = 0
while chances:
chances-=1
guess = int(input("Enter your guess : "))
if guess<high and guess>low:
if guess < find_me:
print("The number you have entered a number less then the predicted number.",end="//")
print("{0} chances left.".format(chances))
elif guess > find_me:
print("The number you have entered a number greater then the predicted number.",end="//")
print("{0} chances left.".format(chances))
else:
print("Congrats!! you have succesfully guessed the right answer.")
return
else:
print("You must not input number out of range")
print("{0} chances left.".format(chances))
print("The predicted number was {0}".format(find_me))
You can conditions within the while loop to check if its right. It can be done the following way.
import random
print('Hello! What is your name?')
myName = input()
number = random.randint(1, 100)
print('Well, ' + myName + ', I am thinking of a number between 1 and 100.')
inputNumber = int(raw_input('Enter the number')
while inputNumber != number:
print "Sorry wrong number , try again"
inputNumber = int(raw_input('Enter the number')
print "Congrats!"
from random import *
def play_game():
print("Let's play a number guessing game")
# Selecting a random number between 1 and 100
number = randint(1, 100)
choice = int(input("I am thinking of a number between 1 and 100. Could you guess what it is? "))
# Guide the user towards the right guess
# Loop will continue until user guesses the right number
while choice != number:
if choice < number:
choice = int(input("Too low. Can you try again? "))
elif choice > number:
choice = int(input("Too high. Can you try again? "))
continue_game = input("You guessed it right! Would you like to play it again? (Y/N) ")
# Restart the game if user wishes to play again
if continue_game == "Y":
print("--" * 42)
play_game()
else:
print("Thanks for playing :)")
exit(0)
play_game()
This question already has answers here:
Ask the user if they want to repeat the same task again
(2 answers)
Closed 4 years ago.
Basically it's a guessing game and I have literally all the code except for the last part where it asks if the user wants to play again. how do I code that, I use a while loop correct?
heres my code:
import random
number=random.randint(1,1000)
count=1
guess= eval(input("Enter your guess between 1 and 1000 "))
while guess !=number:
count+=1
if guess > number + 10:
print("Too high!")
elif guess < number - 10:
print("Too low!")
elif guess > number:
print("Getting warm but still high!")
elif guess < number:
print("Getting warm but still Low!")
guess = eval(input("Try again "))
print("You rock! You guessed the number in" , count , "tries!")
while guess == number:
count=1
again=str(input("Do you want to play again, type yes or no "))
if again == yes:
guess= eval(input("Enter your guess between 1 and 1000 "))
if again == no:
break
One big while loop around the whole program
import random
play = True
while play:
number=random.randint(1,1000)
count=1
guess= eval(input("Enter your guess between 1 and 1000 "))
while guess !=number:
count+=1
if guess > number + 10:
print("Too high!")
elif guess < number - 10:
print("Too low!")
elif guess > number:
print("Getting warm but still high!")
elif guess < number:
print("Getting warm but still Low!")
guess = eval(input("Try again "))
print("You rock! You guessed the number in" , count , "tries!")
count=1
again=str(input("Do you want to play again, type yes or no "))
if again == "no":
play = False
separate your logic into functions
def get_integer_input(prompt="Guess A Number:"):
while True:
try: return int(input(prompt))
except ValueError:
print("Invalid Input... Try again")
for example to get your integer input and for your main game
import itertools
def GuessUntilCorrect(correct_value):
for i in itertools.count(1):
guess = get_integer_input()
if guess == correct_value: return i
getting_close = abs(guess-correct_value)<10
if guess < correct_value:
print ("Too Low" if not getting_close else "A Little Too Low... but getting close")
else:
print ("Too High" if not getting_close else "A little too high... but getting close")
then you can play like
tries = GuessUntilCorrect(27)
print("It Took %d Tries For the right answer!"%tries)
you can put it in a loop to run forever
while True:
tries = GuessUntilCorrect(27) #probably want to use a random number here
print("It Took %d Tries For the right answer!"%tries)
play_again = input("Play Again?").lower()
if play_again[0] != "y":
break
Don't use eval (as #iCodex said) - it's risky, use int(x). A way to do this is to use functions:
import random
import sys
def guessNumber():
number=random.randint(1,1000)
count=1
guess= int(input("Enter your guess between 1 and 1000: "))
while guess !=number:
count+=1
if guess > (number + 10):
print("Too high!")
elif guess < (number - 10):
print("Too low!")
elif guess > number:
print("Getting warm but still high!")
elif guess < number:
print("Getting warm but still Low!")
guess = int(input("Try again "))
if guess == number:
print("You rock! You guessed the number in ", count, " tries!")
return
guessNumber()
again = str(input("Do you want to play again (type yes or no): "))
if again == "yes":
guessNumber()
else:
sys.exit(0)
Using functions mean that you can reuse the same piece of code as many times as you want.
Here, you put the code for the guessing part in a function called guessNumber(), call the function, and at the end, ask the user to go again, if they want to, they go to the function again.
I want to modify this program so that it can ask the user whether or not they want to input another number and if they answer 'no' the program terminates and vice versa. This is my code:
step=int(input('enter skip factor: '))
num = int(input('Enter a number: '))
while True:
for i in range(0,num,step):
if (i % 2) == 0:
print( i, ' is Even')
else:
print(i, ' is Odd')
again = str(input('do you want to use another number? type yes or no')
if again = 'no' :
break