I have created a small program that takes user input for 'flight specifications' and outputs details of that flight based on the input. However, it is just a bunch of if statements, I was wondering if there are any useful techniques to reduce the amount of if statements and make the program more efficient.
Code:
import time
def main():
AMS_DESTINATION = "Schiphol, Amsterdam"
GLA_DESTINATION = "Glasgow, Scotland"
AMS_PRICE = 150.00
GLA_PRICE = 80.00
# User input [LLL 0 00 L L]
flightSpecification = str(input("Enter Flight Specification: "))
flightDestination = flightSpecification[0:3]
bagCount = int(flightSpecification[4])
baggageCost = float((bagCount - 1) * 20)
passengerAge = int(flightSpecification[6:8])
standardMeal = 10.00
vegetarianMeal = 12.00
mealType = str(flightSpecification[9])
seatClass = str(flightSpecification[11])
totalFlightCost = 0
if flightDestination.lower() != 'ams' and flightDestination.lower() != 'gla':
print("Please enter a valid flight specification! [LLL 0 00 L L]")
time.sleep(2)
main()
if flightDestination.lower() == 'ams':
print(f"Destination: {AMS_DESTINATION}")
print(f"Flight cost: £{AMS_PRICE}")
totalFlightCost = 150
elif flightDestination.lower() == 'gla':
print(f"Destination: {GLA_DESTINATION}")
print(f"Flight cost: £{GLA_PRICE}")
totalFlightCost = 80
print(f"Number of bags: {bagCount}")
print(f"Baggage Cost: £{baggageCost}")
if passengerAge > 15:
print("Child: False")
elif passengerAge <= 15:
print("Child: True")
totalFlightCost = totalFlightCost / 2
standardMeal = standardMeal - 2.50
vegetarianMeal = vegetarianMeal - 2.50
elif passengerAge < 0:
print("Age cannot be negative")
main()
if mealType == 'S' and seatClass != 'F':
totalFlightCost = totalFlightCost + standardMeal
print("Meal: Standard")
print(f"Meal Cost: £{standardMeal}")
elif mealType == 'V' and seatClass != 'F':
totalFlightCost = totalFlightCost + vegetarianMeal
print("Meal: Vegetarian")
print(f"Meal Cost: £{vegetarianMeal}")
elif mealType == 'N':
print("Meal: None")
print("Meal Cost: £0")
# THIS COULD DEFINITELY BE DONE MORE EFFICIENTLY
if seatClass == 'F':
if mealType == 'S':
totalFlightCost = totalFlightCost + standardMeal
print("Meal: Standard")
print(f"Meal Cost: FREE")
elif mealType == 'V':
totalFlightCost = totalFlightCost + vegetarianMeal
print("Meal: Vegetarian")
print(f"Meal Cost: £{vegetarianMeal}")
print("Seating Class: First")
totalFlightCost = totalFlightCost * 6
elif seatClass == 'E':
print("Seating Class: Economy")
print(totalFlightCost)
main()
Thanks