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
Related
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
This is the code:
print("Welcome to my guessing game can you get the magic number hint, it's between 1 and 100 ")
import random
Magic_number = random.randrange(1, 100)
print(Magic_number)
guess = int(input("Enter your guess:"))
guess_limit = 5
guess_counter = 1
out_of_guesses = False
print("You have", str(guess_limit - guess_counter), "tries left")
while not out_of_guesses:
guess = int(input("Enter guess: "))
if guess == Magic_number:
print("Well done you got it!!")
exit(0)
elif guess < Magic_number:
print("That number is too small, try again")
elif guess > Magic_number:
print("That number is too high try again")
guess_counter += 1
print("You have", str(guess_limit - guess_counter), "tries left")
# exit clause
if guess_limit == guess_counter:
out_of_guesses = True
print("Game over, sorry")
And even if I get it correct on the first try it does something like this:
Welcome to my guessing game can you get the magic number
hint,
it's between 1 and 100
47
Enter your guess: 47
You have 4 tries left
Enter guess: 47
Well done you got it!!
As you can see even though i was correct on the first try it wasn't counted. Ps.(That is what shows up at the bottom of my screen where the code is executed.)
You do not check if guess == Magic_number after reading input on line 4.
Like this
import random
Magic_number = random.randrange(1, 100)
print(Magic_number)
guess = int(input("Enter your guess:"))
if guess == Magic_number:
print ("You won")
exit(0)
You don't need all those variables, check this.
import random
Magic_number = random.randrange(1, 100)
print(Magic_number)
guess_limit = 5
guess_counter = 0
while True:
guess = int(input("Enter guess: "))
if guess == Magic_number:
print("Well done you got it!!")
exit(0)
elif guess < Magic_number:
print("That number is too small, try again")
elif guess > Magic_number:
print("That number is too high try again")
guess_counter += 1
print(f"You have {guess_limit - guess_counter} tries left")
if guess_counter == guess_limit:
print("Game over, sorry")
exit(0)
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 recently started learning python and my friend from work who is a programmer gave me a simple challenge to write a "guess the number" style game.
So i came up with something as follows:
import random
print("Hello, welcome to GUESS THE NUMBER game")
run = True
def again():
global run
playagain = str(input("Would you like to play again? Type y/n for yes or no: "))
if playagain == "y":
run = True
elif playagain == "n":
run = False
while run:
guess = int(input("Guess the number between 1 and 10: "))
num1 = random.randint(1, 10)
if guess == num1:
print("CONGRATULATIONS, YOU HAVE GUESSED THE NUMBER, THE ANSWER WAS " + str(num1))
again()
elif guess > num1:
print("Too high, go lower!")
elif guess < num1:
print("Too small, go higher!")
My problem is that after the user has chosen to play again, the numbers sometimes dont register and go out of whack. For example you input 5 and it says too low, but if you input 6 it says too high! I don't seem to be dealing in float numbers so they should be whole, any ideas where i went wrong?
Thanks in advance and very excited to learn more on the subject
Your problem is that you're regenerating the random number every time.
num1 = random.randint(1, 10)
Instead, maybe put the guess and check logic inside it's own loop.
while True:
guess = int(input("Guess the number between 1 and 10: "))
if guess == num1:
print("CONGRATULATIONS, YOU HAVE GUESSED THE NUMBER, THE ANSWER WAS " + str(num1))
break # leave the while True loop
elif guess > num1:
print("Too high, go lower!")
elif guess < num1:
print("Too small, go higher!")
again()
You are calculating the random number on each iteration of the loop. Therefore every time you guess the random number changes.
import random
print("Hello, welcome to GUESS THE NUMBER game")
run = True
def again():
global run
playagain = str(input("Would you like to play again? Type y/n for yes or no: "))
if playagain == "y":
run = True
elif playagain == "n":
run = False
num1 = random.randint(1, 10)
while run:
guess = int(input("Guess the number between 1 and 10: "))
if guess == num1:
print("CONGRATULATIONS, YOU HAVE GUESSED THE NUMBER, THE ANSWER WAS " + str(num1))
again()
elif guess > num1:
print("Too high, go lower!")
elif guess < num1:
print("Too small, go higher!")
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()