I want to setup a would you like to retry - python

I have created a guess the number game, at the end of it I want it to ask the user if they would like to retry. I got it to take invalid responses and if Yes then it will carry on, but when I say no it still carries on.
import random
from time import sleep
#Introduction & Instructions
print ("Welcome to guess the number")
print ("A random number from 0 - 1000 will be generated")
print ("And you have to guess it ")
print ("To help find it you can type in a number")
print ("And it will say higher or lower")
guesses = 0
number = random.randint(0, 1)#Deciding the number
while True:
guess = int (input("Your guess: "))#Taking the users guess
#Finding if it is higher, lower or correct
if guess < number:
print ("higher")
guesses += 1
elif guess > (number):
print ("lower")
guesses += 1
elif guess == (number):
print ("Correct")
print (" ")
print ("It took you {0} tries".format(guesses))
#Asking if they want another go
while True:
answer = input('Run again? (y/n): ')
if answer in ('y', 'n'):
break
print ('Invalid input.')
if answer == 'y':
continue
if answer == 'n':
exit()

First of all, when you check :
if answer in ('y','n'):
This means that you are checking if answer exists in the tuple ('y','n').
The desired input is in this tuple, so you may not want to print Invalid input. inside this statement.
Also, the break statement in python stops the execution of current loop and takes the control out of it. When you breaked the loop inside this statement, the control never went to the printing statement or other if statements.
Then you are checking if answer is 'y' or 'n'. If it would have been either of these, it would have matched the first statement as explained above.
The code below will work :
#Asking if they want another go
while True:
answer = input('Run again? (y/n): ')
if answer == 'y':
break
elif answer == 'n':
exit()
else:
print ('Invalid input.')
continue
Also, you might want to keep the number = random.randint(0, 1)#Deciding the number statement inside the while loop to generate a new random number everytime the user plays the game.

This is because of the second while loop in your code. Currently when you put y or n it will break and run again (you don't see the invalid message due to the break occurring before reaching that code), it should be correct if you change it to the following:
while True:
answer = input('Run again? (y/n): ')
# if not answer in ('y', 'n'):
if answer not in ('y', 'n'): # edit from Elis Byberi
print('Invalid input.')
continue
elif answer == 'y':
break
elif answer == 'n':
exit()
Disclaimer: I have not tested this but it should be correct. Let me know if you run into a problem with it.

Related

(Python) Trouble making the user input promt another quiz question or break the loop

I'm pretty new to programming, so please pardon me!
***EDIT 2: Ok so this is the full thing. Everything is working fine except when I try to break out of the while enthusiasm is True: loop, I just keep getting more and more questions (the loop keeps running)
I'm building a Python trivia quiz, and I managed all the answer input loop to work (doesn't allow invalid input, breaks the loop succesfully)
I want the program to ask the user "Would you like another question? (y/n)" and stop the program if 'n'.
The problem is no matter what I tried, I keep getting more trivia questions!
Thanks in advance
import requests
import pprint
import json
import html
print("Welcome to the ultimate test of knowledge and valour, The Internet Quiz!")
print("You will be given an array of multiple choice questions in general knowledge")
input("Press Enter to start!")
y_n = ["y", "n"]
import random
q_num = 1
score = 0
enthusiasm = True
while enthusiasm is True:
r = requests.get("https://opentdb.com/api.php?amount=1&category=9&type=multiple")
question = json.loads(r.text)
first = question['results'][0]['correct_answer']
second = question['results'][0]['incorrect_answers'][0]
third = question['results'][0]['incorrect_answers'][1]
fourth = question['results'][0]['incorrect_answers'][2]
print("--------------------------------------------------------")
print("Question number " + str(q_num)+ ":")
print(html.unescape(question['results'][0]['question']))
options = [first,second,third,fourth]
random.shuffle(options)
for X in options:
print(html.unescape(X))
legend = (
(options[0], 1),
(options[1], 2),
(options[2], 3),
(options[3], 4)
)
error = False
while error is False:
guess = input("Please enter the number of your answer(1-4):")
try:
guess = int(guess)
except:
print("Your answer must be a number between 1-4.")
continue
if guess <1 or guess > 4:
print("Your answer must be a number between 1-4.")
continue
else:
error = True
if (first, guess) in legend:
score += 1
q_num += 1
print("Correct! \nCurrent score: " +str(score))
acid = True
while acid is True:
yesno=input("Would you like another question? (y/n)")
try:
yesno = str(yesno.lower())
except:
print("Invalid input. Please enter y/n.")
continue
if yesno.lower() != "y" and yesno.lower() != "n":
print("Invalid input. Please enter y/n.")
continue
elif yesno.lower() == "y":
break
else:
acid=False
error=True
continue
else:
print("Incorrect! Better hit the books, buddy! \nCurrent score: " +str(score))
q_num += 1
acid = True
while acid is True:
yesno=input("Would you like another question? (y/n)")
try:
yesno = str(yesno.lower())
except:
print("Invalid input. Please enter y/n.")
continue
if yesno.lower() != "y" and yesno.lower() != "n":
print("Invalid input. Please enter y/n.")
continue
elif yesno.lower() == "y":
break
else:
acid=False
error=True
continue
You have two while loops:
while enthusiasm is True:
and
while error is False
Let's look at what happens when you ask if the user wants another question (simplified a little):
yesno=input("Would you like another question? (y/n)")
if yesno.lower() == "y":
break
else:
error=True
You set error to True, but you do not set enthusiasm to False, so the loop starts again at the top. Looking further, enthusiasm never gets set to False, so that condition will always start over. Simply writing
else:
error = True
enthusiasm = False
would be fine. I also would recommend thinking about if you want two loops, and what the purpose of the enthusiasm variable is.
There's a lot of other refactoring that can be done here, but not that you probably should write
while not error:
instead of explicitely checking if error "is" False. Similarly,
while enthusiasm:
is a good check on a boolean
Similarly,
yesno=input("Would you like another question? (y/n)")
try:
yesno = str(yesno.lower())
except:
print("Invalid input. Please enter y/n.")
continue
if yesno.lower() != "y" and yesno.lower() != "n":
can be improved. You don't need to cast yesno to a string, becuase that's what happens when it comes from input. You don't need the try/except either (you may have taken this from an int cast, elsewhere). Since you've already converted yesno to lower once, you don't need to keep doing that every time you compare it to a y or n.
Possible to stop the program with:
import sys
sys.exit()

How to repeat code from a certian point when user input is incorrect

I'm new to Python so I'm not really sure on the basics so I understand this is probably a stupid question.
I'm making code where the user inputs a number, and if they get it wrong, I want the code to restart and ask them to guess again till it's right. How do I do this?
print("Let's play a game! Type in a number and see if you guess mine correctly!")
num = input("Type in a number: ")
for x in range (0,1):
if num == "7":
print("Correct!")
else:
print("Nope, try again!")
(Also I know that a lot of this code is probably wrong.)
You can put it in a while loop:
verified = None
while verified is None:
num = input("Type in a number: ")
if num == "7":
print("Correct!")
# if answer is good
verified = True
else:
print("Nope, try again!")

Is it possible to change a variable’s value while it is in the `while` loop?

I was trying to write code to solve a question:
Generate a random number between 1 and 9 (including 1 and 9). Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right. Keep track of how many guesses the user has taken, and when the game ends, print this out.
The code that I wrote was:
import sys
import random
x=random.randint(1,9)
print('Hello there! Please enter a number between 1 and 9 including the extremes.')
for i in range (10):
z=input()
if int(z)<x:
print('Too low. Please try again.')
elif int(z)>x:
print('Too high. Please try again.')
elif int(z)==x:
print('You guessed it right!')
if i==0:
print('It took you a single turn! Nice')
else:
print('it took you ' + str(i+1)+' turns.')
print('Do you want to play again? Yes or No?')
j=input()
if j.lower()=='yes':
print('Okay, Please enter a number between 1 and 9 including the extremes.')
pass
else:
sys.exit()
Here’s what it looks like when run:
Hello there! Please enter a number between 1 and 9 including the extremes.
4
Too high. Please try again.
3
Too high. Please try again.
2
You guessed it right!
it took you 3 turns.
Do you want to play again? Yes or No?
yes
Okay, Please enter a number between 1 and 9 including the extremes.
6
Too high. Please try again.
4
Too high. Please try again.
2
You guessed it right!
it took you 6 turns.
Do you want to play again? Yes or No?
See, the code gives perfect results when the for loop is first executed. It gives weird results when we try to run this “game” for the second time by saying yes when it asks us the question: Do you want to play again? Yes or No?.
Is it possible to put i=0 when python reaches the 4th last line and the for loop starts again from i=0 so that I do not get weird results?
Or is there some other easier method remove this bug?
You can use while loop for the task. And you should add exception handling method for getting an input.
import random
cond = True
while cond:
print('Hello there! Please enter a number between 1 and 9 including the extremes.')
x=random.randint(1,9)
for i in range (10):
z=int(input())
if int(z)<x:
print('Too low. Please try again.')
elif int(z)>x:
print('Too high. Please try again.')
elif int(z)==x:
print('You guessed it right!')
import sys
if i==0:
print('It took you a single turn! Nice')
else:
print('it took you ' + str(i+1)+' turns.')
print('Do you want to play again? Yes or No?')
j=input()
if j.lower()=='yes':
break
else:
cond = False
sys.exit()
First of all, you pick the random number only once, so it's always going to be the same.
Secondly, your game should be in while loop instead of for loop (if you want to allow player to restart after they guessed).
turns = 0
while True:
secret_number = random.randint(1,9)
print('Please enter a number between 1 and 9 including the extremes.')
guess = input()
turns += 1
if int(guess) < secret_number:
print("Too low")
elif int(guess) > secret_number:
print("Too high")
else:
print("You guessed in {} turn(s)".format(turns))
You continue the loop, and assign turns = 0 if user wants to keep playing, or you break if he doesn't.
All imports should go at the top of the file. Then, put a while loop so the player can restart after every game; this way, the variable x is also reset after every game. Also, the first print should be put outside the while and for loop, so it's printed only one time (the last if will print a new prompt at the beginning of a new game).
Your code at this point should look like this:
import random
import sys
print('Hello there! Please enter a number between 1 and 9 including the extremes.')
while True:
x=random.randint(1,9)
for i in range (10):
z=input()
if int(z)<x:
print('Too low. Please try again.')
elif int(z)>x:
print('Too high. Please try again.')
elif int(z)==x:
print('You guessed it right!')
if i==0:
print('It took you a single turn! Nice')
else:
print('it took you ' + str(i+1)+' turns.')
print('Do you want to play again? Yes or No?')
j=input()
if j.lower()=='yes':
print('Okay, Please enter a number between 1 and 9 including the extremes.')
else:
sys.exit()
I'd write it like this, probably.
from itertools import count
from random import randint
def run_game():
random_value = randint(1, 9)
print('Hello there! Please enter a number between 1 and 9 including the extremes.')
for i in count():
guess_string = input()
try:
guess = int(guess_string)
except ValueError:
print("Invalid value given for guess: {}".format(guess_string))
if guess < random_value:
print("Too low! Please try again.")
elif guess > random_value:
print("Too high! Please try again.")
else:
print('You guessed it right!')
if not i:
print('It took you a single turn! Nice')
else:
print('it took you {} turns.'.format(i + 1))
print('Do you want to play again? Yes or No?')
response_string = input()
return response_string.lower() == 'yes'
if __name__ == "__main__":
while run_game():
pass
But, for simplicity in understanding:
from itertools import count
from random import randint
if __name__ == "__main__":
playing = True
while playing:
random_value = randint(1, 9)
print('Hello there! Please enter a number between 1 and 9 including the extremes.')
for i in count():
guess_string = input()
try:
guess = int(guess_string)
except ValueError:
print("Invalid value given for guess: {}".format(guess_string))
if guess < random_value:
print("Too low! Please try again.")
elif guess > random_value:
print("Too high! Please try again.")
else:
print('You guessed it right!')
if not i:
print('It took you a single turn! Nice')
else:
print('it took you {} turns.'.format(i + 1))
print('Do you want to play again? Yes or No?')
response_string = input()
if response_string.lower() != 'yes':
playing = False
break
The whole of your code is embedded within the for loop and the counter is never reset. If you want to reset i within the for loop, you have to define it outside the for loop so that it has a global scope.

Random number being changed within Python script

I'm working on a Python script where a user has to guess a random number, selected by the script. This is my code:
import random
while True:
number = random.randint(1, 3)
print("Can you guess the right number?")
antwoord = input("Enter a number between 1 and 3: ")
if antwoord == number:
print ("Dang, that's the correct number!")
print (" ")
else:
print ("Not the same!")
print ("The correct answer is:")
print (number)
while True:
answer = input('Try again? (y/n): ')
print (" ")
if answer in ('y', 'n'):
break
print("You can only answer with y or n!")
if answer == 'y':
continue
else:
print("Better next time!")
break
It works... Sort of... I was trying it and came across this:
User enters 2, it says it's incorrect, but then displays the same number!
I have the feeling that, every time I call the variable 'number', it changes the random number again. How can I force the script to hold the random number picked at the beginning, and not keep changing it within the script?
As far as I understand it, you want to pick a new random integer in every loop step.
I guess you are using python 3 and so input returns a string. Since you cannot perform comparisson between a string and an int, you need to convert the input string to an int first.
import random
while True:
number = random.randint(1, 3)
print("Can you guess the right number?")
antwoord = input("Enter a number between 1 and 3: ")
try:
antwoord = int(antwoord)
except:
print ("You need to type in a number")
if antwoord == number:
print ("Dang, that's the correct number!")
print (" ")
else:
print ("Not the same!")
print ("The correct answer is:")
print (number)
while True:
answer = input('Try again? (y/n): ')
print (" ")
if answer in ('y', 'n'):
break
print("You can only answer with y or n!")
if answer == 'y':
continue
else:
print("Better next time!")
break

Python Syntax error while making a little game

New to Python and trying to figure out what went wrong here. Making a simple game in which I have to guess the number that was randomly generated by the computer. Thanks for your help.
Here's what I have:
guessed == random.randint(1,100)
print("I guessed a number between 1 and 100. Try to find it!")
entered = 0
while entered != guessed
entered = raw_input("Enter your suggestion:")
entered = int(guessed_number)
if entered > guessed
print('Try less')
else
print('Try more')
print('You win!')
You're missing colons at the end of your conditionals and loops, aka while entered != guessed:. Add them to the end of the if and else lines as well. Also you are using the comparison (==) operator when assigning guessed instead of the assignment operator (=).
Also you will notice it prints "Try more" even when they guess the correct number, and then it will print "You win!". I'll leave this as an exercise to the new developer to fix.
entered = int(guessed_number)
makes no sense because you don't have a guessed_number variable. I think you meant to do
entered = int(raw_input("Enter your suggestion:")
Also, you're missing colons after your block starts at while, if, and else.
Welcome to Python 3.x! Here's the fixed code for you.
#Import Random
import random as r
#Create a random Number!
guessed = r.randint(1,100)
print("I guessed a number between 1 and 100. Try to find it!")
#Initiate variable --entered--
entered = 0
while (entered != guessed):
entered = int(input("Enter your suggestion:"))
#Fixed your if/else tree with correct indents and an elif.
if (entered > guessed):
print('Try less')
elif (entered <guessed):
print('Try more')
else:
print('You win!')
To add to the list:
guessed == random.randint(1,100)
should be
guessed = random.randint(1,100)
I'm sure you'd rather assign to guessed than compare it random.randint(1,100) and then throw the result of that comparison away.
entered = int(guessed_number)
It doesn't make any sense. There is no variable for 'guessed_number'.
I have edited your code to make it work:
import random
guessed = r.randint(1,100)
print("I guessed a number between 1 and 100. Try to find it!")
entered = 0
while (entered != guessed):
entered = int(input("Enter your suggestion:"))
if (entered > guessed):
print('Try less')
elif (entered <guessed):
print('Try more')
else:
print('You win!')
Hope that helps!
~Edward

Categories