Trying to sum up total cost from user input in defintion - python

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

Related

airline reservation def help 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.

Python how to limit the score (Code doesn't work after adding the if avg== etc

I am trying to find scores from only 7 judges and to have the numbers between 1-10 only, what is the problem with my code I am an newbie trying to self teach myself:)
So what I'm asking is how to limt the input to have to be 7 inputs per name and to limt the user input to 1-10 for numbers.
import statistics#Importing mean
def check_continue(): #defining check_continue (checking if the user wants to enter more name/athletes
response = input('Would you like to enter a another athletes? [y/n] ') #Asking the user if they want another name added to the list
if response == 'n': #if n, ends the loop
return False
elif response == 'y': # if y, continues the loop
return True
else:
print('Please select a correct answer [y/n]') #making sure the awsener is valid
return check_continue() #calling check continue
while(True):
name = input('Please enter a athletes name: ') #asking for an athletes name
if name == (""):
print ("try again")
continue
else:
try:
print("Enter the judges scores with space inbetween each score") #asking for scores
avg = [float(i) for i in input().split( )] #spliting the scores so the user only needs to put a space for each score
except ValueError:
continue
print("Please enter scores only in numbers")
scores = '' .join(avg)
print("please only enter number")
if scores ==("") or scores <=0 or scores >=10:
print("Please enter a score between 1-10")
continue
else:
print("_______________________________________________________________________________")
print("Athlete's name ",name) #Printing athletes name
print("Scores ", avg) #printing athletes scores
avg.remove(max(avg)) #removing the highest score
avg.remove(min(avg)) #removing the lowest score
avgg = statistics.mean(avg) #getting the avg for the final score
print("Final Result: " +
str(round(avgg, 2))) #printing and rounding the fianl socre
if not check_continue():
break
else:
continue
After reading input scores from judges, make sure that len(input.split()) == 7 to match first criteria.
Once you have the list of scores, just have a check that for each score, 1 <= int(score) <= 10.
If necessary, I can provide a working code too.
import statistics # Importing mean
def check_continue(): # defining check_continue (checking if the user wants to enter more name/athletes
# Asking the user if they want another name added to the list
response = input('Would you like to enter a another athletes? [y/n] ')
if response == 'n': # if n, ends the loop
return False
elif response == 'y': # if y, continues the loop
return True
else:
# making sure the awsener is valid
print('Please select a correct answer [y/n]')
return check_continue() # calling check continue
while(True):
# asking for an athletes name
name = input('Please enter a athletes name: ')
if name == (""):
print("try again")
continue
else:
scores = [float(i) for i in input('Enter the judges scores with space inbetween each score').split() if 1 <= float(i) <= 10]
if len(scores) != 7:
print("try again")
continue
print("_______________________________________________________________________________")
print("Athlete's name ", name) # Printing athletes name
print("Scores ", scores) # printing athletes scores
scores.remove(max(scores)) # removing the highest score
scores.remove(min(scores)) # removing the lowest score
# getting the avg for the final score
avg = statistics.mean(scores)
print("Final Result: " + str(round(avg, 2))) # printing and rounding the final score
if not check_continue():
break
This one should work. Let me know if there are any issues.
scores = [float(i) for i in input('Enter the judges scores with space inbetween each score').split() if 1 <= float(i) <= 10]
This line of code only saves values between 1 and 10, thus already checking for those values. Then the number of elements is checked to be 7.
PS: Would also want to point out that in your code, nothing ever executes after the except ValueError: continue. The continue basically skips to the next iteration without running any of the next lines of code.
My two cents. All checks of input you can warp before printing results with if all(): function for length of input scores list and range of nums between 1 and 10 (see code below).
For mean calc you don't need to delete value from list. You can make sorting and then slicing of list.
check_continue() can be simplify. Check entering for y or n value and return True or False by cases in dict. Otherwise loop.
import statistics
def check_continue():
response = input('Would you like to enter a another athletes? [y/n] ').lower() # Format Y and N to y and n
if response in ['y', 'n']: # Check if response is y or n
return {'y': True, 'n': False}[response]
check_continue()
while True:
name = input('Please enter a athletes name: ') #asking for an athletes name
if name: # Check if name not empty
while True: # make a loop with break at only 7 scores enter
scores_input = input("Enter the judges scores with space inbetween each score (only 7 scores)").split(' ')
try:
scores = [float(s) for s in scores_input] # sort list for extract part for avgg calc
except ValueError:
print("Please enter scores only in numbers")
continue
if all([len(scores) == 7, max(scores) <= 10.0, min(scores) >= 1]):
print("_______________________________________________________________________________")
print(f"Athlete's name {name}") #Printing athletes name
print(f"Scores {scores}") #printing athletes scores
avgg = statistics.mean(sorted(scores)[1:-1]) #getting the avg for the final score
print(f'Final result - {avgg :.2f}')
break
else:
print("Please enter 7 numbers for scores between 1-10")
if not check_continue():
break

Edhesive 7.5 code practice GPA average Python

Currently my code is:
def GPAcalc(grade, weighted):
grade = grade.lower()
dictionary = {"a": 4, "b": 3, "c": 2, "d": 1, "f": 0}
if weighted == 1 and grade in dictionary:
return "Your GPA score is: "+str(dictionary[grade] + 1)
elif weighted == 0 and grade in dictionary:
return "Your GPA score is: "+str(dictionary[grade])
else:
return "Invalid"
def GPAav():
grade = GPAcalc()
for i in range(0,cl):
grad= GPAcalc(grade,dictionary)
total = grade + total
print(total/cl)
cl = int(input("How many Classes are you taking? "))
for i in range(0,cl):
print(GPAcalc(input("Enter your letter Grade: "), int(input("Is it weighted?(1= yes, 0= no) "))))
GPAav()
I have to find the average GPA in decimal form from the rest of the code and output it. How would I go about getting the values from GPAcalc and using it in GPAav so i can average it out?
You have 2 options here. Store the grades in an list as they are entered or do the calculations on the fly. I chose the first option. This allows you to use the data later, if you want to add features the the app. You may also want to store the un-weighted grades in a list of tuples ([('a',True),('b',False)...]), but I just store the weighted grades.
Also, it is probably easier if you verify that the user is inputting the correct values as you read them. Have them keep re-trying until they get it right.
Your calculation functions should not print anything. They should just do the calculations they are required to do and return the result as a number.
grade_map = {"a": 4, "b": 3, "c": 2, "d": 1, "f": 0}
def GPAcalc(grade, weighted):
# Data has already been sanitized, so no error checks needed
return grade_map[grade] + weighted
def GPAav(grades):
return sum(grades) / len(grades)
def input_grades():
# TODO: Make sure user enters a number
cl = int(input("How many classes are you taking? "))
grades = []
for _ in range(cl):
# Loop until valid input
while True:
# Get input and convert to lower case
grade = input("Enter your letter grade: ").lower()
if grade in grade_map:
# Ok data. Exit loop.
break
# This only prints on bad input
print("Invalid input. Enter a,b,c,d or f. Try again...")
# Loop until valid input
while True:
# Read the value as a string first to verify "0" or "1"
weighted = input("Is it weighted?(1= yes, 0= no) ")
if weighted in "01":
# Verified. Now convert to int to avoid an exception
weighted = int(weighted)
break
print("Invalid input. Enter 0 or 1. Try again...")
# Store weighted numeric grade in list
grades.append(GPAcalc(grade, weighted))
return grades
grades = input_grades()
print(f"Your average GPA is {GPAav(grades)}.")
TODO: The repeated code in input_grades() is a red-flag that maybe that code can be moved into a re-usable function.

Anyone know how to receive different inputs inside a loop and add them together in a list

Basically, I am trying to make this menu for a project and I need to make it loop. What I am having difficulty on is trying to take input into a list in a loop. I want the program to add up the totals of every order that is taken and put them into a list. I then want the program to add up this list and give me the final total cost of the order. How would I make it so that I can use a list in a loop without it deleting what was previously inputted in there. For example, if I order a chicken sandwhich the first time in the loop and then order only that again the second time and then quit the loop, instead of showing me a price of 10.50 I only get a total price of 5.25. Thanks for the help!
choice = (input("How many people are you ordering for? To quit the program simply type quit."))
while choice != 'quit':
if Beverage == "yes" and Fries == "yes":
Total_Cost = CostSandwich + CostBeverage + CostFries - 1 + KetchupNumber
elif Beverage == "no" and Fries == "no":
Total_Cost = CostSandwich + CostBeverage + CostFries + KetchupNumber
elif Beverage == "yes" and Fries == "no":
Total_Cost = CostSandwich + CostBeverage + CostFries + KetchupNumber
elif Beverage == "no" and Fries == "yes":
Total_Cost = CostSandwich + CostBeverage + CostFries + KetchupNumber
print("Your total cost is", Total_Cost)
print("You ordered a", SandwichType, "Sandwich,", BeverageType, "Beverage,", FriesType, "Fries,", "and", KetchupType, "Ketchup Packets." )
finalcost = [0]
finalcost.append(Total_Cost)
totaloffinalcost = sum(finalcost)
choice = (input("If you would like to quit then type quit or type anything to continue"))
print("The final cost is", totaloffinalcost)
Apart from the fact that a lot can be done to improve and make this much efficient, the answer to your query:
OP: For example, if I order a chicken sandwhich the first time in the loop and then order only that again the second time and then quit the loop, instead of showing me a price of 10.50 I only get a total price of 5.25.
That happens because on each iteration inside the while loop just before taking the sum, you're initialing a list:
finalcost = [0]
Take this outside the while loop:
finalcost = [0]
while choice != 'quit':
# rest of the code

How to use while loops with multiple if/elif statements?

Trying to use a while statement to return to an opening prompt.
I apologize for my garbage code.
I've tried assigning a True/False value to the while loop but the program just terminates when any input is given.
choice = eval(input('What would you like to convert? \n Farenheit to Celcius (1) \n Feet to Meters (2) \n Pounds to Kilograms (3) \n Ounces to Liters (4) \n : '))
while choice:
if choice == 1:
degreesF = eval(input('Enter the temperature in degrees F: '))
degreesC = 5/9*(degreesF - 32)
print(degreesC, 'degrees Celcius')
elif choice == 2:
distanceFeet = eval(input('Enter the distance in feet: '))
distanceMeters = distanceFeet/3.28
print(distanceMeters, 'm')
elif choice == 3:
Pounds = eval(input('Pounds: '))
Kilograms = Pounds*0.45359237038
print(Kilograms, 'kg')
elif choice == 4:
Ounces = eval(input('Ounces: '))
Liters = Ounces*0.0295735
print(Liters, 'L')
Currently, the program returns me to whatever I set the input as. For example, if I input 1, I can convert temperature but I am only able to convert temperature.
Putting below line inside a while True may result in what you expected:
choice = eval(input('What would you like to convert? \n Farenheit to Celcius (1) \n Feet to Meters (2) \n Pounds to Kilograms (3) \n Ounces to Liters (4) \n : '))
If I am not wrong, you need something like below:
while True:
choice = eval(input('What would you like to convert? \n Farenheit to Celcius (1) \n Feet to Meters (2) \n Pounds to Kilograms (3) \n Ounces to Liters (4) \n : '))
if choice == 1:
degreesF = eval(input('Enter the temperature in degrees F: '))
degreesC = 5/9*(degreesF - 32)
print(degreesC, 'degrees Celcius')
elif choice == 2:
distanceFeet = eval(input('Enter the distance in feet: '))
distanceMeters = distanceFeet/3.28
print(distanceMeters, 'm')
elif choice == 3:
Pounds = eval(input('Pounds: '))
Kilograms = Pounds*0.45359237038
print(Kilograms, 'kg')
elif choice == 4:
Ounces = eval(input('Ounces: '))
Liters = Ounces*0.0295735
print(Liters, 'L')
You like to include the input in the while-loop:
while True:
choice = int(input('What would you like to convert? \n Farenheit to Celcius (1) \n Feet to Meters (2) \n Pounds to Kilograms (3) \n Ounces to Liters (4) \n : '))
if choice == 1:
degreesF = float(input('Enter the temperature in degrees F: '))
degreesC = 5/9*(degreesF - 32)
print(degreesC, 'degrees Celcius')
elif choice == 2:
distanceFeet = float(input('Enter the distance in feet: '))
distanceMeters = distanceFeet/3.28
print(distanceMeters, 'm')
elif choice == 3:
Pounds = float(input('Pounds: '))
Kilograms = Pounds*0.45359237038
print(Kilograms, 'kg')
elif choice == 4:
Ounces = float(input('Ounces: '))
Liters = Ounces*0.0295735
print(Liters, 'L')
else:
break
You have to put the eval line inside your while loop for it to run multiple times.
untested (pseudo) code:
while true:
your input line
your other code
this will run forever so I suggest doing somethig like this
while true:
your input line
if input == 0:
break
your other code
this will stop the while loop when you type 0
You need to do a couple of things, and for now you should make them explicit:
Your program should run forever, or until it is told to quit.
Your prompt for a menu selection should loop until it gets a valid answer.
Your inputs for numeric values should loop until they get valid answers.
General Form of the Solution
How can you do these things? In general, by starting with bad initial data, and looping until you see good data:
some_value = bad_data()
while some_value is bad:
some_value = input("Enter some value: ")
A good "default" value for bad_data() is the special value None. You can write:
some_value = None
On the other hand, your is bad test might want a different kind of bad data, such as a string. You might consider using '' as your bad data value:
some_value = ''
Finally, if your is bad test wants an integer value, maybe consider using a number you know is bad, or a number out of range (like a negative value):
some_value = 100
# or
some_value = -1
For your specific problems:
1. How do I run forever?
You can run forever using a while loop that never exits. A while loop will run as long as the condition is true. Is there a value that is always true in Python? Yes! Its name is True:
while True:
# runs forever
2. How do I loop until my menu selection is valid?
Using the general form, above, for an integer selection. Your menu asks the user to enter a number. You can check for a valid value either using str.isdigit() or using try:/except:. In python, the exception is the better choice:
choice = -1 # Known bad value
while choice not in {1, 2, 3, 4}: # {a,b,c} is a set
instr = input('Choose 1..4')
try:
choice = int(instr)
except:
choice = -1
3. How can I loop until I get a valid numeric value?
For floating point numbers, like temperatures, you don't want to try to spell out an explicit set of allowed answers, or a range of numbers. Instead, use None (you could use Nan, but it's more characters for the same result).
temp = None
while temp is None:
instr = input('Enter a temp: ')
try:
temp = float(instr)
except:
temp = None
Be aware that 'nan' is a valid float. So you might want to check for that and disallow it.
How do I combine all these things?
You put them together in blocks:
while True: # run forever
# Menu choice:
choice = -1 # Known bad value
while choice not in {1, 2, 3, 4}: # {a,b,c} is a set
instr = input('Choose 1..4')
try:
choice = int(instr)
except:
choice = -1
if choice == 1:
# Now read temps
temp = None
while temp is None:
instr = input('Enter a temp: ')
try:
temp = float(instr)
except:
temp = None

Categories

Resources