How do I write a question to play game again? - python

I'm expanding upon the random number guessing game from Automate the Boring Stuff with Python and I can't figure out how to write the code for when the game asks if you want to play again.
More specifically, if the user types "yes" or "no" to wanting to play the game, the code does the appropriate thing. However, if the user types in anything else, I want it to say "Please answer yes or no" and then allow the user to enter another answer.
In this case, my code currently prints "Please answer yes or no", but then it treats the answer as "yes", so it starts the game again. I don't want it to immediately start a new game unless the user specifically types "yes". How can I do this?
Here's the code
import random
print ('Hello, what is your name?')
name = input ()
name = name.strip()
while True:
print ('Well, ' + name + ', I am thinking of a number between 1 and 20.')
secretNumber = random.randint (1, 20)
print ('DEBUG: Secret number is ' + str(secretNumber))
print ('Take a guess.')
for guessesTaken in range (1, 7):
try:
guess = int (input ())
if (guess < secretNumber and guessesTaken < 6):
print ('Your guess is too low. Guess again.')
elif (guess > secretNumber and guessesTaken < 6):
print ('Your guess is too high. Guess again.')
else:
break # This condition is for the correct guess
except ValueError:
print ('You did not enter a number.') # This condition is for if a non-integer is entered.
if (guess == secretNumber and guessesTaken == 1):
print ('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guess.')
elif (guess == secretNumber and guessesTaken > 1):
print ('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses.')
else:
print ('Sorry. Your guesses were all wrong. The number I was thinking of was ' + str(secretNumber))
print ('Would you like to play again?')
answer = input ()
answer = answer.lower()
if answer == 'no':
print ('Ok.')
break
elif answer == 'yes':
print ('Ok, let\'s go!')
else:
print ('Please answer yes or no')

Simply have a second loop that will continue to prompt until a valid input is given.
usr_response = input('Would you like to play again: ').lower()
while usr_response not in ('yes','no'):
usr_response = input('Invalid response. Please choose yes or no: ')
if usr_response == 'no':
break

So the problem is that the code checks for valid input only once. If the 2nd input is invalid as well, no condition is checked. For the solution, You should replace:
if answer == 'no':
print ('Ok.')
break
elif answer == 'yes':
print ('Ok, let\'s go!')
else:
print ('Please answer yes or no')
with:
list1 = ['yes', 'no']
while answer not in list1:
print ('Please answer yes or no:')
answer = input()
if answer == 'no':
print ('Ok.')
break
elif answer == 'yes':
print ('Ok, let\'s go!')

Related

How do I stop this from repeating?

I am new to coding. It works alright until you guess a number. then it says either higher or lower eternally. Please help me understand what I've done wrong. I have tried searching the internet and trying to retype some of the code but it won't work. I am trying to make a conversation as well as a mini guess the number game.
Here's my Code
# Conversation A
import random
print("Answer all questions with 'yes' or 'no' and press ENTER")
print('Hello I am Jim the computer')
z = input('How are you? ')
if z == 'Good' or z == 'Great' or z == 'good' or z == 'great':
print("That's great!")
else:
print("Oh. That's sad. I hope you feel better.")
a = input("what's your name? ")
print(a + "? Thats a nice name.")
b = input('Do you own any pets? ')
if b == 'yes' or b == 'Yes':
print("That's cool. I love pets!")
else:
print("That's a shame, you should get a pet. ")
c = input("Do you like animals? ")
if c == 'yes' or c == 'Yes':
print("Great! Me too!")
else:
print("Oh that's sad. They're really cute. ")
d = input("Do you want to see a magic trick? ")
if d == "yes" or d == "Yes":
input("Ok! Think of a number between 1-30. Do you have it? ")
print("Double that number.")
print("Add ten.")
print("Now divide by 2...")
print("And subtract your original number!")
y = input("Was your answer 5? ")
if y == 'yes' or y == 'Yes':
print("Yay i got it right! I hope you like my magic trick.")
else:
print("Oh that's sad. I'll work on it. I really like magic tricks and games.")
else:
print("Ok. Maybe next time. I love magic tricks and games!")
e = input("Do you want to play a game with me? ")
if e == "yes" or e == "Yes":
randnum = random.randint(1,100)
print("I am thinking of a number between 1 and 100...")
if e == 'no' or e == 'No':
print("oh well see you next time" + a + '.')
guess = int(input())
while guess is not randnum:
if guess == randnum:
print("Nice guess " + a + "! Bye, have a nice day!")
if guess < randnum:
print("Higher.")
if guess > randnum:
print("Lower.")
You need to add a break statement when you want stop looping and move the input for guess inside the loop so you don't exit before printing the statement:
while True:
guess = int(input())
if guess == randnum:
print("Nice guess " + a + "! Bye, have a nice day!")
break
Edit: Also, you dont want to use is every time: Is there a difference between "==" and "is"?

How should I add Try & except Block to handle in my for loop

# This is a guess the number game.
import random
print ('Hello, What is your name?')
name = input()
print('Well, ' + name + '! I am thinking of a number between 1 to 20.')
secretNumber = random.randint(1,20)
print('Debug:' + str(secretNumber))
for guessTaken in range (1,7):
print('Take a guess. '+ name +'!' )
guess =int(input())
if guess<secretNumber:
print('Your guess is too low')
elif guess>secretNumber:
print('Your guess is too high')
else:
break # This is for correct guess is equal.
if guess ==secretNumber:
print('Good Job, ' +name+ '! You guess my number in ' + str(guessTaken)+ ' guesses!')
else:
print('Nope, The number I was thinking of was ' +str(secretNumber))
Hi my fellow super coders,
So I am trying to put Try and Except block in this program, I try it putting just after
guess=int(input()) unfortunately i am not able to make it work.
So i am trying to handle the ValueError, So lets say user needs to input Integers (Numbers), If he types string like , "One","Six" etc. the program crashes. I want to handle this case. Please can some help me out. :)
Thank You so much.
Cobra
How about this, it re asks if the user inputs a string:
# This is a guess the number game.
import random
print ('Hello, What is your name?')
name = input()
print('Well, ' + name + '! I am thinking of a number between 1 to 20.')
secretNumber = random.randint(1,20)
print('Debug:' + str(secretNumber))
for guessTaken in range (1,7):
print('Take a guess. '+ name +'!' )
try:
guess =int(input())
except:
print("Must be a number, try again: ")
continue
if guess<secretNumber:
print('Your guess is too low')
elif guess>secretNumber:
print('Your guess is too high')
else:
break # This is for correct guess is equal.
if guess ==secretNumber:
print('Good Job, ' +name+ '! You guess my number in ' + str(guessTaken)+ ' guesses!')
else:
print('Nope, The number I was thinking of was ' +str(secretNumber))
If the user enters something that is not a number python will skip to the exception because an error will occur, I added some text to the prints to clarify the rules of the game.
I used else after for loop which is very useful sometimes for the case where the user can't guess the number in 7 tries you can test it and see that even though the else is not after the if, when the if guess==secretNumber is true and you break the loop the else statement is not doing anything.
P.S still new to answering here so please give feedback about my answer
import random
print ('Hello, What is your name?')
name = input()
print('Well, ' + name + '! I am thinking of a number between 1 to 20.')
secretNumber = random.randint(1,20)
print('Debug:' + str(secretNumber))
for guessTaken in range (1,7):
print('Take a guess. '+ name +'!, You Have 7 tries' )
try:
guess = int(input())
if guess<secretNumber :
print('Your guess is too low')
elif guess>secretNumber :
print('Your guess is too high')
if guess == secretNumber:
print('Good Job, ' + name + '! You guess my number in ' + str(guessTaken)+ ' guesses!')
break # This is for correct guess is equal.
except:
print('Please Enter A number ' + name + 'and not anything else' )
else:
print('Nope, The number I was thinking of was ' +str(secretNumber))

I need help fixing a ValueError in a simple random number game

I created a simple number guessing game and I'm trying to fix a bug when inputing nothing accidentally.
When the program asks to take a guess, if the user hits enter without inputting a number then I get this error:
Traceback (most recent call last): File
"/Users/tom/Documents/Automate with Python/RandomNumberGame.py", line
13, in
guess = int(input()) ValueError: invalid literal for int() with base 10: ''
I'd like it to print 'Please enter a number' instead.
I've new to programming and have started reading "Automate the boring stuff with Python". Thanks in advance!
The original code did not include
elif guess == ' ':
print('Please enter a number')
but the goal is make the program say that if the input is left blank
I tried adding:
guess = int(input()) or str(input())
without any progress
guess the number game
import random
print('Hello, What is your name?')
name = input()
print('Well, ' + name + ', I am thinking of a number between 1 and 1000, You have 10 guesses to figure it out. Good luck!')
secretNumber = random.randint(1,1000)
print('DEBUG: Secret number is ' + str(secretNumber))
for guessesTaken in range(1,11):
print('Take a guess.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')
elif guess == ' ':
print('Please enter a number')
else:
break #This condition is for the correct guess
if guess == secretNumber:
print('Good job ' + name + '! You guessed the number in ' + str(guessesTaken) + ' guesses!')
else:
print('Too many guesses, The number I was thinking of was ' + str(secretNumber))
If you also don't want to lose a try if the user just pressed enter without entering a number. You can use a try-except within a while True: block like this
#code till this
for guessesTaken in range(1,11):
print('Take a guess.')
while True:
try:
guess = int(input())
break
except ValueError:
print('Please enter a number')
continue
#rest of your code
This will allow the user to continue with the game if he pressed enter accidentally while the number of tries remains the same.
Full code:
import random
print('Hello, What is your name?')
name = input()
print('Well, ' + name + ', I am thinking of a number between 1 and 1000, You have 10 guesses to figure it out. Good luck!')
secretNumber = random.randint(1,1000)
print('DEBUG: Secret number is ' + str(secretNumber))
#code till this
for guessesTaken in range(1,11):
print('Take a guess.')
while True:
try:
guess = int(input())
break
except ValueError:
print('Please enter a number')
continue
#rest of your code
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')
else:
break #This condition is for the correct guess
if guess == secretNumber:
print('Good job ' + name + '! You guessed the number in ' + str(guessesTaken) + ' guesses!')
else:
print('Too many guesses, The number I was thinking of was ' + str(secretNumber))
The variable guess is an integer value because you are converting the input into an integer: guess = int(input()). If the input is a space, or any other invalid string (cannot be parsed into a number), a ValueError exception is raised - that's why you get that error message.
You can handle when specific exceptions occur in Python using a try/except block. It works like so:
try:
# execute some code
except SomeException:
# handle the exception
The code in the try block will try to be executed, and if running the code results in the exception SomeException being raised, the code in the except block will be run.
In your specific case, what you want to do is to handle the ValueError exception, so you could just wrap the relevant code in a try/except like so:
...
for guessesTaken in range(1,11):
print('Take a guess.')
try:
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')
elif guess == ' ':
print('Please enter a number')
else:
break #This condition is for the correct guess
except ValueError:
print('Please enter a number')
...
If you want invalid inputs to not take up a guess, you can implement the game like so:
...
guessesTaken = 1
while True:
print('Take a guess.')
try:
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')
elif guess == ' ':
print('Please enter a number')
else:
break #This condition is for the correct guess
except ValueError:
print('Please enter a number')
continue # go back to the start of loop (without incrementing guessesTaken)
guessesTaken += 1
if guessesTaken >= 10:
break
...

Python Guessing game - incomplete code

Can someone please help me re-design this code so that the program prompts the user to choose Easy, Medium or Hard.
Easy: maxNumber = 10
Medium: maxNumber = 50
Hard: maxNumber = 100
It should choose a random number between 0 and the maxNumber.
The program will loop calling a function the get the users guess, and another to check their guess. a function named “getGuess” which will ask the user for their guess and reprompt
if the guess is not between 0 and the maxNumber
r function named “checkGuess” which will check the users guess
compared to the answer.
The function will return “higher” if the number is higher
than the guess; “lower” if the number is lower than the guess and “correct” if thenumber is equal to the guess.
Once the user has guessed the number correctly the program will display all their guesses and
how many guesses it took them. Then the program will ask the user if they would like to try
again and redisplay the difficulty menu.
import random
guessesTaken = 0
print('Hello! Welcome to the guessing game')
myName = input()
number = random.randint(1, 20)
print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')
while guessesTaken < 6:
print('Take a guess.')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
You could do something like this:
from random import randint
myName = input("what's your name? ")
def pre_game():
difficulty = input("Choose difficulty: type easy medium or hard: ")
main_loop(difficulty)
def main_loop(difficulty):
if difficulty == "easy":
answer = randint(0, 10)
elif difficulty == "medium":
answer = randint(0, 50)
else:
answer = randint(0, 100)
times_guessed = 0
guess = int()
while times_guessed < 6:
print('Take a guess.')
guess = input()
guess = int(guess)
times_guessed += 1
if guess < answer:
print('Your guess is too low.')
if guess > answer:
print('Your guess is too high.')
if guess == answer:
break
if guess == answer:
guessesTaken = str(times_guessed)
print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
if guess != answer:
print('Nope. The number I was thinking of was ' + str(answer))
next = input("Play again? y/n: ")
if next == "y":
pre_game()
else:
print("Thanks for playing!")
pre_game()

Ending a program in Python

I am struggling to end my program in Python, all I want is to type q or quit to end the program when done. Here is my code
# This is a guess the number game
import random
guessesTaken = 0
print('Hello! What is your name?')
myName = input()
number = random.randint(1, 20)
print('Well, ' + myName + ', I am thinking of a number between 1 and 20, can you guess it?')
while guessesTaken < 6:
print('Take a guess!')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low')
if guess > number:
print('Your guess is too high')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job ' + myName + '!You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
print('Game Over')
choice = input('Press Q to Quit')
if choice == 'q' :
sys.exit()
Please tell me where I am going wrong??
From what I can tell you have two errors.
First you need to import the sys module for sys.exit() to work.
Second, your indentation is incorrect in two places. Here is the correct code. The comments show where the indentation is incorrect:
# This is a guess the number game
import random
import sys
guessesTaken = 0
print('Hello! What is your name?')
myName = input()
number = random.randint(1, 20)
print('Well, ' + myName + ', I am thinking of a number between 1 and 20, can you guess it?')
while guessesTaken < 6:
print('Take a guess!')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low')
if guess > number:
print('Your guess is too high')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job ' + myName + '!You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number: #indentation was off here
number = str(number)
print('Nope. The number I was thinking of was ' + number)
print('Game Over') #and here
choice = input('Press Q to Quit')
if choice == 'q' :
sys.exit() # and here
As #MarkyPython noted, you have some indent error, and you need to import sys if you want to use exit.
Note that given the code that you have, it is actually bad practice to use sys.exit(). I would instead recommend that you use break. This will exit your while loop. Because you have no code after that, your program will graciously exit.
If you add more code later on, you'll probably want to put your code inside a function. At that point, using return will be the way to go.
Using break or return is better practice because it makes it easier to add features to your program later on and makes the flow of your code better (no abrupt exit 'jump').
print('Hello! What is your name?')
myName = input()
number = random.randint(1, 20)
print('Well, ' + myName + ', I am thinking of a number between 1 and 20, can you guess it?')
while guessesTaken < 6:
print('Take a guess!')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low')
if guess > number:
print('Your guess is too high')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job ' + myName + '!You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
print('Game Over')
choice = input('Press Q to Quit')
if choice == 'q' :
break # instead of exit

Categories