airline reservation def help python - python

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.

Related

How to check multiple parameters without a mess of 'if' statements?

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.

Trying to sum up total cost from user input in defintion

I am trying to build a menu for user . User must order min 3 items and after that needs to decide if want to keep ordering after or end it. I created while loop for that and now it's my question
How can I sum up all prices for each choice?
I include user answer in definition otherwise my loop is not working as I wish... I need to sum up each choice of different prices that need to match positions from list I've created.
I tried if statement inside def, outside. Like if input answer will be = 1, then price will be 1,20 etc and tried to sum it up, would not work.
Many thanks for any help !
prices = [1.20,1.30,2.00,1.60,2.00,2.50,4.00,4.80,3.80,3.25,3.40,2.70,2.50,3.15,4.40]
food_menu = ["sandwich","pizza","lemon cake","chips","salad","panini","yoghurt","pasta","bagel,"cheese wrap","cherry muffin","egg","blt","marmite sarnine","watermelon pieces"]
def order1():
input("Please choose which treat you wish to order by typing its position number [1-15] and confirm with ENTER : ")
input("Next item to order: ")
def order2():
input("Another item number to order: ")
if decision == "y":
print ("Awesome! Let's get started!")
order1()
i=1
x=""
while i>0:
if decision == "y":
order2()
x = input("Keep adding more food for bigger discount?\ny - for yes\ns - for stop:\nYour answer: ")
if (x == "s"):
break
elif decision == "n":
print ("Please come back tomorrow or try again. Today you need to get minimum 3 items today!\U0001F641")
print ("Bye bye!")
i=0
exit()
else:
print ("Wrong answer, please try again from the start.. \U0001F641 ")
i=0
exit()
After that I should sum up all the prices for each item that customer wants to order.
I'd suggest you have one main loop, then 2 parts in it
handle choice of user for the product
handle choice for continuing or not
Also a dict is the best structure to store both menu and prices, and it provides easy acess and very test inclusion
food_menu = {'sandwich': 1.2, 'pizza': 1.3, 'lemon cake': 2.0, 'chips': 1.6, 'salad': 2.0, 'panini': 2.5,
'yoghurt': 4.0, 'pasta': 4.8, 'bagel': 3.8, 'cheese wrap': 3.25, 'cherry muffin': 3.4, 'egg': 2.7,
'blt': 2.5, 'marmite sarnine': 3.15, 'watermelon pieces': 4.4}
decision = ""
count = 0
total = 0
print("Menu with prices:")
print(*food_menu.items(), sep="\n")
while True:
item = input("Please choose which treat you wish to order by typing its position number [1-15] "
"and confirm with ENTER : ")
if item in food_menu:
total += food_menu[item]
count += 1
else:
print("Wrong input")
decision = input("Keep adding more food for bigger discount? (y - for yes / s - for stop) : ")
if decision == "s":
if count < 3:
print("Please come back tomorrow or try again. Today you need to get minimum 3 items today!")
else:
print("Total price is:", total)
break

An if else statement is not working python [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 1 year ago.
I am making a text adventure game, but it keeps running the 1st variation in the code, even though I specified both scenarios:
print("By Rishi Suresh 2021")
print('')
print('')
print("A S h o r t R i d e")
print('')
print('')
print(" P L A Y ( P )")
print('')
print('')
if input()=="p":
print('')
print('')
print("Your journey begins on a bleak day. It's cloudy, and the windows of your apartment amplify the pitter patter of the soft rain outside. Your clothes are strewn about. You hear the landline ringing. You also see a diary.")
print('')
print('')
if input("What do you do? Do you pick up the diary (A) or answer the landline (B)? ")=="b"or "B":
print("")
print("")
print("You pick up the landline, and hear a voice on the other end. It is scratchy, and tells you to come to the London Underground. You pick up your clothes, a empty whiskey bottle and some glasses, and dress. You head outside. ")
elif input() == "A" or "a":
print("The diary reads:")
print('')
print('')
print("Dear Diary,")
print("Tommorow's the day. We have all the trucks ready, all the Tommy's, all the big men. This stop and shop will be the sucess of the century.")
print("The landline rings again. You pick up the landline, and hear a voice on the other end. It is scratchy, and tells you to come to the London Underground. You pick up your clothes, a empty whiskey bottle and some glasses, and dress. You head outside.")
This clause:
if input("What do you do? Do you pick up the diary (A) or answer the landline (B)? ")=="b"or "B":
will always pass, because "B" (and "A" or any non-empty string, for that matter) is a truthy value:
if "B":
print("Hey!")
if "A":
print("I pass, too!")
if "A really, really, really long string that goes on...":
print("So do I!")
if "":
print("I'll never print.")
This means if <anything> or "B": will always pass (provided evaluation of <anything> doesn't throw an exception or change control flow), because the second part of the or is satisfied. The == operator is binding to input (i.e. input(...) == "b" or "B" is (input(...) == "b") or "B"); you can't express "the result is a member of some set" in this way (i.e. x == 1 or 2 is (x == 1) or 2, not x in (1, 2)).
Assign the result of your input calls to some variable result, and then test result in ("b", "B") or result.lower() == "b" (ditto for the second case).
by asking for another input in the elif you are asking for another user input discarding the user's previous input,plus or "a" would cause the statment to always be true since you are not checking if the input is equal to "a", this would be better:
print("")
print('')
print('')
print("")
print('')
print('')
print(" ")
print('')
print('')
if input()=="p":
print('')
print('')
print("")
print('')
print('')
option=input(" a or b")
if option =="b"or option =="B":
print("")
print("")
print("")
elif option == "A" or option == "a":
print("The diary reads:")
print('')
print('')
print("Dear Diary,")
print("")
print("")

If else loop in python doesn't function properly

so i'm writing a program that's supposed to take 2 inputs of data as int's for a user's debt. the variables are debt1 and debt2. it's supposed to add these two values together and then depending on the user's input, it's supposed to give out a specific response using the "if/else" loop i've created. the problem is that the program only prints out the response from the first "if" statement no matter what the input is, it always prints out "your debt is dangerously high". how do i correct this?
** Here is my code **
Name = input("Please enter your name: ")
debt1 = int(input("Please enter your first debt amount: "))
debt2 = int(input("Please enter your second debt amount: "))
totalDebt = debt1+debt2
print("Your total debt is ", totalDebt)
if (totalDebt > 900,000):
print("Your debt is dangerously high ", Name)
elif((totalDebt >= 450,000 and totalDebt < 900,000)):
print("We can help you reduce your debt.")
else:
print("Congratulations, you know how to manage debt.")
Don't use commas in numbers:
if totalDebt > 900000:
print("Your debt is dangerously high ", Name)
elif (totalDebt >= 450000 and totalDebt < 900000):
print("We can help you reduce your debt.")
else:
print("Congratulations, you know how to manage debt.")
As #rdas said, you can use _ for long numbers, in place of ,

using exceptions and writing data to files in python 3

here what I need to do:
Your program must raise an exception if the user chooses any item not on the menu
presented. Along with raising an exception, write the code to handle this exception.
Ask the user for a value to convert.Your program must raise and exception, and handle the exception, if an input
errors occurs
Perform the conversion and write the original value, the original unit, the
converted value, and the converted unit to an output file named
conversions.txt.
Repeat steps a and b 10 times (in a loop).
heres my code:
#imports
import os
# global variables
mile_choice = 1
gallon_choice = 2
pound_choice = 3
inch_choice = 4
fah_choice = 5
quit_choice = 6
mainfile = open('conversions.txt', 'w')
# intro and global name variable
name = input ('what is your name? ')
print()
print('hello',name,', today we will be doing\
some standard to metric conversions.')
#define main function
def main():
choice = 0
while choice != quit_choice:
display_menu()
print()
choice = int(input('Please enter a number 1 - 6 : '))\
if choice == mile_choice:
print()
miletokm()
elif choice == gallon_choice:
print()
galtolit()
elif choice == pound_choice:
print()
poundstokg()
elif choice == inch_choice:
print()
inchtocm()
elif choice == fah_choice:
print()
fahtocel()
elif choice == quit_choice:
print()
print('Exiting the program.')
#define functions
def display_menu():
print()
print(' Menu ')
print()
print('Press 1 for Miles to Kilometers')
print()
print('Press 2 for Gallons to Liters')
print()
print('Press 3 for Pounds to Kilograms')
print()
print('Press 4 for Inches to Centimeters')
print()
print('Press 5 for Fahrenhiet to Celisus')
print()
print('To exit please enter 6 ')
def miletokm():
invalid_attempts = 0
#while loop for invalid input limited to 3
while invalid_attempts < 3 and invalid_attempts >= 0:
print()
mile = float(input('how many miles would you\
like to convert to kilometers? '))
mainfile.write(str(mile) + '\n')
# if statement to determine weather to proceed with conversation
# valid input = conversion
# invalid input = return with + 1 to invalid_attempt count
if mile >= 0 :
print()
mile_conv = mile * 1.6
print('that would be:', format(mile_conv, '.2f'), 'kilometers.')
print()
mainfile.write(str(mile_conv) + '\n')
return mile
else:
print()
print ('invalid input')
print()
invalid_attempts += 1
I left out the other conversion def. to help keep it shorter.
I am having problems with the exception part first and for most.
I have tried various things but I cant figure out how to write out the code correctly
I know how to define a value error for a number entered outside of the menu range
I don't understand how to write the units along with the data entered to the file.
The way I Have it now, it is not writing any information to mainfile.
I also feel like my code is very sloppy written. I have no idea because my professor refuses to help me.
I know that's alot to run through but i really have no where else to turn. I don't understand how I should structure the code and how to effectively accomplish what I need done.
what I have read covers the basis of this but I have no examples to look at other than very simple simple examples that deal with strictly one thing.
You could try something like... (from http://docs.python.org/2/tutorial/errors.html#exceptions)
>>> while True:
... try:
... x = int(raw_input("Please enter a number: "))
... break
... except ValueError:
... print "Oops! That was no valid number. Try again..."
...
You're on the right track. First thing that you need to do is to handle better the value for choice that the user gives you. Check what happens if they give you 9 or 'foo'.
Next, you should do the same for every value received in your functions that convert units. For that, you use try/except as #bitfish showed you (except that you use input instead of raw_input).
close the files you open (mainfile.close())
doing this elif choice == quit_choice: inside of this while choice != quit_choice makes no sense
use '\n' to skip lines (print('\n') is the same than print() two times
there are many ways to solve such a problem, white the experience you'll acquire you'll find more elegant ones, but this one is already ok.

Categories

Resources