How to make this program ask user to replay game? [duplicate] - python

This question already has answers here:
Repeat Game - Python Rock, Paper, Scissors
(2 answers)
Closed 2 years ago.
I would like to know how to ask a user "Would you like to play again?" and how to loop that so it works.
I have tried a few different things but nothing has worked yet. This is only my 4th day learning code and I decided I wanted to try and make my own mini game. All the code so far is done without looking anything up online and is done through memory of what I have learned the past few days so forgive me if its not the best.
'''
import random
import time
user_answer = input("Would you like to try and guess the number the die will roll? : ")
def guess_number():
dice_sides = ["1", "2", "3", "4", "5", "6"]
r_roll = random.choice(dice_sides)
if user_answer == "yes" or "Yes":
print("Excellent, lets play!")
else:
print("Okay, have a great day!")
user_guess = input("What is your guess? : ")
time.sleep(1)
print("The number is.....")
time.sleep(1.5)
print(r_roll)
if user_guess == r_roll:
print("Congrats! You won!")
else:
print("Sorry, you lose....")
guess_number()
'''

Try the following:
guess_number()
while True:
response = input("wanna play again?")
if response.lower() == "yes":
guess_number()
else:
break

Related

How do I have multiple optional inputs? [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 8 months ago.
import time
x = input("Buy Eggs? (Y/N) ")
if x.lower().strip() == "yes" or "y":
print("Buy Eggs")
time.sleep(0.5)
print("You bought eggs")
elif x.lower().strip() == "no" or "n":
print("Don't buy eggs")
time.sleep(.5)
print("You don't have eggs")
What I want to happen is to allow multiple words to be inputted for one if command. I thought it'd work but instead of working it would prioritize the top piece of code.
Buy Eggs? (Y/N) n #<--- Answer#
Buy Eggs
You bought eggs
Process finished with exit code 0
It only seems to work if I remove the or command but I haven't found any other options to allow multiple optional inputs.
Thank you if you do choose to help me
Hope this can help you:
ans = input("Buy Eggs? (Y/N) ")
if ans.lower().strip() in ('y', 'yes'):
print("Buy Eggs")
time.sleep(0.5)
print("You bought eggs")
elif ans.lower().strip() in ('n', 'no'):
print("Don't buy eggs")
time.sleep(.5)
print("You don't have eggs")
I think you can give the multiple inputs in a list :
import time
x = input("Buy Eggs? (Y/N) ")
if x in ["yes",'y', "Y", "yea"]:
print("Buy Eggs")
time.sleep(0.5)
print("You bought eggs")
elif x in ["no", "n", "NO", "N"]:
print("Don't buy eggs")
time.sleep(.5)
print("You don't have eggs")

Why is python is running the if statement when it should be running elif [duplicate]

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed last year.
I'm still learning the basics of python and can't seem to figure out why my simple dice rolling code isn't working properly.
import random
def main():
num = int(input("How many sides of the die?\n"))
num_of_rolls = int(input("How many rolls?\n"))
roll_y_n = input("Are you ready to roll? Y/N\n")
var = 1
def dice_roll(num):
return random.randrange(1,num)
if roll_y_n.lower() in "yes" or "y":
while var <= num_of_rolls:
print("You rolled a " + str(dice_roll(num)) + ".")
var = var + 1
else:
print("Okay, Byeee!")
exit()
retry = input("Do you want to go again? Y/N\n")
if retry.lower() == "yes" or "y":
main()
elif retry in "no" or 'n':
print("Okay, Byeee!")
exit()
main()
it runs it just fine, but when ever I type in "n" to get it to stop it still runs as if I typed in "y".
Sorry if this is a dumb question, I just can't figure it out.
There is lot of syntax error in your code:
Use this:
if roll_y_n.lower() in ["yes", "y"]:
while var <= num_of_rolls:
print("You rolled a " + str(dice_roll(num)) + ".")
var = var + 1
if retry.lower() in ["yes","y"]:
main()
elif retry in ["no", 'n']:
print("Okay, Byeee!")
exit()

Is there a way to repeat code in a simple way?

I am making a python quiz and everything is going well but there are some things that aren't working. Such as when the user has answered all the questions, I want the code to ask the user if they would like to play the quiz again. I have done the part where the code asks the user if they would like to play again but I don't know how to repeat the quiz. I have tried things such as making the quiz a variable and printing the variable but that didn't work. Please help me.
Here's the code, the part where I ask if the user wants to play again is at the bottom.
import random
import time
Question_list = {
"How many years are there in a millennium?":"1000",
"How many days are there in 2 years?":"730",
"How many years are there in a half a century?":"50"
}
question = list (Question_list.keys())
#input answer here
while True:
if not question:
break
ques = random.choice(question)
print(ques)
while True:
answer = input('Your Answer: ' )
# if correct, moves onto next question
if answer.lower() == Question_list[ques]:
print("Correct Answer")
break
else:
#if wrong, Asks the same question again
print("Wrong Answer. Try again")
question.remove(ques)
play_again = input("Would you like to play the quiz again\n")
if play_again == "yes":
print()
# i want it to repeat the quiz but don't know how to do that.
# this part works fine
else:
print("Thanks for playing")
time.sleep(2)
exit()
You already have an infinite loop for asking multiple questions. You can also put an infinite loop to play multiple quizes like this:
import random
import time
Question_list = {
"How many years are there in a millennium?":"1000",
"How many days are there in 2 years?":"730",
"How many years are there in a half a century?":"50"
}
while True:
question = list (Question_list.keys())
#input answer here
while True:
if not question:
break
ques = random.choice(question)
print(ques)
while True:
answer = input('Your Answer: ' )
# if correct, moves onto next question
if answer.lower() == Question_list[ques]:
print("Correct Answer")
break
else:
#if wrong, Asks the same question again
print("Wrong Answer. Try again")
question.remove(ques)
play_again = input("Would you like to play the quiz again\n")
#if answer is not yes, break the outer infinite loop
if play_again != "yes":
print("Thanks for playing")
break
time.sleep(2)
exit()
You could try this, use the while True outside, then it could always run if play_again is yes and add break in the bottom if want to stop.
import random
import time
while True:
Question_list = {
"How many years are there in a millennium?":"1000",
"How many days are there in 2 years?":"730",
"How many years are there in a half a century?":"50"
}
question = list (Question_list.keys())
#input answer here
while True:
if not question:
break
ques = random.choice(question)
print(ques)
while True:
answer = input('Your Answer: ' )
# if correct, moves onto next question
if answer.lower() == Question_list[ques]:
print("Correct Answer")
break
else:
#if wrong, Asks the same question again
print("Wrong Answer. Try again")
question.remove(ques)
play_again = input("Would you like to play the quiz again\n")
if play_again == "yes":
print()
# i want it to repeat the quiz but don't know how to do that.
else:
break
# this part works fine
print("Thanks for playing")
time.sleep(2)
exit()
You can set a while loop which repeats the question until a certain condition is met. Use a variable which is true and while it is true the game continues, but once a condition is met which should end the game, switch the variable to false and the while loop should stop.

Text based adventure challenge issues

I'm new at coding and I've been trying this text-based adventure game. I keep running into syntax error and I don't seem to know how to solve this. Any suggestions on where I could have gone wrong would go a long way to helping.
def play_again():
print("\nDo you want to play again? (y/n)")
answer = input(">")
if answer == "y":
play_again()
else:
exit()
def game_over(reason):
print("\n", reason)
print("Game Over!!!")
play_again()
def diamond_room():
print("\nYou are now in the room filled with diamonds")
print("what would you like to do?")
print("1) pack all the diamonds")
print("2) Go through the door")
answer = input(">")
if answer == "1":
game_over("The building collapsed bcos the diamonds were cursed!")
elif answer == "2":
print("You Win!!!")
play_again()
else:
game_over("Invalid prompt!")
def monster_room():
print("\nYou are now in the room of a monster")
print("The monster is sleeping and you have 2 choices")
print("1) Go through the door silently")
print("2) Kill the monster and show your courage")
answer = input(">")
if answer == "1":
diamond_room()
elif answer == "2":
game_over("You are killed")
else:
game_over("Invalid prompt")
def bear_room():
print("\nThere's a bear in here!")
print("The bear is eating tasty honey")
print("what would you like to do?")
print("1) Take the honey")
print("2) Taunt the bear!")
answer = input(">").lower()
if answer == "1":
game_over("The bear killed you!!!")
elif answer == "2":
print("The bear moved from the door, you can now go through!")
diamond_room()
else:
game_over("Invalid prompt")
def start():
print("Do you want to play my game?")
answer = input(">").lower()
if answer == "y":
print("\nyou're standing in a dark room")
print("you have 2 options, choose l or r")
answer == input(">")
if answer == "l":
bear_room()
elif answer == "r":
monster_room()
else:
game_over("Invalid prompt!")
start()
it keeps popping error and i cant detect where the error is coming from.
You have 2 problems.
Assertion instead of Assignment.
Calling the wrong function.
For 1. You have
def start():
print("Do you want to play my game?")
answer = input(">").lower()
if answer == "y":
print("\nyou're standing in a dark room")
print("you have 2 options, choose l or r")
answer == input(">")
if answer == "l":
bear_room()
elif answer == "r":
monster_room()
else:
game_over("Invalid prompt!")
You should uuse answer = input(">") and not answer ==.
For 2. You have
def play_again():
print("\nDo you want to play again? (y/n)")
answer = input(">")
if answer == "y":
play_again()
else:
exit()
You should call start not play_again
In this part of your code, you should change you last line:
if answer == "y":
print("\nyou're standing in a dark room")
print("you have 2 options, choose l or r")
answer == input(">")
to answer = input(">").lower()
use = to assign a value to a variable, and use == to check the similarity(ex. in an if)
it is better to make the user input to lower case as other parts of your code, because in next lines of you've checked its value in an if condition with lower case (r and l).
3)another problem is that in def play_again(): you have to call start() function, sth like this:
print("\nDo you want to play again? (y/n)")
answer = input(">")
if answer == "y":
start()

Number guessing game python (make the game ask to play every time)

import random
def game():
number = random.randint(0, 10)
guess = 0
print("Guess a number from 0-10:")
while number != guess:
try:
guess = int(input(""))
if number != guess:
print("you haven't guessed the number, keep trying")
else:
print("You guessed it!")
break
except ValueError:
print("Please enter an integer")
game()
choose = input("Would you like to play again?\n")
while choose == "yes":
game()
if choose == "no":
break
I'm trying to add a feature where every time the game is won, the user has the option to play again, right now the game runs, then you win, it asks if you want to play again, you say yes, it runs again then you win and it runs again without asking.
Choose is only set one time, so the while-loop never breaks. You could simply add:
choose = input("Would you like to play again?\n")
while choose == "yes":
game()
choose = input("Would you like to play again?\n")
if choose == "no":
break
Or somewhat more elegantly:
choose = input("Would you like to play again?\n")
while choose != "no":
game()
choose = input("Would you like to play again?\n")
You're currently only asking the user if he wants to play again once, and keep it going with the while loop. You should ask the user again after every time the game is played, like so:
choose = input("Would you like to play again?\n")
while choose == "yes":
game()
choose = input("Would you like to play again?\n") #add this line
if choose == "no":
break

Categories