How do I have multiple optional inputs? [duplicate] - python

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")

Related

how to make it that it does not repeat?

I know that a "not repeat with random from a list" is probably seen as a info you can find, but as someone who does not have a lot of knowledge of python yet, i cannot seem to understand those answers or they do not work for my problem. So I hope any of you are able to help.
as my first small project I am building a truth or dare program, and now I am at the point that I want to make it that the questions cannot be asked twice, and that if the truth questions are all done it prints that announcement, and I want the same for my dare questions.
here is my program so far, sorry if it is messy:
import random
import time
truth = ["If you could be invisible, what is the first thing you would do?",
"What is a secret you kept from your parents?",
"What is the most embarrassing music you listen to?",
"What is one thing you wish you could change about yourself?",
"Who is your secret crush?"]
dare = ["Do a free-style rap for the next minute",
"Let another person post a status on your behalf.",
"Hand over your phone to another player who can send a single text saying anything they want to anyone they want.",
"Let the other players go through your phone for one minute.",
"Smell another player's armpit."]
print("Hello, and welcome to my truth or dare show, just type truth or type dare to get a question!")
lives = 3
while lives > 0:
choice = input("truth or dare?: ").lower()
time.sleep(0.5)
if choice == "truth":
print(random.choice(truth))
time.sleep(0.5)
while True:
answer_truth = input("want to answer? type yes or no: ").lower()
if answer_truth == "yes":
input("> ").lower()
print("good answer")
time.sleep(0.5)
print(f"you have {lives} lives left")
break
elif answer_truth == "no":
print("you lost a life!")
time.sleep(1)
lives -= 1
print(f"you have {lives} lives left")
break
else:
print("that is not an option")
elif choice == "dare":
print(random.choice(dare))
time.sleep(0.5)
while True:
do_dare = input(f"did you do the dare? type yes or no: ").lower()
if do_dare == "yes":
print("well done!")
time.sleep(0.5)
print(f"you have {lives} lives left")
break
elif do_dare == "no":
print("you lost a life!")
lives -= 1
time.sleep(0.5)
print(f"you have {lives} lives left")
break
else:
print("that is not an option")
else:
print("that is not an option")
time.sleep(0.5)
print("GAME OVER!")
This should work:
choice = random.choice(truth)
time.sleep(0.5)
# inside the loop
truth.remove(choice)
if len(truth) == 0:
print("all questions are done")
do the same for dare
You probably want a construct like this:
from random import shuffle
ls = ["a", "b", "c"]
shuffle(ls)
lives = 3
while lives > 0 and ls:
current_question = ls.pop()
... # Rest of your code
So you want to select a random option, but then no longer have it in the set that you select random things from in the future.
If you imagine it physically, you have a jar list that has papers item's in it and you want to take them out at random. Obviously, any that you take out can not be taken out again.
We can accomplish this by removing the item from the list after it's 'picked'
To answer your question about having it let them know there are no more truths or no more dares, we can simply add a conditional to the whole truth segment and one to the whole dare segment as well, then further, if both run out, end the game.
while lives > 0 and (len(truth)>0 or len(dare>0)):
# Rest of the program
if choice == "truth":
if len(truth) > 0:
# Code
else:
print("there are no more truths (existential crisis), maybe try a dare instead")
elif choice == "dare":
if len(dare)>0:
# Code
else:
print("there are no more dares *sigh of releif*, maybe try a truth instead")

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

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

Is there any way to make this code simpler? I feel like there should be but I am very new to Python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
def life():
print("You wake up")
eat = input("are you hungry? Please Enter y or n.")
if eat.upper() == "Y":
print("I predict you will eat breakfast")
elif eat.upper() == "N":
print("I predict you will skip breakfast")
while eat.upper() not in ("Y","N"):
print("input not accepted")
eat = input("are you hungry? Please Enter y or n.")
if eat.upper() == "Y":
print("I predict you will eat breakfast")
elif eat.upper() == "N":
print("I predict you will skip breakfast")
print("You leave the house")
day = input("is it cloudy? please enter y or n")
if day.upper() == "Y":
print("I predict you will bring an umbrella")
elif day.upper() == "N":
print("I predict you will wear sunglasses")
while day.upper() not in ("Y","N"):
print("input not accepted")
day = input("is it cloudy? please enter y or n")
if day.upper() == "Y":
print("I predict you will bring an umbrella")
elif day.upper() == "N":
print("I predict you will wear sunglasses")
print("You go out for dinner")
food = input("Do you want meat? please enter y or n")
if food.upper() == "Y":
print("I predict you will order steak!")
elif food.upper() == "N":
pass
while food.upper() not in ("Y", "N"):
print("input not accepted")
food = input("Do you want meat? please enter y or n")
if food.upper() == "Y":
print("I predict you will order steak!")
elif food.upper() == "N":
pass
pasta = input("Do you want Pasta: please enter y or n")
if pasta.upper() == "Y":
print("I predict you will order spaghetti and meatballs!!")
elif pasta.upper() == "N":
print("I predict you will order salad.")
while pasta.upper() not in ("Y", "N"):
print("input not accepted")
pasta = input("Do you want Pasta: please enter y or n")
if pasta.upper() == "Y":
print("I predict you will order spaghetti and meatballs!!")
elif pasta.upper() == "N":
print("I predict you will order salad.")
life()
I feel like it is unnecessary to repeat multiple lines of code in the while statement. Is there any way to make the while statement go to a previous line of code and run it from there instead of re-entering the same code back into the while statement. The code seems to run fine but I would like it to be less clunky if possible.
Thanks!
There are several modifications I would suggest.
Use inline conditional statements <expression1> if <condition> else <expression2>
Use string formatting "Today is {}".format(date)
So you can write
s = "eat" if eat.upper() == "Y" else "skip" if eat.upper() == "N" else ""
print("I predict you will {} breakfast".format(s))
Be sure to check that eat.upper() is "Y" or "N" first, or the code would fail.
Since your code for eat and day are similar, you could also use a function to simplify your code.

Why "While" doesn't show anything after input command? [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 3 years ago.
Just i did somethin wrong with while loop i supposed
After print menu section u can input something but than program ends.
print("Welcome in American Roulette")
rules=("blabla rules of roulette")
import random
while True:
print("Enter 'rules' to show rules")
print("Enter 'play' to play the game")
print("Enter 'author' to show info about creator")
print("Enter 'quit' to end the program")
user_input=input()
if user_input=="quit" or "Quit":
break
elif user_input=="rules" or "rule" or "Rules" or "Rule":
print(rules)
elif user_input=="play":
bet=int(input("Place your bet\n"))
amount=float(input("How much you want to bet?"))
spin=random.randint(0,36)
if bet>36:
print("You need to bet number beetwen 0 and 36!")
elif bet<0:
print("You need to bet number beetwen 0 and 36")
elif spin==bet:
print("You won",amount*35)
print("Now you have",start-amount+amount*35)
else:
print("You lose")
elif user_input=="author":
print("Jacob X")
else:
print("Unknown command")
Added some text here becouse my code is mostly code ffs
Your first if should be:
if user_input.lower() == "quit":
break
or
if user_input == "quit" or user_input == "Quit":
break
You are missing the second user_input on the conditional. As "Quit" is not an empty string it evaluates to True and your while loop will break.
This is also the case for this elif:
elif user_input=="rules" or "rule" or "Rules" or "Rule":

How can I return my code to the start of the code?

I've been trying to return my code to the beginning after the player chooses 'yes' when asked to restart the game. How do I make the game restart?
I've tried as many solutions as possible and have ended up with this code. Including continue, break, and several other obvious options.
import time
def start():
score = 0
print("Welcome to Atlantis, the sunken city!")
time.sleep(1.5)
print("You are the first adventurist to discover it!")
time.sleep(1.5)
print("Do you explore or talk to the merpeople?")
time.sleep(1.5)
print("Type 1 to explore Atlantis alone.")
time.sleep(1.5)
print("Type 2 to talk to the resident merpeople.")
start()
def surface():
print("You return to the surface.")
print("When you go back to Atlantis it's gone!")
print("Your findings are turned to myth.")
print("The end!")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = -1
def castle():
print("The merpeople welcome you to their castle.")
print("It is beautiful and you get oxygen.")
print("Now that you have your oxygen, you can either go to the surface or explore Atlantis alone.")
score = 1
print("To explore alone enter 5. To go to the surface enter 6.")
def drowndeath():
print("You begin to explore around you.")
print("You avoid the merpeople who avoid you in return.")
print("But, OH NO, your oxygen begins to run out!")
print("You run out of air and die.")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = 4
def merpeople():
print("The merpeople talk kindly to you.")
print("They warn you that your oxygen tank is running low!")
print("You can follow them to their castle or go back to the surface.")
print("Type 3 to go to the castle or 4 to go to the surface.")
score = 5
def alone():
print("You begin to explore alone and discover a secret caven.")
print("You go inside and rocks trap you inside!")
print("You die underwater.")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = 6
def famous():
print("You come back to land with new discoveries!")
print("Everyone loves you and the two worlds are now connected!")
print("You win!")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
def choice_made():
choice = input("Make your decision!\n ")
if choice == "1":
drowndeath()
elif choice == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice_made()
choice_made()
def choice2_made():
choice2 = input("What do you do?\n ")
if choice2 == "4":
surface()
elif choice2 == "3":
castle()
elif choice2 == "yes":
start()
elif choice2 == "no":
exit()
else:
print("Please enter a valid answer.")
choice2_made()
choice2_made()
def choice3_made():
choice3 = input("Make up your mind!\n ")
if choice3 == "5":
alone()
if choice3 == "6":
famous()
else:
print("Please enter a valid answer.")
choice3_made()
choice3_made()
def restart_made():
restart = input("Type your answer!\n ")
if restart == "yes":
sys.exit()
elif restart == "no":
exit()
else:
print("Please choose yes or no!")
restart_made()
restart_made()
while True:
choice = input("Make your decision!\n ")
if choice == "1":
drowndeath()
elif choice == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice_made()
choice_made()
while True:
choice2 = input("What do you do?\n ")
if choice2 == "4":
surface()
if choice2 == "3":
castle()
else:
print("Please enter a valid answer.")
choice2_made()
choice2_made()
while True:
choice3 = input("Make up your mind!\n ")
if choice3 == "5":
alone()
if choice3 == "6":
famous()
if choice3 == "1":
drowndeath()
if choice3 == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice3_made()
choice3_made()
while True:
restart = input("Type your answer!\n ")
if restart == "yes":
sys.exit()
elif restart == "no":
exit()
else:
print("Please choose yes or no!")
restart_made()
restart_made()
I want for my code to restart completely when 'yes' is typed after given the option.
In general, if you want to be able to 'go back to the beginning' of something, you want to have a loop that contains everything. Like
while True:
""" game code """
That would basically repeat your entire game over and over. If you want it to end by default, and only restart in certain situations, you would do
while True:
""" game code """
if your_restart_condition:
continue # This will restart the loop
if your_exit_condition:
break # This will break the loop, i.e. exit the game and prevent restart
""" more game code """
break # This will break the loop if it gets to the end
To make things a little easier, you could make use of exceptions. Raise a RestartException whenever you want to restart the loop, even from within one of your functions. Or raise an ExitException when you want to exit the loop.
class RestartException(Exception):
pass
class ExitException(Exception):
pass
while True:
try:
""" game code """
except RestartException:
continue
except ExitException:
break
break
You have two main options.
First option: make a main function that, when called, executes your script once. Then, for the actual execution of the code, do this:
while True:
main()
if input("Would you like to restart? Type 'y' or 'yes' if so.").lower() not in ['y', 'yes']:
break
Second, less compatible option: use os or subprocess to issue a shell command to execute the script again, e.g os.system("python3 filename.py").
EDIT: Despite the fact this is discouraged on SO, I decided to help a friend out and rewrote your script. Please do not ask for this in the future. Here it is:
import time, sys
score = 0
def makeChoice(message1, message2):
try:
print("Type 1 "+message1+".")
time.sleep(1.5)
print("Type 2 "+message2+".")
ans = int(input("Which do you choose? "))
print()
if ans in (1,2):
return ans
else:
print("Please enter a valid number.")
return makeChoice(message1, message2)
except ValueError:
print("Please enter either 1 or 2.")
return makeChoice(message1, message2)
def askRestart():
if input("Would you like to restart? Type 'y' or 'yes' if so. ").lower() in ['y', 'yes']:
print()
print("Okay. Restarting game!")
playGame()
else:
print("Thanks for playing! Goodbye!")
sys.exit(0)
def surface():
print("You return to the surface.")
print("When you go back to Atlantis it's gone!")
print("Your findings are turned to myth.")
print("The end!")
def castle():
print("The merpeople welcome you to their castle.")
print("It is beautiful and you get oxygen.")
print("Now that you have your oxygen, you can either go to the surface or explore Atlantis alone.")
def drowndeath():
print("You begin to explore around you.")
print("You avoid the merpeople who avoid you in return.")
print("But, OH NO, your oxygen begins to run out!")
print("You run out of air and die.")
def merpeople():
print("The merpeople talk kindly to you.")
print("They warn you that your oxygen tank is running low!")
print("You can follow them to their castle or go back to the surface.")
def alone():
print("You begin to explore alone and discover a secret caven.")
print("You go inside and rocks trap you inside!")
print("You die underwater.")
def famous():
print("You come back to land with new discoveries!")
print("Everyone loves you and the two worlds are now connected!")
print("You win!")
def playGame():
print("Welcome to Atlantis, the sunken city!")
time.sleep(1.5)
print("You are the first adventurer to discover it!")
time.sleep(1.5)
print("Do you explore or talk to the merpeople?")
time.sleep(1.5)
ans = makeChoice("to explore Atlantis alone", "to talk to the resident merpeople")
if ans == 1:
drowndeath()
askRestart()
merpeople()
ans = makeChoice("to go to the castle", "to return to the surface")
if ans == 2:
surface()
askRestart()
castle()
ans = makeChoice("to return to the surface", "to explore alone")
if ans == 1:
famous()
else:
alone()
askRestart()
playGame()

Categories