Beginner's Python- What is my Mistake? [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
This is Sheldon Cooper's Friendship Algorithm.
Python code.
Please help me find the mistake.
I doubled checked it x200 times but can't seem to find it.
I'm in high school so this would be pretty easy for all of you.
.
print("The Friendship Algorithm \n By Dr. Sheldon Cooper Ph.D")
print("Place a phone call")
home = input("Are they home?")
if home == "yes":
print("Ask, would you like to share a meal?")
meal = input("What is their response?")
.
if meal == "yes":
print("Dine together")
print("Begin friendship!")
elif meal == "no":
print("Ask, do you enjoy a hot beverage?")
.
hot_beverage = input("What is their response?")
if hot_beverage == "yes":
beverage = input("Tea, coffee or cocoa?")
if beverage == "tea":
print("Have tea")
print("Begin friendship!")
elif beverage == "coffee":
print("Have coffee")
print("Begin friendship!")
elif beverage == "cocoa":
print("Have cocoa")
print("Begin friendship!")
else:
print("That is not an option")
.
elif hot_beverage == "no":
while interest_cycle:
print("Recreational activities: \n Tell me one of your interests.")
interest = input("Do you share that interest?")
if n > 6:
print("Choose least objectional interest")
interest_cycle = False
elif interest == "no":
print("Ask for another")
n = n + 1
elif interest == "yes":
interest_cycle = False
print("Ask, why don't we do that together?")
print("Partake in interest")
print("Begin friendship!")
.
else:
print("That is not an option")
.
elif home == "no":
print("Leave message")
print("Wait for callback")
else:
print("That is not an option")

Very nicely written ! I made a few modifications to make it work on my computer.
Firstly I replaced all the input() with raw_input, this way you won't have to enter your answer with quotions.
Secondly, I had to rework the indentations on my side.
And lastly, I edited your while loop to hopefully make it look more like the actual flow chart.
If I were you, I would also add some conditions to prevent the program from ending if the user enters a bad value.
I hope it works for you !
print("The Friendship Algorithm \n By Dr. Sheldon Cooper Ph.D")
print("Place a phone call")
home = raw_input("Are they home?")
if home == "yes":
print("Ask, would you like to share a meal?")
meal = raw_input("What is their response?")
if meal == "yes":
print("Dine together")
print("Begin friendship!")
elif meal == "no":
print("Ask, do you enjoy a hot beverage?")
hot_beverage = raw_input("What is their response?")
if hot_beverage == "yes":
beverage = raw_input("Tea, coffee or cocoa?")
if beverage == "tea":
print("Have tea")
print("Begin friendship!")
elif beverage == "coffee":
print("Have coffee")
print("Begin friendship!")
elif beverage == "cocoa":
print("Have cocoa")
print("Begin friendship!")
else:
print("That is not an option")
elif hot_beverage == "no":
n = 0
while n<= 6:
print("Recreational activities: \n Tell me one of your interests.")
interest = raw_input("Do you share that interest?")
if interest == "no":
print("Ask for another")
n = n + 1
elif interest == "yes":
print("Ask, why don't we do that together?")
print("Partake in interest")
print("Begin friendship!")
break
else:
print("That is not an option")
elif home == "no":
print("Leave message")
print("Wait for callback")
else:
print("That is not an option")

For starters, the while loop will not execute because you have not set the value for interest_cycle hence it will return None whereas in python None is equivalent to False when converted to boolean.
Please refer to this for more info: https://www.digitalocean.com/community/tutorials/how-to-construct-while-loops-in-python-3
And also check your indentation on the if home == "yes":, elif home == "no":
and else:.
Good work on the code. I like the readability.

Related

I came across what is most likely is an indentation error, but I can't figure it out [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 23 days ago.
Improve this question
I'm programming a text adventure game in python, and while fixing some syntax. I got what I think is an indentation error, but I can't seem to be able to fix it. My expected results were for the opening part in the game to run, me enter the main game, and be able to test the inventory system. now my question may be silly, but I'm just starting in python. the specific error is:
File "main.py", line 56
else:
^
SyntaxError: invalid syntax
and my code is:
import random
room = random.randrange(100,400)
door = 0
closets = 0
invintorySlots = 0
# Menu
print(" --------DOORS--------")
answer = input(" < Press enter to continue >")
#intro
print("You enter the hotel, its storming outside")
print("The receptionist, a girl with black hair and brown eyes says hi to you.")
print("Her: Your reserved room is number",room)
print(" ")
answer = input("(A): Thanks! (B): Your cute (C): ...")
if answer == "a":
print("You: Thanks!")
print("Her: No problem!")
elif answer == "b":
print("You: Your cute.")
print("Her: Im not really into dating right now.. Thank you though!")
elif answer == "c":
print("Her: Not much of a talker eh?")
print("You walk to your room")
print("You enter but its not your room. its another room, with another door.")
#main game
door += 1
print("You enter door",door)
if closets > 0:
if random.randrange(1,2) == 2:
print("The lights flicker")
answer = input("(A): Hide in the closet (B): go to the next door (C): look around")
if answer == "a":
print("You hide in a closet")
elif answer == "b":
door += 1
print("You enter door",door)
elif answer == "c":
print("You look around")
if random.randrange(1,10) == 1:
print("You found a lighter!")
#Each item has a number ID
if invintorySlots == 0:
invintorySlots = 1
print("You got a lighter")
else:
print("Would you like to replace your current item with this one?")
answer = input("(A): yes (B): no
if answer == "a":
print("You swapped your item for a lighter")
else:
print("You kept your lighter")
else:
answer = input("(A): Go to the next door (B): say your name (C): ...")
answer = input("(A): yes
Should be
answer = input("(A): yes (B): no")
And your if else should not be tabbed over after.
You have an extra else statement at the end which will never be reached.
Your code should look like this:
import random
room = random.randrange(100,400)
door = 0
closets = 0
invintorySlots = 0
# Menu
print(" --------DOORS--------")
answer = input(" < Press enter to continue >")
#intro
print("You enter the hotel, its storming outside")
print("The receptionist, a girl with black hair and brown eyes says hi to you.")
print("Her: Your reserved room is number",room)
print(" ")
answer = input("(A): Thanks! (B): Your cute (C): ...")
if answer == "a":
print("You: Thanks!")
print("Her: No problem!")
elif answer == "b":
print("You: Your cute.")
print("Her: Im not really into dating right now.. Thank you though!")
elif answer == "c":
print("Her: Not much of a talker eh?")
print("You walk to your room")
print("You enter but its not your room. its another room, with another door.")
#main game
door += 1
print("You enter door",door)
if closets > 0:
if random.randrange(1,2) == 2:
print("The lights flicker")
answer = input("(A): Hide in the closet (B): go to the next door (C): look around")
if answer == "a":
print("You hide in a closet")
elif answer == "b":
door += 1
print("You enter door",door)
elif answer == "c":
print("You look around")
if random.randrange(1,10) == 1:
print("You found a lighter!")
#Each item has a number ID
if invintorySlots == 0:
invintorySlots = 1
print("You got a lighter")
else:
print("Would you like to replace your current item with this one?")
answer = input("(A): yes (B): no")
if answer == "a":
print("You swapped your item for a lighter")
else:
print("You kept your lighter")

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

simple python text adventure game errors [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I got this sample rpg text adventure game online and im trying to understand the codes so that i can use it as a reference to develop my own text adventure game in the future. However, i am currently facing the error "gold is not defined at line 121 and i suspect is cause by indentation error. Although this is the error im facing so far, i believed that are more mistakes in the codes which i am glad for anyone to point it out.Thanks!
# gold = int(100)
inventory = ["sword", "armor", "potion"]
print("Welcome hero")
name = input("What is your name: ")
print("Hello", name,)
# role playing program
#
# spend 30 points on strenght, health, wisdom, dexterity
# player can spend and take points from any attribute
classic = {"Warrior",
"Archer",
"Mage",
"Healer"}
print("Choose your race from", classic,)
classicChoice = input("What class do you choose: ")
print("You are now a", classicChoice,)
# library contains attribute and points
attributes = {"strenght": int("0"),
"health": "0",
"wisdom": "0",
"dexterity": "0"}
pool = int(30)
choice = None
print("The Making of a Hero !!!")
print(attributes)
print("\nYou have", pool, "points to spend.")
while choice != "0":
# list of choices
print(
"""
Options:
0 - End
1 - Add points to an attribute
2 - remove points from an attribute
3 - Show attributes
"""
)
choice = input("Choose option: ")
if choice == "0":
print("\nYour hero stats are:")
print(attributes)
elif choice == "1":
print("\nADD POINTS TO AN ATTRIBUTE")
print("You have", pool, "points to spend.")
print(
"""
Choose an attribute:
strenght
health
wisdom
dexterity
"""
)
at_choice = input("Your choice: ")
if at_choice.lower() in attributes:
points = int(input("How many points do you want to assign: "))
if points <= pool:
pool -= points
result = int(attributes[at_choice]) + points
attributes[at_choice] = result
print("\nPoints have been added.")
else:
print("\nYou do not have that many points to spend")
else:
print("\nThat attribute does not exist.")
elif choice == "2":
print("\nREMOVE POINTS FROM AN ATTRIBUTE")
print("You have", pool, "points to spend.")
print(
"""
Choose an attribute:
strenght
health
wisdom
dexterity
"""
)
at_choice = input("Your choice: ")
if at_choice.lower() in attributes:
points = int(input("How many points do you want to remove: "))
if points <= int(attributes[at_choice]):
pool += points
result = int(attributes[at_choice]) - points
attributes[at_choice] = result
print("\nPoints have been removed.")
else:
print("\nThere are not that many points in that attribute")
else:
print("\nThat attribute does not exist.")
elif choice == "3":
print("\n", attributes)
print("Pool: ", pool)
else:
print(choice, "is not a valid option.")
While True:
print("Here is your inventory: ", inventory)
print("What do you wish to do?")
print("please input shop, tavern, forest.")
choice = input("Go to the shop, go to the tavern, go to the forest: ")
crossbow = int(50)
spell = int(35)
potion = int(35)
if choice == "shop":
print("Welcome to the shop!")
print("You have", gold,"gold")
buy = input("What would you like to buy? A crossbow, a spell or a potion: ")
if buy == "crossbow":
print("this costs 50 gold")
answer = input("Do you want it: ")
if answer == "yes":
print("Thank you for coming!")
inventory.append("crossbow")
gold = gold - crossbow
print("Your inventory is now:")
print(inventory)
print("Your gold store now is: ", gold)
if answer == "no":
print("Thank you for coming!")
if buy == "spell":
print("this costs 35 gold")
answear2 = input("Do you want it: ")
if answear2 == "yes":
print("Thank you for coming!")
inventory.append("spell")
gold = gold - spell
print("Your inventory is now:")
print(inventory)
if answear2 == "no":
print("Thank you for coming!")
if buy == "potion":
print("this costs 35 gold")
answear3 = input("Do you want it: ")
if answear3 == "yes":
print("Thank you for coming!")
inventory.append("spell")
gold = gold - potion
print("Your inventory is now:")
print(inventory)
if answear3 == "no":
print("Thank you for coming!")
choice = input("Go to the shop, go to the tavern, go to the forest: ")
while choice != "shop" or "tavern" or "forest":
print("Not acepted")
print("What do you wish to do?")
print("please input shop, tavern, forest.")
choice = input("Go to the shop, go to the tavern, go to the forest: ")
if choice == "teavern":
print("You enter the tavern and see a couple of drunken warriors singing, a landlord behind the bar and a dodgy figure sitting at the back of the tavern.")
tavernChoice = input("Would you like to talk to the 'drunken warriors', to the 'inn keeper', approach the 'dodgy figure' or 'exit'")
if tavernChoice == "drunken warriors":
print("You approach the warriors to greet them.")
print("They notice you as you get close and become weary of your presence.")
print("As you arrive at their table one of the warriors throughs a mug of ale at you.")
if dexterity >= 5:
print("You quickly dodge the mug and leave the warriors alone")
else:
print("You are caught off guard and take the mug to the face compleatly soaking you.")
print("The dodgy figure leaves the tavern")
From a quick glance at it. #gold = int(100) is commented out on line 1.
This causes a issue because it doesn't know what gold is. it isn't defined. remove the # before it.

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

I am having trouble vaildating my code.I need my code to loop untill a valid answer is inputted

I am struggling with this piece of Python code. The problem is,when a user enters something wrong I need my code to keep looping until they input a valid answer.
This is how the code is supposed to work: User is prompted to choose a drink, then a cuisine, then a dish. After this, the program displays the order the user wanted.
Order = [ 'No drink', 'No food' ]
Yesses = [ 'y', 'yes', 'yep', 'okay', 'sure' ]
DRINK = 0
FOOD = 1
print("Welcome to Hungary house!")
print("")
print("First, let me get your drink order, if any.")
answer = input("Would you like something to drink? ").lower()
if answer in Yesses:
print("What drink would you prefer?")
print ("1: Fanta")
print ("2: Coke")
print ("3: Pepsi")
print ("4: Sprite")
choice = input("Please enter a drink from the menu above\n").lower()
if choice == "1" or choice == "fanta":
Order[DRINK] = "Fanta"
if choice == "2" or choice == "coke":
Order[DRINK] = "Coke"
if choice == "3" or choice == "pepsi":
Order[DRINK] = "Pepsi"
if choice == "4" or choice == "sprite":
Order[DRINK] = "Sprite"
print ("You have chosen: " + Order[DRINK])
print("")
print("Now, let me get your food order, if any.")
answer = input("Do you want any food (Y/N)? ").lower()
if answer in Yesses:
answer = input("Do you want Italian,Indian or Chinese food?\n").lower()
if answer == "indian":
answer = input("Do you want Curry or Onion Bhaji?\n").lower()
if answer == "curry":
Order[FOOD] = "Curry"
answer = input("With your curry, do you want Rice or Naan?\n").lower()
if answer == "rice":
Order.append("- with rice")
if answer == "naan":
Order.append("- with naan")
if answer == "onion bhaji" or answer == "bhaji":
Order[FOOD] = "Onion Bhaji"
answer = input("With your bhaji, do you want Chili or Peppers?\n").lower()
if answer == "chili":
Order.append("- with chili")
if answer == "peppers":
Order.append("- with peppers")
if answer == "chinese":
answer = input("Do you want Chicken Wings or Noodles?\n").lower()
if answer == "chicken wings" or answer == "wings":
Order[FOOD] = "Chicken Wings"
answer = input("With your wings, do you want Chips or Red Peppers?\n").lower()
if answer == "chips":
Order.append("- with Chips")
if answer == "red peppers" or answer == "peppers":
Order.append("- with Red Peppers")
if answer == "noodles":
Order[FOOD] = "Noodles"
answer = input("With your noodles, do you want Meatballs or Chicken?\n").lower()
if answer == "meatballs":
Order.append("- with meatballs")
if answer == "chicken":
Order.append("- with chicken")
if answer == "italian":
answer = input("Do you want Pasta or Noodles?\n").lower()
if answer == "pasta" or answer == "Pasta":
Order[FOOD] = "Pasta"
answer = input("With your Pasta, do you want Vegetarian Toppings or meat toppings?\n").lower()
if answer == "vegetarian Toppings":
Order.append("- with Vegetarian Toppings")
if answer == "meat toppings" or answer == "meat":
Order.append("- with Meat toppings")
if answer == "pizza":
Order[FOOD] = Pizza
answer = input("With your Pizza, do you want Grilled chicken or Chicken?\n").lower()
if answer == "Grilled chicken":
Order.append("- Grilled chicken")
if answer == "seasonal vegetables":
Order.append("- seasonal vegetables")
try:
if Order[2]:
print("You have ordered the following. Your order number is 294")
print("")
print(" ", Order[DRINK])
print(" ", Order[FOOD])
except:
pass
try:
if Order[2]:
print(" ", Order[2])
except:
print("")
print("No food or drink?! Get out!")
try:
if Order[2]:
print("""
Your order should arrive within 10-50 minutes. If you wish to cancel,
please contact us at 077 3475 8675309. Thank you for your patronage!
""")
except:
pass
As an example, for the drink part to continually loop over until the user enters something valid:
while choice != "1" or choice != "2" or choice != "3" or choice != "4":
choice = input("Please enter a valid drink: ")
if choice == "1" or choice == "fanta":
Order[DRINK] = "Fanta"
if choice == "2" or choice == "coke":
Order[DRINK] = "Coke"
if choice == "3" or choice == "pepsi":
Order[DRINK] = "Pepsi"
if choice == "4" or choice == "sprite":
Order[DRINK] = "Sprite"
I think this would work because it would keep iterating over the loop until the condition is met. And then once the loop is completed, it will execute the code below it.
Use a while loop and break once you're satisfied:
drink = None
while drink is None:
choice = input("Please enter a drink from the menu above\n").lower()
if choice == "1" or choice == "fanta":
drink = "Fanta"
elif choice == "2" or choice == "coke":
drink = "Coke"
elif choice == "3" or choice == "pepsi":
drink = "Pepsi"
elif choice == "4" or choice == "sprite":
drink = "Sprite"
Order[DRINK] = drink
while True:
choice = input("Please enter a drink from the menu above\n").lower()
if choice == "1" or choice == "fanta":
Order[DRINK] = "Fanta"
break
if choice == "2" or choice == "coke":
Order[DRINK] = "Coke"
break
if choice == "3" or choice == "pepsi":
Order[DRINK] = "Pepsi"
break
if choice == "4" or choice == "sprite":
Order[DRINK] = "Sprite"
break
This is pretty clunky, but it's most in line with what you've already got. I'd suggesting moving most of these items into lists like this, but that's a bit of a refactor for this answer. Consider the below, but really all you have to do is stick your input into an infinite loop and then break when the user gets it right.
drink_list = ['fanta', 'coke', 'pepsi', 'sprite']
if choice in drink_list:
break
Update:
Here is the first part of your code with a while (condition):
Order = [ 'No drink', 'No food' ]
Yesses = [ 'y', 'yes', 'yep', 'okay', 'sure' ]
DRINK = 0
FOOD = 1
print("Welcome to Hungary house!")
print("")
print("First, let me get your drink order, if any.")
answer = input("Would you like something to drink? ").lower()
if answer in Yesses:
print("What drink would you prefer?")
print ("1: Fanta")
print ("2: Coke")
print ("3: Pepsi")
print ("4: Sprite")
correct = False
while (!correct):
choice = input("Please enter a drink from the menu above\n").lower()
if (choice == "1" or choice == "fanta"):
Order[DRINK] = "Fanta"
correct = True
elif (choice == "2" or choice == "coke"):
Order[DRINK] = "Coke"
correct = True
elif (choice == "3" or choice == "pepsi"):
Order[DRINK] = "Pepsi"
correct = True
elif (choice == "4" or choice == "sprite"):
Order[DRINK] = "Sprite"
correct = True
print ("You have chosen: " + Order[DRINK])
Original answer:
So if it's using input() you can get away with doing a while loop until the statement is true. So put all the code in a loop and fulfill the Boolean when correct. For example:
correct = false
while (!correct):
var = input ("your statement")
if var == "good":
correct = true
#next stuff

Categories