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. (btw, yes I realize this part is a copy of my other question. This is a different problem in the same program, so I started it the same way.)
Anyways, I am having an issue with the last part of the program not taking any values. It is supposed to take the input for keep_playing and continue going if it is equal to 'y'. The issue is that it isn't actually making the variable equal anything(at least I don't think so.) So, whatever value I put in, it just prints the same response every time. Here is the small part of the code which isn't working, though I feel like it is something wrong with the rest of the code:
def keep_playing(attempts,keep_playing):
keep_playing = 'y'
if keep_playing == 'y':
guess(attempts)
keep_playing = str(input("Another game (y to continue)? "))
else:
print()
print("Thanks for playing")
return keep_playing
The expected output is:
Enter a number between 1 and 100, or 0 to quit: 4
Too low, try again It's 66 for testing purposes
Enter a number between 1 and 100, or 0 to quit: 67
Too high, try again It's 66 for testing purposes
Enter a number between 1 and 100, or 0 to quit: 66
Congratulations! You guessed the right number!
There were 2 attempts
Another game (y to continue)? y
Enter a number between 1 and 100, or 0 to quit: 0
You quit too early
The number was 79
Another game (y to continue)? n
Thanks for playing!
But the actual output is:
Enter a number between 1 and 100, or 0 to quit: 4
Too low, try again It's 66 for testing purposes
Enter a number between 1 and 100, or 0 to quit: 67
Too high, try again It's 66 for testing purposes
Enter a number between 1 and 100, or 0 to quit: 66
Congratulations! You guessed the right number!
There were 2 attempts
Another game (y to continue)? y
Enter a number between 1 and 100, or 0 to quit: 0
You quit too early
The number was 79
Another game (y to continue)? n
Another game (y to continue)? y
>>>
Notice how no matter what I do, it continues to run. The first part with the higher and lower works fine, however the bottom part just seems to break, and I don't know how to fix it. If anyone has any solutions that would be greatly appreciated.
Also, in case anyone wanted to see the whole thing, in case there was in issue with that, here it is:
import random
def main():
global attempts
attempts = 0
guess(attempts)
keep_playing(attempts,keep_playing)
def guess(attempts):
number = random.randint(1,100)
print('')
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 It's",number, "for testing purposes") #printing the number makes it easier to fix :/
attempts += 1
guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
elif guess > number:
print("Too high, try again It's",number, "for testing purposes")
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()
keep_playing = str(input("Another game (y to continue)? "))
return keep_playing
else:
print()
print("You quit too early")
print("The number was ",number)
keep_playing = str(input("Another game (y to continue)? "))
return keep_playing
def keep_playing(attempts,keep_playing):
keep_playing = 'y'
if keep_playing == 'y':
guess(attempts)
keep_playing = str(input("Another game (y to continue)? "))
else:
print()
print("Thanks for playing")
return keep_playing
main()
I notice a couple things here
There is some issue with the naming of your function, python thinks that keep_playing is the str variable keep_playing and not the function. In my code below I will rename the function keep_playing to keep_playing_game.
You need to pass in the parameters when you call the function keep_playing_game so the function knows what the user input and attempts are.
Why are you setting keep_playing = 'y' in the first line of your function def keep_playing_game(attempts,keep_playing)? If you remove this line, your program should run as expected based on the value the user enters and not what the function assigns keep_playing to.
I would recommend trying something like this
import random
def main():
global attempts
attempts = 0
guess(attempts)
# keep_playing(attempts,keep_playing) -> this line should be removed
def guess(attempts):
number = random.randint(1,100)
print('')
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 It's",number, "for testing purposes") #printing the number makes it easier to fix :/
attempts += 1
guess = int(input("Enter a number between 1 and 100, or 0 to quit: "))
elif guess > number:
print("Too high, try again It's",number, "for testing purposes")
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()
keep_playing = str(input("Another game (y to continue)? "))
return keep_playing_game(keep_playing, attempts)
else:
print()
print("You quit too early")
print("The number was ",number)
keep_playing = str(input("Another game (y to continue)? "))
return keep_playing_game(keep_playing, attempts)
def keep_playing_game(keep_playing, attempts):
if keep_playing == 'y':
guess(attempts)
else:
print()
print("Thanks for playing")
return
return None
main()
Related
I'm having issues with this random number guessing game. There are 2 issues: The first issue has to do with the counting of how many tries you have left. it should give you 3 changes but after the 2nd one it goes into my replay_input section where I am asking the user if they want to play again.
import random
# guess the # game
guess = input("Enter in your numerical guess. ")
random_number = random.randint(0, 10)
print(random_number) # used to display the # drawn to check if code works
number_of_guess_left = 3
# this is the main loop where the user gets 3 chances to guess the correct number
while number_of_guess_left > 0:
if guess != random_number:
number_of_guess_left -= 1
print(f"The number {guess} was an incorrect guess. and you have {number_of_guess_left} guesses left ")
guess = input("Enter in your numerical guess. ")
elif number_of_guess_left == 0:
print("You lose! You have no more chances left.")
else:
print("You Win! ")
break
The second part has to do with the replay input, I can't seem to get it to loop back to the beginning to restart the game.
replay_input = input("Yes or No ").lower()
if replay_input == "yes":
guess = input("Enter in your numerical guess. ")
The break statement exits a while loop. The code in the loop executes once, hits break at the end, and moves on to execute the code after the loop.
You can have the player replay the game by wrapping it in a function which I've called play_game below. The while True loop at the end (which is outside of play_game) will loop until it encounters a break statement. The player plays a game once every loop. The looping stops when they enter anything other than "yes" at the replay prompt which will make it hit the break statement.
import random
def play_game():
# guess the # game
guess = input("Enter in your numerical guess. ")
random_number = random.randint(0, 10)
print(random_number) # used to display the # drawn to check if code works
number_of_guess_left = 3
# this is the main loop where the user gets 3 chances to guess the correct number
while number_of_guess_left > 0:
if guess != random_number:
number_of_guess_left -= 1
print(f"The number {guess} was an incorrect guess. and you have {number_of_guess_left} guesses left ")
guess = input("Enter in your numerical guess. ")
elif number_of_guess_left == 0:
print("You lose! You have no more chances left.")
else:
print("You Win! ")
while True:
play_game()
replay_input = input("Yes or No ").lower()
if replay_input != "yes":
break
Please focus on the basics first before posting the questions here. Try to debug with tools like https://thonny.org/. However, I updated your code, just check.
import random
# guess the # game
random_number = random.randint(0, 10)
print(random_number)
# don't forget to convert to int
guess = int(input("Enter in your numerical guess. "))
number_of_guess_left = 3
# this is the main loop where the user gets 3 chances to guess the correct number
while number_of_guess_left > 0:
number_of_guess_left -= 1
if guess == random_number:
print("You Win! ")
break
else:
if number_of_guess_left == 0:
print("You lose! You have no more chances left.")
break
else:
print(f"The number {guess} was an incorrect guess. and you have {number_of_guess_left} guesses left ")
guess = int(input("Enter in your numerical guess. "))
I have a class project, where I am making a number guessing game. I have the following requirements:
#1. A main() function that holds the primary algorithm, but itself only passes information among other functions. main() must have the caller for random_int()
#2. A function called in main() (not nested in main()!) that compares the user's guess to the number from random_int() and lets the user know if it was too high or too low.
#3. A function called in main() that asks the user for a new guess.
#4. A function that prints out a string letting the user know that they won.
#5. Tell the user how many guesses it took them to get the correct answer.
I am currently having an issue trying to take the user inputted value "guess" and compare it with the value of a randomly generated integer "random_int" in a while loop in the function def high_low():
def random_int(size): #Generates a random integer from given parameters (size)
return randrange(1, size+1)
def new_guess(): #Prompts the user to enter an integer as their guess
guess = (input("Enter your guess (between 1 - 1000): "))
return guess
def high_low(random_int, new_guess): #Lets the user know if the number they guessed is too high or too low
while guess != random_int: #While loop to continue until user guesses correct number
if guess > random_int:
print("The number you guessed is too high, guess again.")
elif guess < random_int:
print("The number you guessed is too low, guess again.")
attempts+=1
I either get the error "guess not defined" or '>' not supported between instances of 'function' and 'function'
Here is all of the code for context, note though that most of it below what I have posted above is pseudocode for the purposes of figuring out the logic of the game's function, and I have not yet gone through with debugging.
#Python number guessing game
#Import randrange module
from random import randrange
#Initialize variables
attempts = 0
def random_int(size): #Generates a random integer from given parameters (size)
return randrange(1, size+1)
def new_guess(): #Prompts the user to enter an integer as their guess
guess = (input("Enter your guess (between 1 - 1000): "))
return guess
def high_low(random_int, new_guess): #Lets the user know if the number they guessed is too high or too low
while guess != random_int: #While loop to continue until user guesses correct number
if guess > random_int:
print("The number you guessed is too high, guess again.")
elif guess < random_int:
print("The number you guessed is too low, guess again.")
attempts+=1
new_guess()
def win(random_int, new_guess): #Prints that the answer is correct, along with the number of guesses it took
while guess == random_int:
if attempts >= 2: #If it took the user more than 1 attempt, uses "guesses" for proper grammar
print("You guessed the correct number, you win! It took you ", str(attempts()), " guesses.")
input("Would you like to play again? (Y/N): ")
if input == Y: #If user inputs "Y", runs the program again
main()
elif input == N: #If user inputs "N", terminates the program
break
elif attempts < 2: #If it took the user only 1 attempt, uses "guess" for proper grammar
print("You guessed the correct number, you win! It took you ", str(attempts()), " guess.")
input("Would you like to play again? (Y/N): ")
if input == Y: #If user inputs "Y", runs the program again
main()
elif input == N: #If user inputs "N", terminates the program
break
def main(): #Function to call all functions in the program
random_int(1000)
new_guess()
high_low(random, new_guess)
win()
main() #Calls the "main" function, runs the program
The code has a couple of issues I'll walk through all of them with an explanation so that we understand the reason why they happen at all. First we'll address all errors one by one.
Error-1
The first error on executing the code is '>' not supported between instances of 'function' and 'function'.
To understand that, notice the difference between Call-1 and Call-2 in below example code:
def f1():
return 1
def f2():
return 2
def less_than(n1, n2):
return n1 < n2
less_than(f1, f2) # Call-1: this will not work and give you error similar to what you get
less_than(f1(), f2()) # Call-2: this works
Call-1 passes the function itself, whereas Call-2 passes result of f1() and f2(), which are integers and can be compared by <.
In the code the main() needs to be rewritten like this:
def main(): #Function to call all functions in the program
r = random_int(1000)
n = new_guess()
high_low(r, n)
win()
Error-2
After above fix, executing will give another error:
NameError: name 'guess' is not defined
It means guess has not been defined. That's fixed by re-writing high_low() again like this. Notice the name new_guess replaced with guess. One is the function and other is the variable.
def high_low(random_int, guess): #Lets the user know if the number they guessed is too high or too low
while guess != random_int: #While loop to continue until user guesses correct number
if guess > random_int:
print("The number you guessed is too high, guess again.")
elif guess < random_int:
print("The number you guessed is too low, guess again.")
attempts+=1
guess = new_guess()
Error-3
Again running would give this error:
TypeError: '>' not supported between instances of 'str' and 'int'
Fix is simple, the new_guess() function needs to convert input to int as calling input returns everything as string.
def new_guess(): #Prompts the user to enter an integer as their guess
guess = int(input("Enter your guess (between 1 - 1000): "))
return guess
Error-4
Last error would be:
UnboundLocalError: local variable 'attempts' referenced before assignment
This simply means no value has been set to attempts before using it in attempts += 1
This gets fixed again by updating high_low and adding attempts = 0:
def high_low(random_int, guess): #Lets the user know if the number they guessed is too high or too low
attempts = 0
while guess != random_int: #While loop to continue until user guesses correct number
if guess > random_int:
print("The number you guessed is too high, guess again.")
elif guess < random_int:
print("The number you guessed is too low, guess again.")
attempts+=1
guess = new_guess()
Final code looks like this:
from random import randrange
#Initialize variables
attempts = 0
def random_int(size): #Generates a random integer from given parameters (size)
return randrange(1, size+1)
def new_guess(): #Prompts the user to enter an integer as their guess
guess = int(input("Enter your guess (between 1 - 1000): "))
return guess
def high_low(random_int, guess): #Lets the user know if the number they guessed is too high or too low
attempts = 0
while guess != random_int: #While loop to continue until user guesses correct number
if guess > random_int:
print("The number you guessed is too high, guess again.")
elif guess < random_int:
print("The number you guessed is too low, guess again.")
attempts+=1
guess = new_guess()
def win(random_int, new_guess): #Prints that the answer is correct, along with the number of guesses it took
while guess == random_int:
if attempts >= 2: #If it took the user more than 1 attempt, uses "guesses" for proper grammar
print("You guessed the correct number, you win! It took you ", str(attempts()), " guesses.")
input("Would you like to play again? (Y/N): ")
if input == Y: #If user inputs "Y", runs the program again
main()
elif input == N: #If user inputs "N", terminates the program
break
elif attempts < 2: #If it took the user only 1 attempt, uses "guess" for proper grammar
print("You guessed the correct number, you win! It took you ", str(attempts()), " guess.")
input("Would you like to play again? (Y/N): ")
if input == Y: #If user inputs "Y", runs the program again
main()
elif input == N: #If user inputs "N", terminates the program
break
def main(): #Function to call all functions in the program
r = random_int(1000)
n = new_guess()
high_low(r, n)
win()
main() #Calls the "main" function, runs the program
your high_low function has no reference to a variable named guess. I think the solution is to just add the line guess = new_guess() right before the while loop.
This question already has answers here:
Repeat Game - Python Rock, Paper, Scissors
(2 answers)
Closed 1 year ago.
number = int(input("please choose your number: "))
while number != number_to_guess:
if number > number_to_guess:
number = int(input("Your guess is wrong it was bigger then the generated number, try again: "))
continue
if number < number_to_guess :
number = int(input("Your guess was wrong it was smaller then the generated number, try again: "))
if number == number_to_guess:
print("Congrats you won")
restart = input("Do you want to play again? if yes type y, if not you can close the window \n")
while restart not in ["y"]:
restart = input("please type y or close the window \n")
i want it as the title suggest to restart after the user types y, and i want it to always start with number input"choose your..." but i have no idea of how to do that
You can write the code in a function, and then, if you want to restart, call that function again
def game():
number = int(input("please choose your number: "))
number_to_guess = 5
while number != number_to_guess:
if number > number_to_guess:
number = int(input("Your guess is wrong it was bigger then the generated number, try again: "))
continue
if number < number_to_guess :
number = int(input("Your guess was wrong it was smaller then the generated number, try again: "))
if number == number_to_guess:
print("Congrats you won")
restart = input("Do you want to play again? if yes type y, if not you can close the window \n")
if restart == "y": #restart the game
game()
while restart not in ["y"]:
restart = input("please type y or close the window \n")
# main code
game()
We can use functions or a while loop for this.
with functions,
def game():
#implement game here
number = input()
#other stuff
while True:
game()
restart = input()
if restart != 'y':
break # exit game
Note: this is pretty basic logic, refer to the tutorials here for more information on functions and loops.
I need help changing the range and showing the user what the range is so they know if they are closer or not. I have given the description I have been given. On what I need to do . I have given the code that I have come up wit so far. Let me know if you need anything else from me.
Step 6 – Guiding the user with the range of values to select between
Add functionality so that when displaying the guess prompt it will display the current range
to guess between based on the user’s guesses accounting for values that are too high and too
low. It will start out by stating What is your guess between 1 and 100, inclusive?, but as
the user guesses the range will become smaller and smaller based on the value being higher
or lower than what the user guessed, e.g., What is your guess between 15 and 32,
inclusive? The example output below should help clarify.
EXAMPLE
----------------
What is your guess between 1 and 44 inclusive? 2
Your guess was too low. Guess again.
import random
import sys
def main():
print("Assignment 6 BY enter name.")
welcome()
play()
#Part 1
def welcome():
print("Welcome to the guessing game. I have selected a number between 1 and 100 inclusive. ")
print("Your goal is to guess it in as few guesses as possible. Let’s get started.")
print("\n")
def play():
''' Plays a guessing game'''
number = int(random.randrange(1,10))
guess = int(input("What is your guess between 1 and 10 inclusive ?: "))
number_of_guess = 0
while guess != number :
(number)
#Quit
if guess == -999:
print("Thanks for Playing")
sys.exit(0)
#Guessing
if guess < number:
if guess < number:
guess = int(input("Your guess was too low. Guess Again: "))
number_of_guess += 1
elif guess not in range(1,11):
print("Invalid guess – out of range. Guess doesn’t count. : ")
guess = int(input("Guess Again: "))
else:
guess = input("Soemthing went wrong guess again: ")
if guess > number:
if guess > number:
guess = int(input("Your guess was too high. Guess Again: "))
number_of_guess += 1
elif guess not in range(1,11):
print("Invalid guess – out of range. Guess doesn’t count. : ")
guess = int(input("Guess Again: "))
else:
guess = input("Soemthing went wrong guess again: ")
#Winner
if guess == number :
number_of_guess += 1
print("Congratulations you won in " + str(number_of_guess) + " tries!")
again()
def again():
''' Prompts users if they want to go again'''
redo = input("Do you want to play again (Y or N)?: ")
if redo.upper() == "Y":
print("OK. Let’s play again.")
play()
elif redo.upper() == "N":
print("OK. Have a good day.")
sys.exit(0)
else:
print("I’m sorry, I do not understand that answer.")
again()
main()
What you'll need is a place to hold the user's lowest and highest guess. Then you'd use those for the range checks, instead of the hardcoded 1 and 11. With each guess, if it's a valid one, you then would compare it to the lowest and highest values, and if it's lower than the lowest then it sets the lowest value to the guess, and if it's higher than the highest it'll set the highest value to the guess. Lastly you'll need to update the input() string to display the lowest and highest guesses instead of a hardcoded '1' and '10'.
You need to simplify a lot your code. Like there is about 6 different places where you ask a new value, there sould be only one, also don't call method recursivly (call again() in again()) and such call between again>play>again.
Use an outer while loop to run games, and inside it an inner while loop for the game, and most important keep track of lower_bound and upper_bound
import random
import sys
def main():
print("Assignment 6 BY enter name.")
welcome()
redo = "Y"
while redo.upper() == "Y":
print("Let’s play")
play()
redo = input("Do you want to play again (Y or N)?: ")
def welcome():
print("Welcome to the guessing game. I have selected a number between 1 and 100 inclusive. ")
print("Your goal is to guess it in as few guesses as possible. Let’s get started.\n")
def play():
lower_bound, upper_bound = 0, 100
number = int(random.randrange(lower_bound, upper_bound))
print(number)
guess = -1
number_of_guess = 0
while guess != number:
guess = int(input(f"What is your guess between {lower_bound} and {upper_bound - 1} inclusive ?: "))
if guess == -999:
print("Thanks for Playing")
sys.exit(0)
elif guess not in list(range(lower_bound, upper_bound)):
print("You're outside the range")
continue
number_of_guess += 1
if guess < number:
print("Your guess was too low")
lower_bound = guess
elif guess > number:
print("Your guess was too high")
upper_bound = guess
print("Congratulations you won in", number_of_guess, "tries!")
import random
print"hello what is your name?"
name = raw_input()
print"hello", name
print"wanna play a game? y, n"
choice = raw_input()
if choice =='y':
print'good lets start a number guessing game'
elif choice =='n':
print'maybe next time'
exit()
random.randint(1,10)
number = random.randint(1,10)
print'pick a number between 1-10'
numberofguesses = 0
guess = input()
while numberofguesses < 10:
if guess < number:
print"too low"
elif guess > number:
print"too high"
elif guess == number:
print'your correct the number is', number
break
if guess == number:
print'CONGRATS YOU WIN THE GAME'
when i enter my guess into the program it only gives me one output for example
i enter 8
programs output is "too high"
but when i guess again the output is blank, how do i fix this?
hello what is your name?
ed
hello ed
wanna play a game? y, n
y
good lets start a number guessing game
pick a number between 1-10
2
too low
>>> 5
5
>>> 3
3
>>> 2
2
>>>
I think this is what you want:
numberofguesses = 0
while numberofguesses < 10:
guess = input() #int(raw_input("Pick a number between 1 and 10: ")) would be much better here.
numberofguesses+=1
if guess < number:
print "too low"
elif guess > number:
print "too high"
elif guess == number:
print 'your correct the number is', number
break
With your version of the code, you guess once. If you're wrong, your program tries the same guess over and over again forever (assuming your break was actually supposed to be indented in the elif). You might be typing new guesses into the terminal, but your program never sees them. If the break was actually in the correct place in your code, then you guess once and whether write or wrong it exits the loop right away.
your break is outside of your ifstatement
It will execute while loop one time and break no matter what