I'm writing a program for myself that makes a meal plan. I want to make the meal plan customizable, so I have this method:
def getRestrictedMeals(meals):
restrictions = []
mealsR = []
In the method, I ask the user questions that customize the code and I save their answer in a list (The getRestHelp method just saves some answers as boolean.):
print("Would you like only foods you aren't allergic to?")
print("1. Yes")
print("2. No")
user = int(input("Please choose an option: "))
print()
restrictions.append(getRestHelp(user))
print("Would you like only healthy foods?")
print("1. Yes")
print("2. No")
user = int(input("Please choose an option: "))
print()
restrictions.append(getRestHelp(user))
print("Would you like only Gluten Free foods?")
print("1. Yes")
print("2. No")
user = int(input("Please choose an option: "))
print()
restrictions.append(getRestHelp(user))
print("Would you like only Vegitarian foods?")
print("1. Yes")
print("2. No")
user = int(input("Please choose an option: "))
print()
restrictions.append(getRestHelp(user))
print("What is the longest cook time you want?")
print("Please enter 1000 for any cook time.")
user = int(input())
restrictions.append(user)
Next I grab the information from each meal:
facts = []
for x in meals:
facts.append(x.getAllergy())
facts.append(x.getHealthy())
facts.append(x.getGluten())
facts.append(x.getVegitarian())
facts.append(x.getCookTime())
This is where I'm stuck. I know I need to compare the lists the add the meal to mealR if it meets the restrictions, but I'm not sure how to do that without getting into a mess of 'if' statements. I can't make sure the lists match each other because if the user answers 'No' to a question, then any meal can be added.
If the user input is Allergies = No and Healthy = Yes, I want to avoid something like this (because I would have to go deeper and deeper for each parameter):
if(restrictions[0] == 0):
if(restrictions[1] == 0):
# I would continue going here for other parameters.
else:
if(x.getHealthy()):
# I would continue going here for other parameters.
mealsR[i] = x
i+=1
else:
if(!x.getAllergy()):
# I would continue going here for other parameters.
In this case I think the best approach would be to start with a list containing all of the meals. Then you start removing meals from the list according to each of the restrictions, no need for nested conditionals. It's a good application for filter too.
Use a list of questions for all the repetitive code:
choices = [
"Would you like only foods you aren't allergic to?",
"Would you like only healthy foods?",
"Would you like only Gluten Free foods?",
"Would you like only Vegitarian foods?"
]
restrictiosn = [None] * 5
for i, choice in enumerate(choices):
user = int(input(f"""{choice}
1. Yes
2. No
Please choice an option: """))
restrictions[i] = getRestHelp(user)
If I understand the question, you just need to see if a meal is valid given a set of restrictions. You can do this using a bunch of logical operators:
def isMealValid(meal, restrictions):
return (
not (restrictions[0] and meal.getAllergy())
and (not restrictions[1] or meal.getHealthy())
and not (restrictions[2] and meal.getGluten())
and (not restrictions[3] or meal.getVegitarian())
and meal.getCookTime() <= restrictions[4]
)
You may need to adjust depending on what the meal methods return. You can then use this function in a filter or list comprehension or whatever.
Related
for my homework I am asked to create a airline reservation system. It asks if they would like to either create, cancel, display reservations, or exit the program. I am having trouble figuring out how to add the seats to the dictionary and still have them there when the code runs again. here is the basics of my code so far.
def reservation():
print("Please choose an option: ")
print("1. Reserve a Seat")
print("2. Cancel a Reservation")
print("3. Display Reservations")
print("4. Exit")
plane={}
co=int(input("Enter a choice: "))
#choose an option
if co==1:
seat=row+col
#check if seat has been taken if not reserve
if seat in plane:
plane[seat]=name
print("Seat row col has already been reserved by "+plane[key])
reservation()
else:
plane[seat]=name
print("Seat "+seat+" has been reserved for "+name)
print (seat+" "+plane[seat])
reservation()
elif co==2:
row=input("Row (1-25): ")
seat=row+col
if seat in plane:
del plane[seat]
print("The reservation for seat "+seat+" has been cancelled.")
input("Press enter to continue...")
else:
print("Seat "+seat+" is not currently reserved by anyone.")
input("Press enter to continue...")
elif co==3:
print("Reservations:")
for key in plane:
print(key+"\t"+plane[key])
elif co==4:
exit()
reservation()
In your program, I noticed that you attempt to continue calling your reservation function recursively in order to keep in acting like a loop. As noted in the comments you probably would be better off utilizing a loop for this exercise. Recursive function calls are good for things such as factorials, producing an exploded bill of materials, and such.
Also, I noticed that a few value assignments appeared to be backwards and actually would probably throw an error such as the following line of code.
if seat in plane:
plane[seat]=name
The "name" variable doesn't appear to be defined yet so that probably was cause the program to halt. With that in mind, I took a swing at doing some revisions and additions to the program in order for it to function in the spirit I believe you are after. Following is the sample code.
def reservation():
plane={}
while True:
#Choose an option
print("Please choose an option: ")
print("1. Reserve a Seat")
print("2. Cancel a Reservation")
print("3. Display Reservations")
print("4. Save Reservations")
print("5. Exit")
co=int(input("Enter a choice: "))
if co == 1:
row = int(input("Please enter a row: "))
col = int(input("Please enter a seat number (1 -6)"))
# Since lists start at index 0, the formula will be adjusted to accomodate
seat = (row - 1) * 6 + col - 1
# Check if seat has been taken if not reserve
if seat in plane:
name = plane[seat]
print("Seat", (seat + 1), "has already been reserved by " + plane[seat])
else:
name = input("Please enter your name ")
plane[seat] = name
print("Seat", (seat + 1), "has been reserved for", name)
print ((seat + 1)," ", plane[seat])
elif co == 2:
row = int(input("Row (1-25): "))
col = int(input("Seat# (1 - 6): "))
seat = (row - 1) * 6 + col - 1
if seat in plane:
del plane[seat]
print("The reservation for seat", (seat + 1), "has been cancelled.")
input("Press enter to continue...")
else:
print("Seat", (seat + 1), "is not currently reserved by anyone.")
input("Press enter to continue...")
elif co == 3:
print("Reservations:")
for key in plane:
print((key + 1), "\t", plane[key])
elif co == 4:
with open('plane.txt', 'w') as f:
for line in plane:
record = plane[line] + " " + str(line + 1)
f.write(record)
f.close()
elif co == 5:
break
reservation()
First off, I encapsulated the reservation logic within a "while" loop as suggested in the comments above. That replaces the recursive calls and replaces the "exit()" call with a simple "break" call for option #4. Next, since the plane seats are being treated like a list, I did some sleight of hand calculations to insure that the possible seat list would start at index "0". I subtracted "1" where needed for deriving and index value and added "1" back in for viewing purposes.
Here is just a brief bit of text from my terminal testing out the program.
#Una:~/Python_Programs/Reservations$ python3 Reservations.py
Please choose an option:
1. Reserve a Seat
2. Cancel a Reservation
3. Display Reservations
4. Save Reservations
5. Exit
Enter a choice: 1
Please enter a row: 4
Please enter a seat number (1 -6)2
Please enter your name Craig
Seat 20 has been reserved for Craig
20 Craig
Please choose an option:
1. Reserve a Seat
2. Cancel a Reservation
3. Display Reservations
4. Save Reservations
5. Exit
Enter a choice: 4
Please choose an option:
1. Reserve a Seat
2. Cancel a Reservation
3. Display Reservations
4. Save Reservations
5. Exit
Enter a choice: 5
Also, since you indicated that there was a need to save the reservations, I added a selection to the choices and a simple write to a text file for that. It is over simplified and you probably can find better solutions for that. Plus you will also probably want to add in some functionality to read the data back in. That could be a further embellishment to be worked on.
Anyway, please examine this code. Hopefully this will both clarify things for you plus give you ideas on how you might further embellish the functionality.
Regards.
For a school project me and my group partner made a code, I tested each function in a separate test file to see if they worked and it all looks good, but the menu just isn't working as intended. My brain can't seem to figure out where I went wrong, I would love a second opinion on this.. thank you so much <3 Here is my code!
def mainmenu():
print("Hello! Welcome to The Sprint Project Company! Please choose from 1-5: ")
print("1. Simple IPO Program")
print("2. IFs and Loop sample")
print("3. Strings and dates")
print("4. Data files and Default Values")
print("5. Quit")
while True:
choice = input("Enter choice (1-5): ")
if choice == 1:
ipo()
elif choice == 2:
ifloop()
elif choice == 3:
stringsdates()
elif choice == 4:
datafiles()
else:
break
mainmenu()
Whenever I run this it just automatically ends. I even tested by putting a print section under the else but it just skips straight to ending the code. Thank you so much for looking at my question <3
There are two points on your code.
First, the function "input()" returns a string, hence you are comparing a STRING with an INTEGER, then it evalueates to False.
It is like you are comparing 1 with '1', and they are not the same.
Second, your function mainmenu() must be put inside the loop.
Make this two changes and it will work.
while True:
mainmenu() # Add the function here.
choice = int(input("Enter choice (1-5): ")) # Change here
if choice == 1:
I'm very new to python. Need to get this working.
The program asks user how many tickets they want, after they input they get that ticket amount and transaction amount (tickets are 5 dollars). so far so good. Program works as is supposed to.
Program then asks user if they want to continue, if they say yes, program will start over. If they say no, program will then sum all transactions and output results of number of tickets purchased and dollar amount.
That's where I get stuck. How do I get the program to loop and output the sum of all amounts?
I know I should be adding them to some kind of list that will sum. But how do I do this? :(
tickets = input("How many tickets would you like? ")
tickets = int(tickets)
totalTicket = (tickets * 5)
print(f"You ordered {tickets} tickets and your total is {totalTicket} Dollars")
continuePurchase = input("Would you like to continue? Y/N \n")
while True:
if continuePurchase == "Y":
tickets = input("How many tickets would you like? ")
tickets = int(tickets)
totalTicket = (tickets * 5)
print(
f"You ordered {tickets} tickets and your total is {totalTicket} Dollars")
continue
elif continuePurchase == "N":
Since you always set the total tickets from the most recent user input, you are not going to be able to get the total tickets from more than one user inputs. You need to add items to a list. It can be any size and you can add new elements to it (in our case, new tickets being purchased)
It is also wise to avoid loops that use {while true}. Since we always want to loop when the user input is Y, then that can be the condition of the loop. Loop until the user input is not Y (I would add a function to make sure the user is entering Y or N. If they do not, ask the question again)
continuePurchase = "Y"
purchaseList = []
'TODO I would check if there is a valid input. Is it y/n? Should the upper/lower case matter'
while continuePurchase == "Y":
tickets = input("How many tickets would you like?")
purchaseList.append(int(tickets))
totalTicket = (tickets * 5)
print(f"You ordered {tickets} tickets and your total is {totalTicket} Dollars")
continuePurchase = input("Would you like to continue? Y/N \n")
'Answer was N, so now we can add up all the tickets'
print("You have purchased ", sum(purchaseList), " tickets total")
Here, this is a slightly modified code of yours. This works:
tickets = input("How many tickets would you like? ")
tickets = int(tickets)
totalTicket = (tickets * 5)
while True:
continuePurchase = input("Would you like to continue? Y/N \n").lower()
if continuePurchase == "y":
tickets = input("How many tickets would you like? ")
tickets = int(tickets)
totalTicket = (tickets * 5)
continue
else:
break
print(f"You ordered {tickets} tickets and your total is {totalTicket} Dollars")
I am trying to make a sort of quiz game to memorise cocktail specs.
I created a dictionary called "cocktails" and inside of it there are keys as cocktail names (Negroni, Aperol Spritz) and as value there is another dictionary for each cocktail with "spirits" and "dose" keys with lists of values. I coded this and it works but I was wondering if there was a better way to do it since I want to add lots more cocktails.
I am looking for a loop that "loops" through every value inside of the list when the answer is correct instead of me having to type in manually the value everytime with the if/ else statements.
Basically I want to loop through those two automatically if the answer is correct:
cocktails["negroni"]["spirits"][0] and
cocktails["negroni"]["ml"][0]
so the [0] should become 1 and then [2] in both of the lines every time the loop continues.
I hope I explained it clearly. Ps: I'm very new to programming :)
This is the code I'm working with:
code
cocktails = {
"negroni": {
"spirits": ["gin", "vermouth", "campari"],
"ml": [25, 25, 25],
},
"aperol_spritz": {
"spirits": ["aperol", "prosecco", "soda"],
"ml": [50, 50, "top"]
}
}
cocktail = "Negroni"
print(cocktail)
stop_quiz = True
while stop_quiz:
guess = int(input(cocktails["negroni"]["spirits"][0] + ": "))
if guess != cocktails["negroni"]["ml"][0]:
continue
else:
guess = int(input(cocktails["negroni"]["spirits"][1] + ": "))
if guess != cocktails["negroni"]["ml"][1]:
continue
else:
guess = int(input(cocktails["negroni"]["spirits"][2] + ": "))
if guess != cocktails["negroni"]["ml"][2]:
continue
else:
print("You know how to make a " + cocktail + "!")
answer = input("Do you want to play again? ")
if answer == "yes":
continue
elif answer == "no":
print("See you soon!")
stop_quiz = False
There are multiple options to get what you want, I would advice to take a look at classes to get a more object oriented approach. With that said, let's do it without classes!
Note: I also made some suggestions to your code to make it slightly simpler and adhere to the variable naming.
cocktails = {
"negroni": {
"spirits": ["gin", "vermouth", "campari"],
"ml": [25, 25, 25],
},
"aperol_spritz": {
"spirits": ["aperol", "prosecco", "soda"],
"ml": [50, 50, "top"]
}
}
Game:
cocktail = 'negroni'
print(cocktail)
stop_quiz = True
while stop_quiz:
for spirit, amount in zip(cocktails[cocktail]['spirits'], cocktails[cocktail]['ml']):
guess = int(input(f"{spirit}: "))
while guess != amount:
print("You are wrong :( , try again!")
guess = int(input(f"{spirit}: "))
print("You know how to make a " + cocktail + "!")
answer = input("Do you want to play again? ")
if answer == "yes":
continue
elif answer == "no":
print("See you soon!")
stop_quiz = False
Explanation
We make use of the following 2 things:
Pythons built in zip
A kind of do while loop.
The zip iterator creates a loop that contains your spirit and answer:
for spirit, amount in zip(cocktails[cocktail]['spirits'], cocktails[cocktail]['ml']):
Now you can iterate over all the different spirits, and you already have the right answers to compare with.
In Python there is no such thing as a do while loop by default. But we can simulate the behavior of asking something until we get what we want. We first ask for an input amount, and if this is not what we want we ask again (and again ...).
guess = int(input(f"{spirit}: "))
while guess != amount:
print("You are wrong :( , try again!")
guess = int(input(f"{spirit}: "))
When the player successfully guesses all the spirits amounts you will get the end message and prompted to play again.
Improvements
Now there are a few things that could be changed to improve the code:
the value stop_quiz is True, but it makes more sense to make it False, and check the opposite condition in the while loop. Or you can change the name to for example running.
At the end you prompt a yes and no question, but you continue the yes question if this is True. So why check for it at all? Also there is no else statement, so you really only have to check for the no value.
cocktail = 'negroni' # same as list(cocktails)[0]
print(cocktail)
running = True
while running:
for spirit, amount in zip(cocktails[cocktail]['spirits'], cocktails[cocktail]['ml']):
guess = int(input(f"{spirit}: "))
while guess != amount:
print("You are wrong :( , try again!")
guess = int(input(f"{spirit}: "))
print("You know how to make a " + cocktail + "!")
answer = input("Do you want to play again? ")
if answer == 'no':
print("See you soon!")
running = False
I'm just starting to learn Python and I'm writing a simple dice rolling program that asks the user for the number of dice and how many sides the dice will have.
So far I have this:
numberOfDice = eval(input("How many dice/die would you like to use? "))
numberOfSides = eval(input("How many sides will each die have? "))
for i in range(1,numberOfDice + 1) :
roll = random.randint(1,numberOfSides)
print(roll)
while True :
replay = input("Would you like to play again? ")
if replay.lower() == "yes" :
numberOfDice = eval(input("How many dice/die would you like to use? "))
numberOfSides = eval(input("How many sides will each die have? "))
for i in range(1,numberOfDice + 1) :
roll = random.randint(1,numberOfSides)
print(roll)
else :
break
It works, but it doesn't seem very efficient to me. I'm wondering if there might be a way to ask the user at the end of the first for loop if they want to play again, and, if they say yes, ask them for new values and repeat the for loop again. Is there any way to do something like this?
The general application is a "stay while valid" loop, such as:
replay = True
while replay:
... remainder of code
replay = raw_input("Roll again? (y or n)") == 'y'
Note that this is a simple version, with no error checking: if the user enters a 'y', the program continues; anything else terminates the wonderful world of rolling a douse (never say 'die' :-) ).