I know there is a solution to the number guessing game in python. I've seen the code here too. and as a continuation how can I add a function(or anything else) to prompt the user- after successfully guessing it- if he wants to continue or not if not halt it. I know the code don't know how to add it to code.
import random
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
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")
return
count+=1
so here is what we had in this forum but how can I add this to what I have above :
ask = input('do you want to continue? y stands for yes and n for discontinuing')
if ask=="y":
UserGuess=int(input('Enter youre desired Number: '))
else:
return
Include it in a while loop outside the function. This way, you will get recursion out of the way.
def play_game():
....
....
count+=1
play_game()
while True:
ask = input('do you want to continue? y stands for yes and n for discontinuing')
if ask=="y":
play_game()
else:
break
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)
I don't know what's wrong with it.. I run it and I'm able to input a number but then it stops working. It says, "TypeError: play_game() missing 1 required positional argument: 'limit.' But I'm not sure what's missing there??
#!/usr/bin/env python3
import random
def display_title():
print("Guess the number!")
print()
def get_limit():
limit = int(input("Enter the upper limit for the range of numbers: "))
return limit
def play_game(limit):
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
count += 1
elif guess >= number:
print("Too high.")
count += 1
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
return
def main():
display_title()
again = "y"
while again.lower() == "y":
limit = get_limit()
play_game()
again = input("Play again? (y/n): ")
print()
print("Bye!")
# if started as the main module, call the main function
if __name__ == "__main__":
main()
You have defined your play_game function to take limit as a parameter, but when you call this function in your main loop, you don't supply a value in the brackets of play_game().
You could either try adding that limit value that you've specified by calling it like
play_game(25)
Or, based on your code, since you're asking the user to provide a limit, call it like:
play_game(limit)
Or, if you want to be able to call play_game() without setting a limit, then change your play_game definition line to something like:
def play_game(limit=25):
Which will set a default value of 25 whenever that function is called without supplying the limit value.
Yes, play_game() needs the parameter limit. I've done a quick check on your code, and there is some additional problem
the count variable isn't initialized
you calculate the random number in every step
guess > number should be used instead of guess >= number
Here is the fixed code, it works for me. I hope it will be usefull:
import random
count = 0
number = -1
def display_title():
print("Guess the number!")
print()
def get_limit():
limit = int(input("Enter the upper limit for the range of numbers: "))
return limit
def play_game(limit):
global number, count
if number == -1:
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
count += 1
elif guess > number:
print("Too high.")
count += 1
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
return
display_title()
again = "y"
while again.lower() == "y":
limit = get_limit()
play_game(limit)
again = input("Play again? (y/n): ")
print()
print("Bye!")
In your main you are calling playgame() without providing a limit as an argument.
Your main should look something like
def main():
display_title()
again = "y"
while again.lower() == "y":
limit = get_limit()
play_game(10)
again = input("Play again? (y/n): ")
print()
print("Bye!")
So my assignment(I have to use the while statement) was to make a number guessing game, part of that was to show the number of guesses the player had after they get the number right. I found something that I read is supposed to work but doesn't. here is my code.
#A text program that is a simple number guessing game.
import time
import random
#Setting up the A.I.
Number = random.randint(1,101)
def AI():
B = AI.counter =+ 1
Guess = int(input("Can you guess what number I'm Thinking of?: "))
while Guess > Number:
print("nope, to high.")
return AI()
while Guess < Number:
print("Sorry, thats to low. try again!")
return AI()
while Guess == Number:
print("Congragulations! you win! You guessed " + str(B) + " times")
time.sleep(60)
quit()
AI.counter = 0
AI()
Though when the player gets the number right it says that the player got it in one guess even when that's not the case.
You were pretty close #Simpson! Here's a slightly changed version that should give you what you're looking for :)
Let me know if you have any questions!
#A text program that is a simple number guessing game.
import random
#Setting up the A.I.
def AI():
counter = 1
number = random.randint(1,101)
guess = int(input("Can you guess what number I'm Thinking of?: "))
while guess != number:
if guess < number:
print("Sorry, thats to low. try again!")
else:
print("nope, too high")
counter += 1
guess = int(input("Can you guess what number I'm Thinking of?: "))
print("Congragulations! you win! You guessed " + str(counter) + " times")
time.sleep(60)
quit()
AI()
Without recursion - changed the whiles to ifs and added counter inside the method.
import time
import random
Number = random.randint(1,101)
def AI():
B = 1
Guess = int(input("Can you guess what number I'm Thinking of?: "))
while True:
if Guess > Number:
print("nope, to high.")
elif Guess < Number:
print("Sorry, thats to low. try again!")
if Guess == Number:
print("Congragulations! you win! You guessed " + str(B) + " times")
time.sleep(2)
break # leave the while true
# increment number
B += 1
Guess = int(input("Can you guess what number I'm Thinking of?: "))
AI()
Counting function calls is a perfect case for function decorators, a very useful feature of Python. You can define your decorator as:
def call_counted(funct):
def wrapped(*args, **kwargs):
wrapped.count += 1 # increase on each call
return funct(*args, **kwargs)
wrapped.count = 0 # keep the counter on the function itself
return wrapped
And then you can use it to decorate a function you wish to count calls to without dealing with the counter itself in your process flow:
import time
import random
secret_number = random.randint(1, 101)
#call_counted # decorate your AI function with the aforementioned call_counted
def AI():
current_guess = int(input("Can you guess what number I'm thinking of?: "))
while current_guess > secret_number:
print("Nope, too high. Try again!")
return AI()
while current_guess < secret_number:
print("Sorry, that's too low. Try again!")
return AI()
while current_guess == secret_number:
print("Congratulations! You win! You guessed {} times.".format(AI.count))
time.sleep(60)
quit()
AI()
I restyled your code a bit, but it's essentially the same.
I'd avoid recursion, tho, because this can be written much simpler and without the need to count function calls:
import time
import random
secret_number = random.randint(1, 101)
def AI():
counter = 0
while True:
counter += 1
current_guess = int(input("Can you guess what number I'm thinking of?: "))
if current_guess > secret_number:
print("Nope, too high. Try again!")
elif current_guess < secret_number:
print("Sorry, that's too low. Try again!")
else:
break
print("Congratulations! You win! You guessed {} times.".format(counter))
time.sleep(60)
quit()
AI()
You could do it generically with a function decorator that addes a call counter to any function to which it is applied:
(Note I also modified your code so it follows the PEP 8 - Style Guide for Python Code more closely.)
""" A text program that is a simple number guessing game. """
import functools
import time
import random
def count_calls(f):
""" Function decorator that adds a call count attribute to it and counts
the number of times it's called.
"""
f.call_count = 0
#functools.wraps(f)
def decorated(*args, **kwargs):
decorated.call_count += 1
return f(*args, **kwargs)
return decorated
# Setting up the A.I.
number = random.randint(1, 101)
# print('The number is:', number) # For testing.
#count_calls
def AI():
guess = int(input("Can you guess what number I'm thinking of?: "))
while guess > number:
print("Nope, too high.")
return AI()
while guess < number:
print("Sorry, that's too low. Try again!")
return AI()
while guess == number:
print("Congragulations! You win! You guessed " + str(AI.call_count) + " times")
time.sleep(10)
quit()
AI()
Use default arguments:
def AI(B=1):
Guess = int(input("Can you guess what number I'm Thinking of?: "))
while Guess > Number:
print("nope, to high.")
return AI(B + 1)
while Guess < Number:
print("Sorry, thats to low. try again!")
return AI(B + 1)
while Guess == Number:
print("Congragulations! you win! You guessed " + str(B) + " times")
time.sleep(60)
return
And then call the function:
AI()
Also, you should really be using ifs instead of whiles here since the loops are run exactly once, but whiles also work, so that's fine. Also, recursion might eat up your RAM, which just wastes resources, provided that you could've implemented the same thing as a loop, but your approach works, so that's fine too.
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