I am new to Python and writing a program for a number guessing game. Here's the code:
import random
import math
def guessing_game_func():
name = input("Enter your name: ")
print("Welcome ", name)
lower_bound = 0
upper_bound = 50
#generating random number between 0 and 50
random_number = random.randint(lower_bound, upper_bound)
min_guessing_num = int(math.log(upper_bound - lower_bound + 1, 2))
print("INSTRUCTION: Guess a number between 0 and 50"
"\nHOT means you are close to the correct number and COLD means you are far from it")
print("You have only ", round(min_guessing_num), "tries")
#initializing number of guesses
count = 0
while count < min_guessing_num:
count += 1
guess = int(input("Guess a number: "))
if random_number == guess:
print("Congratulations. You guessed correctly after", count, "tries")
break
elif random_number > guess:
print("Hot")
elif random_number < guess:
print("Cold")
if count >= min_guessing_num:
print("Fail! The number is", random_number)
decision = input("Do you wish to play again? YES or NO").lower()
while decision == "yes":
guessing_game_func()
#if decision == "yes":
#guessing_game_func()
if decision == "no":
print("Close IDE")
guessing_game_func()
When I run this code, in the case where the user selects No, the game starts again but I do not want it to.
I just want it to print Close IDE and that should be it. However, the game starts again and I know this is because I am calling the function after it, but if I do not do that, then nothing will happen. What I mean by this is that, the code will run and all I'll see is Process finished with exit code 0
How do I fix this please?
The problem you have is with the loop that calls your function recursively:
decision = input("Do you wish to play again? YES or NO").lower()
while decision == "yes":
guessing_game_func()
if decision == "no":
print("Close IDE")
You have the recursive call which effectively implements a loop, and a while loop around that. When the inner call returns, remember that decision does not change within the outer function's while loop. That means that another call will be made and the loop will continue forever.
The simple solution is to decide whether you want to iterate via loop or recursion. I would recommend the former, but since you've already chosen the latter, just replace the while loop with a simple if:
decision = ""
while decision not in {"yes", "no"}:
decision = input("Do you wish to play again? YES or NO").lower()
if decision == "yes":
guessing_game_func()
else:
print("Close IDE")
Mad Physicist's answer covers the why does this happen and suggests a simple fix. However, I'd discourage you from using recursion to implement a replayed game. Instead, move the logic that decides whether to replay a game outside the function that implements the game logic.
def guessing_game_func():
...
while count < min_guessing_num:
...
# The function ends immediately after this while loop
# Now we're OUTSIDE the function
# Initialize decision to "yes", so the while loop is entered by default
decision = "yes"
while decision == "yes":
guessing_game_func()
decision = input("Do you wish to play again? YES or NO").lower()
if decision == "no":
print("Close IDE")
This way, you aren't limited to the recursion limit and can replay as many times as you like, since the next call of guessing_game_func only happens after the first call has ended.
I'm not sure why you want to print Close IDE only when "no" is entered -- what if decision is something other than "yes" and "no"? If you want to force decision to be one of those two options, you can pop it in another while loop, as shown in Asking the user for input until they give a valid response:
while decision == "yes":
guessing_game_func()
while True:
decision = input("Do you wish to play again? YES or NO").lower()
if decision in ("yes", "no"):
break # Acceptable input, so break out of the infinite loop
# Close IDE can be unguarded by an `if`, because the only way to get here is to enter "no" when asked for decision
print("Close IDE")
import random
import math
def guessing_game_func():
name = input("Enter your name: ")
print("Welcome ", name)
lower_bound = 0
upper_bound = 50
#generating random number between 0 and 50
random_number = random.randint(lower_bound, upper_bound)
min_guessing_num = int(math.log(upper_bound - lower_bound + 1, 2))
print("INSTRUCTION: Guess a number between 0 and 50"
"\nHOT means you are close to the correct number and COLD means you are far from it")
print("You have only ", round(min_guessing_num), "tries")
#initializing number of guesses
count = 0
while count < min_guessing_num:
count += 1
guess = int(input("Guess a number: "))
if random_number == guess:
print("Congratulations. You guessed correctly after", count, "tries")
break
elif random_number > guess:
print("Hot")
elif random_number < guess:
print("Cold")
if count >= min_guessing_num:
print("Fail! The number is", random_number)
decision = input("Do you wish to play again? YES or NO").lower()
while decision == "yes":
guessing_game_func()
break
#if decision == "yes":
#guessing_game_func()
if decision == "no":
print("Close IDE")
guessing_game_func()
Try this . I have added break after you call your function.now it works.
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 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!")
I want to add some code to the end of this guessing game which will ask the user if they want to play again. If they say yes, the program will, I suppose, just run again from the beginning. I've tried multiple ideas, but none have worked. The closest was another if loop at the end. Thank you! x
print("Welcome to this guessing game!")
import random
x = random.randrange(50)
guess = int(input("I've picked an integer between 1 to 99. Guess what it is: "))
while x != "guess":
print
if guess < x:
print("Your guess is too low!")
guess = int(input("Guess again:"))
elif guess > x:
print("Your guess is too high!")
guess = int(input("Guess again:"))
else:
print ("You guessed the right number!")
Something like:
while True:
your code
if input("Continue? Y/N: ").lower() not in {"y", "yes"}:
break
At the end of every play, this gets input from the user, converts it to lower case, and sees if it's "y" or "yes". If it's not, the game breaks out of the loop, i.e. quits. Otherwise it keeps looping.
You could wrap your game in a function. And then on user say "yes", you invoke the function. And at the end of you game, reask the samequestion.
This is what function is made for.
Pseudo code:
function askUser(){
'Do you want to play'=>yes: launchGame, no:print("ok bye bye")
}
function myGame(){
//your game
askUser()
}
for example
import random
something="yes"
while(something == "yes"):
#your code...
#....
#from your code
else:
print ("You guessed the right number!")
something=input("Do you want to play again? (yes/no)")#input return str? I use raw_input all the time in p2.7
and this:
while x != "guess":
why to guess use " "?
x = random.randrange(50) so x never being a string "guess" its like while True: or while 1:
print("Welcome to this guessing game!")
import random
x = random.randrange(50)
guess = int(input("I've picked an integer between 1 to 99. Guess what it is: "))
while True:
if guess < x:
print("Your guess is too low!")
guess = int(input("Guess again:"))
elif guess > x:
print("Your guess is too high!")
guess = int(input("Guess again:"))
else:
print ("You guessed the right number!")
break
You are learning about the basics of python too little advice to read more books
x is the type of int and guess you use "" included "guess" he is not a variable name and become a string
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
import random
computer=random.randint(1, 100)
guess=int(input("guess the number"))
if guess > 100:
print("your guess is too high")
elif guess < 1:
print("your guess is too low")
elif guess==computer:
print("well done!")
else:
print("you\'re wrong, guess again")
This is my current code. it's game where the computer randomly chooses a number and the player has to guess it. i have tried but i don't know how to ask the player if they want to play again and if they say yes how to restart it.
Wrap the game code to function and use while True to call it again and again
import random
def play():
computer=random.randint(1, 100)
guess=int(input("guess the number"))
if guess > 100:
print("your guess is too high")
elif guess < 1:
print("your guess is too low")
elif guess==computer:
print("well done!")
else:
print("you\'re wrong, guess again")
while True:
answer = input("do you want to play?")
if answer == 'yes':
play()
elif answer == 'no':
break
else:
print("dont understand")
Put all the if-else statements within one big while loop that keeps looping until the user guesses the number correctly. Then, after each losing outcome, give the user another chance to guess the number so that the loop has a chance to reevaluate the guess with the next iteration. In my modification below I decided to leave the last if-else statement outside of the loop because when the user guesses correctly, the code will break out of the loop to check if the guess is correct. Of course in this scenario it has to be correct so the user is told that he or she is right and the program terminates.
import random
computer=random.randint(1, 100)
guess=int(input("guess the number\n"))
while(guess != computer):
if guess > 100:
print("your guess is too high\n")
guess=int(input("guess the number again\n"))
elif guess < 1:
print("your guess is too low\n")
guess=int(input("guess the number again\n"))
if guess==computer:
print("well done!\n")
Just an overview of how you can do it.
initialize a variable play_again = "yes"
Place a while check on play_again:
while play_again == "yes":
Enclose all if statements and guess input in the while loop
Read the user input in a variable within but at the end of the loop:
play_again = raw_input("\n\nWant to play again?: ")
You can use a while loop for multiple iterations
import random
computer=random.randint(1, 100)
guess=int(input("guess the number"))
play_again = 'y'
while play_again == 'y':
if guess > 100:
print("your guess is too high")
elif guess < 1:
print("your guess is too low")
elif guess==computer:
print("well done!")
else:
print("you\'re wrong, guess again")
play_again = input("Want to play again(y/n): ")
You should put your code in while loop. Then after game ask user if they want to continue with input() function. If they say 'no' you can break the loop or set argument of while to False.
In the process of learning Python using the book 'Python Programming for the Absolute Beginner Third Edition' and struggling with a challenge that has been set.
I have to create a Number Guessing program where the player picks a number and the program tries to guess it by picking a random number then using higher or lower questions to get closer to the number. I've got most of it figured out but I'm struggling with the higher or lower loop. The trouble I'm having is that i can't get the program to not go above or below it's second to last guess i.e.
My number is 78
computer picks 50
i say higher
computer picks 80
i say lower
computer can then pick 12 (when i don't want it going below 50.
I'm using Python 3.1
Here is a copy of the code.
import random
computer_tries = 0
player_number = None
computer_guess = random.randint(1, 100)
print(
"""
Welcome Player to the fabulous number guessing game.
Please allow me to show you my incredible deduction skills
""")
question = None
while question != ("yes"):
question = input("Has the player picked a number? ")
question = question.lower()
if question == "yes":
print("\nI will now guess your number!!!\n")
while player_number == None:
computer_tries += 1
print(computer_guess, "\n")
confirmation = input("Is this the correct number? ")
confirmation = confirmation.lower()
if confirmation == "yes":
player_number = computer_guess
if computer_tries < 2:
print("I did it! I guessed your number was", computer_guess,
"and it only \ntook me", computer_tries,
"try to get it right!")
else:
print("I did it! I guessed your number was", computer_guess,
"and it only \ntook me", computer_tries,
"tries to get it right!")
else:
higher_lower = None
while higher_lower not in ("higher", "lower"):
higher_lower = input("Is my guess higher or lower"
+ " than your number? ")
higher_lower = higher_lower.lower()
if higher_lower == "higher":
higher = computer_guess
computer_guess = random.randint(higher, 101)
elif higher_lower == "lower":
lower = computer_guess
computer_guess = random.randint(0, lower)
else:
print("Please choose either higher or lower.")
input("\n\nPress the enter key to exit")
Thanks in advance for any help you folks can give.
Ally
I see the following problems with your code:
your random number generators are bound only on one side of the number spectrum, e.g. random.randint(0, lower) - so it's ignoring the higher bound. Similarly for computer_guess = random.randint(higher, 101).
I suggest you initialise higher and lower.
Some debug helps :)
Here's the working code:
import random
computer_tries = 0
player_number = None
computer_guess = random.randint(1, 100)
print(
"""
Welcome Player to the fabulous number guessing game.
Please allow me to show you my incredible deduction skills
""")
question = None
lower = 0 # initial lower guess
higher = 101 # initial higher guess
while question != ("yes"):
question = input("Has the player picked a number? ")
question = question.lower()
if question == "yes":
print("\nI will now guess your number!!!\n")
while player_number == None:
computer_tries += 1
print(computer_guess, "\n")
confirmation = input("Is this the correct number? ")
confirmation = confirmation.lower()
if confirmation == "yes":
player_number = computer_guess
if computer_tries < 2:
print("I did it! I guessed your number was", computer_guess,
"and it only \ntook me", computer_tries,
"try to get it right!")
else:
print("I did it! I guessed your number was", computer_guess,
"and it only \ntook me", computer_tries,
"tries to get it right!")
else:
higher_lower = None
while higher_lower not in ("higher", "lower"):
higher_lower = input("Is my guess higher or lower"
+ " than your number? ")
higher_lower = higher_lower.lower()
if higher_lower == "higher":
higher = computer_guess
computer_guess = random.randint(lower+1, higher-1)
elif higher_lower == "lower":
lower = computer_guess
computer_guess = random.randint(lower+1, higher-1)
else:
print("Please choose either higher or lower.")
print("DEBUG: number must be " + str(lower) + " < x < " + str(higher))
input("\n\nPress the enter key to exit")
You have to store something like min_comp_guess and max_comp_guess
Then, when you are about to "guess" number you have to generate it for a valid range (obviously min_comp_guess up to max_comp_guess).
I'm always second! :)
You are never storing the upper and lower bounds to the possible numbers. In your example, as soon as your program picks 50 and you say "higher", you need to store somewhere the information that "the number is definitely higher than 50". The same goes for when you answer "lower".
I may be completely wrong but whilst testing your code I found that by choosing the programs number was higher than my chosen number it would increase the number instead or a presumable decrease, not making it any closer to the number I had guessed. A similar higher/lower program I created had the same problem, to fix the problem I simply switched the more than and less than signs around, hopefully you find this helpful and could apply this to your program.