Python Warm / Cold Declaring Variable outside while loop - python

I'm writing a simple warmer / colder number guessing game in Python.
I have it working but I have some duplicated code that causes a few problems and I am not sure how to fix it.
from __future__ import print_function
import random
secretAnswer = random.randint(1, 10)
gameOver = False
attempts = 0
currentGuess = int(input("Please enter a guess between 1 and 10: "))
originalGuess = currentGuess
while gameOver == False and attempts <= 6:
currentGuess = int(input("Please enter a guess between 1 and 10: "))
attempts += 1
originalDistance = abs(originalGuess - secretAnswer)
currentDistance = abs(currentGuess - secretAnswer)
if currentDistance < originalDistance and currentGuess != secretAnswer:
print("Getting warmer")
elif currentDistance > originalDistance:
print("Getting colder")
if currentDistance == originalDistance:
print("You were wrong, try again")
if currentGuess == secretAnswer or originalGuess == secretAnswer:
print("Congratulations! You are a winner!")
gameOver = True
if attempts >= 6 and currentGuess != secretAnswer:
print("You lose, you have ran out of attempts.")
gameOver = True
print("Secret Answer: ", secretAnswer)
print("Original Dist: ", originalDistance)
print("Current Dist: ", currentDistance)
It asks for input before I enter the loop, which is to allow me to set an original guess variable helping me to work out the distance from my secret answer.
However, because this requires input before the loop it voids any validation / logic I have there such as the if statements, then requires input directly after this guess, now inside the loop.
Is there a way for me to declare originalGuess inside the loop without it updating to the user input guess each iteration or vice versa without duplicating currentGuess?
Thanks

There doesn't seem to be a need to ask the user before you enter the loop... You can just check if guesses = 1 for the first guess...
gameOver=False
guesses = 0
while not gameOver:
guesses += 1
getUserInput
if guesses = 1 and userInput != correctAnswer:
print "try again!"
checkUserInput
print "good job!, it took you {} guesses!".format(guesses)

Related

How do I break out of my while loop without using the most popular functions?(sys.exit,break,etc.)

I am making a program that generates a random number and asks you to guess the number out of the range 1-100. Once you put in a number, it will generate a response based on the number. In this case, it is Too high, Too low, Correct, or Quit too soon if the input is 0, which ends the program(simplified, but basically the same thing).
It counts the number of attempts based on how many times you had to do the input function, and it uses a while loop to keep asking for the number until you get it correct. The problem that I am facing is that I have to make it break out of the while loop once the guess is either equal to the random number or 0. This normally isn't an issue, because you could use sys.exit() or some other function, but according to the instructions I can't use break, quit, exit, sys.exit, or continue. The problem is most of the solutions I've found for breaking the while loop implement break, sys.exit, or something similar and I can't use those. I used sys.exit() as a placeholder, though, so that it would run the rest of the code, but now I need to figure out a way to break the loop without using it. This is my code:
import random
import sys
def main():
global attempts
attempts = 0
guess(attempts)
keep_playing(attempts)
def guess(attempts):
number = random.randint(1,100)
guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
while guess != 0:
if guess != number:
if guess < number:
print("Too low, try again")
attempts += 1
guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
elif guess > number:
print("Too high, try again")
attempts += 1
guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
else:
print()
print("Congratulations! You guessed the right number!")
print("There were", attempts,"attempts")
print()
#Ask if they want to play again
sys.exit()#<---- using sys.exit as a placeholder currently
else:
print()
print("You quit too early")
print("The number was ",number,sep='')
#Ask if they want to play again
sys.exit()#<----- using sys.exit as a placeholder currently
def keep_playing(attempts):
keep_playing = 'y'
if keep_playing == 'y' or keep_playing == 'n':
if keep_playing == 'y':
guess(attempts)
keep_playing = input("Another game (y to continue)? ")
elif keep_playing == 'n':
print()
print("You quit too early")
print("Number of attempts", attempts)
main()
If anyone has any suggestions or solutions for how to fix this, please let me know.
Try to implement this solution to your code:
is_playing = True
while is_playing:
if guess == 0:
is_playing = False
your code...
else:
if guess == number:
is_playing = False
your code...
else:
your code...
Does not use any break etc. and It does breaks out of your loop as the loop will continue only while is_playing is True. This way you will break out of the loop when the guess is 0 (your simple exit way) or when the number is guessed correctly. Hope that helps.
I am not a fan of global variables but here it's your code with my solution implemented:
import random
def main() -> None:
attempts = 0
global is_playing
is_playing = True
while is_playing:
guess(attempts)
keep_playing()
def guess(attempts: int) -> None:
number = random.randint(1,100)
print(number)
is_guessing = True
while is_guessing:
attempts += 1
guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
if guess == 0:
is_guessing = False
print("\nYou quit too early.")
print("The number was ", number,sep='')
else:
if guess == number:
is_guessing = False
print("\nCongratulations! You guessed the right number!")
print("There were", attempts, "attempts")
else:
if guess < number:
print("Too low, try again.")
elif guess > number:
print("Too high, try again.")
def keep_playing() -> None:
keep_playing = input('Do you want to play again? Y/N ')
if keep_playing.lower() == 'n':
global is_playing
is_playing = False
main()
TIP:
instead
"There were", attempts, "attempts"
do: f'There were {attempts} attempts.'

Local Assignment Error in Number Guessing Game [duplicate]

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?

How can I get two variables to hold the amount of higher than and lower than guesses?

I am creating a game in which the computer selects a random number 1-10
Then the user guesses the number until they get it right.
The trouble I am having is that when the users enter the wrong answer the variables high or low should be updated, but it just continues looping until the user does enter the right answer. Which causes high and low to always be at 0.
Any ideas? I know there is probably something wrong with the way I am looping?
Any pushes in the right direction would be great!
# module to generate the random number
import random
def randomNum():
selection = random.randint(0,9)
return selection
# get the users choices
def userGuess():
correct = True
while correct:
try:
userPick = int(input('Please enter a guess 1-10: '))
if userPick < 1 or userPick >10:
raise ValueError
except ValueError:
print('Please only enter a valid number 1 - 10')
continue
return userPick
# define main so we can play the game
def main():
correctNum = randomNum()
guess = userGuess()
high = 0
low = 0
if guess != correctNum:
print('uhoh try again!')
guess=userGuess()
elif guess > correctNum:
print('That guess is too high!')
high = high + 1
elif guess < correctNum:
print('That guess is too low')
low = low + 1
else:
print('You win!')
# the outcome of the game:
print('Guesses too high:', high)
print('Guesses too low:',low)
print('Thank you for playing!')
main()
Try modifying your main function :
def main():
correctNum = randomNum()
guess = userGuess()
high = low = 0 # nifty way to assign the same integer to multiple variables
while guess != correctNum: # repeat until guess is correct
if guess > correctNum:
print('That guess is too high!')
high = high + 1
else:
print('That guess is too low')
low = low + 1
print('Try again!')
guess=userGuess()
print('You win!')
# the outcome of the game:
print('Guesses too high:', high)
print('Guesses too low:',low)
print('Thank you for playing!')
Also, be careful with random.randint(0,9) : this will give a number between 0-9 (including 0 and 9, but never 10)!
You want to be doing random.randint(1, 10)
# module to generate the random number
import random
def get1to10():
selection = random.randint(1,10)
return selection
# get the users choices
def userGuess():
correct = True
while correct:
try:
userPick = int(input('Please enter a guess 1-10: '))
if userPick < 1 or userPick >10:
raise ValueError
except ValueError:
print('Please only enter a valid number 1 - 10')
continue
return userPick
# define main so we can play the game
def main():
correctNum = get1to10()
guess = 0
high = 0
low = 0
# use a while loop to collect user input until their answer is right
while guess != correctNum:
guess = userGuess()
# use if statements to evaluate if it is < or >
if guess > correctNum:
print('This is too high!')
high = high + 1
continue
# use continue to keep going through the loop if these are true
elif guess < correctNum:
print('this is too low!')
low = low + 1
continue
else:
break
# the outcome of the game:
print('----------------------')
print('Guesses too high:', high)
print('Guesses too low:',low)
print('The correct answer was:', '*',correctNum,'*', sep = '' )
print('Thank you for playing!')
print('---------------------')
main()
I found this solution to work well for what I needed!
Thank you everyone who answered this post!
You can try using a dictionary:
guesses = {'Higher': [],
'Lower': [],
'Correct': False,
} # A Dictionary variable
def add_guess(number, correct_number):
if number > correct_number:
guesses['Higher'].append(number)
elif number < correct_number:
guesses['Lower'].append(number)
else:
guesses['Correct'] = True
return guesses
add_guess(number=5, correct_number=3) # Higher
add_guess(10, 3) # Higher
add_guess(2, 3) # Lower
# Correct is False, and higher has the numbers (10, 5) while lower has the numbers (2)
print(guesses)
add_guess(3, 3) # Correct should now be True
print(guesses)
This, of course, isn't the entire code but should point you in the right direction. There is a ton of resources on python dictionaries online.

How to get my random number guessing game to loop again upon user input and how to create an error trap?

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)

My Guess The Number Game Will Not Loop Back to Beginning

import random
control = True
main = True
count = 0
user = input("Would you like to play Guess The Number?")
if (user == "yes"):
while (control == True):
randgen = random.randrange(0, 100)
print("Guess a random number")
while main == True:
number = int(input())
if (number == randgen):
print("Great Job you guessed the correct number")
print("You have tried ", count, "time(s)")
main = False
control = False
if (number < randgen):
count += 1
print("Your number is smaller than the random number")
print("You are at ", count, "trie(s)")
main = True
if (number > randgen):
count += 1
print("Your number is larger than the random number")
print("You are at ", count, "trie(s)")
main = True
again = int(input("Would you like to play again?1 for yes and 2 for no."))
if (again == 1):
control = True
user = ("yes")
if (again == 2):
control = False
print ("Ok bye bye")
##user ("no")
if (user == "no"):
print ("OK then Bye")
This Code works except for the part that when I want to play again it does not work. I have a coding background in java that's why I know some code but I made the guess the number game in java and I cannot figure out whats wrong with my python version(posted above).
Please make these changes:
if (again == 1):
control = True
main=True
user = ("yes")

Categories