How to find the total cost for this python program - python

I have created a simple python program that lets users drive different cars. The user will enter their full name, address, and phone number. The user will then be asked which car they wish to drive, with a maximum of five selected cars. The cars have set prices and a total bill will be added up at the end of the program, however, I am currently unable to find a solution to work out the total cost for the user. The program also asks the user how many laps of the race they wish to perform in the car, I have already worked out how to display the total cost of the laps, but need it added to the total cost somehow. Thanks!
Code
cars_list = ["Lamborghini", "Ferrari", "Porsche", "Audi", "BMW"]
cars_prices = {"Lamborghini":50, "Ferrari":45, "Porsche":45, "Audi":30, "BMW":30}
laps_cost = 30
final_cost = []
final_order = {}
cust_num_cars = int(input("Please enter the number of cars you want to drive in this session: "))
while cust_num_cars > 5:
cust_num_cars = int(input("You can only drive a maximum of five cars! Please try again.\n Enter cars: "))
for index in range(cust_num_cars):
print("\nChoose a car type from the following list", cars_list)
select_cars = input("Select a car type: ")
if select_cars in cars_list:
print("\nYou have selected to drive the", {select_cars})
final_cost.append(cars_prices[select_cars])
if select_cars not in cars_list:
print("\n",{select_cars}, "is not in the available list of cars to drive!")
cust_name = input("\nPlease enter your full name: ")
cust_address = input("Please enter your full address: ")
cust_phone_num = int(input("Please enter your mobile phone number: "))
add_laps = input("\nWould you like to drive additional laps? (Yes/No): ")
if add_laps == "Yes":
print("\nYou have selected an additional lap!")
num_of_laps = int(input("Number of additional laps: "))
print("\nYou have selected", num_of_laps, "additional laps!")
final_cost.append(cars_prices[add_laps])
sum = num_of_laps * laps_cost
else:
print("\nYou have selected no additional extra laps.")
print("Total laps cost: £",final_cost)
print("\n----Order & Billing summary----")
print("Customer Full Name:", cust_name)
print("Customer Address:", cust_address)
print("Customer Phone Number", cust_phone_num)
print("Total cost", final_cost.append(cars_prices))
I have tried everything I know in my little experience with Python to work out a final cost. I have worked out the total cost for the number of laps, but can't work out how to add that to the cost of the selected cars and then display a total cost.

First, you can't use a for-loop because when you select a car that isn't in the possibilities you have lost an iteration, use a while loop
# final_cost renamed to car_cost
while len(car_cost) != cust_num_cars:
print("\nChoose a car type from the following list", cars_list)
select_cars = input("Select a car type: ")
if select_cars in cars_list:
print("\nYou have selected to drive the", select_cars)
car_cost.append(cars_prices[select_cars])
else:
print("\n", select_cars, "is not in the available list of cars to drive!")
Then use sum() for the cars cost and add to the laps cost
num_of_laps = 0
add_laps = input("\nWould you like to drive additional laps? (Yes/No): ")
if add_laps == "Yes":
print("\nYou have selected an additional lap!")
num_of_laps = int(input("Number of additional laps: "))
print("\nYou have selected", num_of_laps, "additional laps!")
else:
print("\nYou have selected no additional extra laps.")
total = num_of_laps * laps_cost + sum(car_cost)
print("Total price:", total)

To calculate the total cost, you can use the built-in sum() function, which takes an iterable (like a list) and returns the sum of all its elements. In your case, you can use it to add up all the prices of the cars that the user selected:
total_cost = sum(final_cost)
Then you can add the cost of the laps to the total cost. In your code, the variable sum holds the total cost of the laps. You can add that to the total_cost variable:
total_cost += sum

Hi friend in this program its better to add all of your costs in one variable.
in a list your list's elements are not adding together,
but with variables you can add your cost every time you get a cost like this:
cost_sum = 0
cost = input("Enter a cost: ")
cost_sum += cost

Related

How to automatically assign a new number as a key in the dictionary whenever the user wants to add an item?

For example, I have an empty dictionary called a shopping list. and it shall store keys such as #"1,2,3,4..." and the value should be a list that store the name and price of item. For some #reason I can only have 1 key in the shopping list only...
The code is below:
#Convenience store inventory of products with code number, item name, price and stock
items = { 0:['black tea',500,20], 1:['red tea',500,1], 2:['milk
tea',500,0]}
shopping_list = {}
query = input("Enter the code number of the item you want to get: ")
query = int(query)
for i in items:
if query == i:
item = i
print(items[item][0], "will cost you", "{:.2f}".format(items[item][1]/100),"dollars")
#Temporary shopping list shall store item code, name and price from original list of product
n=0
buy_more = input("Do you wish to choose some more items? (Y or N) ")
while buy_more.isdigit() and buy_more not in "Yy" and buy_more not in "Nn":
print("Please enter (Y or N) only. ")
buy_more = input("Do you wish to choose some more items? (Y or N) ")
#loopback and let users to buy an additional item
while buy_more in "Yy":
shopping_list[n] = [items[item][0],items[item][1]]
print("Nice! Please choose one more item.")
buy_more = input("Do you wish to choose some more items? (Y or N) ")
#Continue to the transaction process
if buy_more in "Nn":
print("Continue to transaction process. ")
break
shopping_list[n] = [items[item][0],items[item][1]]
print(shopping_list). `
I optimised your code a bit, maybe it will help, here in the code since you asking for the item code as input I'm not incrementing it:
items = { 0:['black tea',500,20], 1:['red tea',500,1], 2:['milk tea',500,0]}
shopping_list = {}
#Temporary shopping list shall store item code, name and price from original list of product
buy_more='y'
while buy_more:
if buy_more not in 'YyNn':
print("Please enter (Y or N) only. ")
buy_more = input("Do you wish to choose some more items? (Y or N) ")
#loopback and let users to buy an additional item
while buy_more in "Yy":
query = int(input("Enter the code number of the item you want to get: "))
print(items[query][0], "will cost you", "{:.2f}".format(items[query][1]/100),"dollars")
shopping_list[query] = [items[query][0],items[query][1]]
print("Nice! Please choose one more item.")
buy_more = input("Do you wish to choose some more items? (Y or N) ")
#Continue to the transaction process
if buy_more in "Nn":
print("Continue to transaction process. ")
break
print(shopping_list)

Code is giving an "Output is too large" when printing

here is the code=
def main():
print("Enter your age: ")
age= float(input())
while age >= 0:
if (age<= 2.00) :
print("The guest whose age is",age,"is admitted without charge.")
elif ((age>= 3.00) and (age<= 12.00)):
print("A(n)",age," year old will cost $14.00 dollars for admission.")
elif (age>=65.00) :
print("A(n)",age,"year old will cost $18.00 dollars for admission.")
else :
print("A(n)",age,"year old will cost $23.00 dollars for admission.")
print("End of guest list")
main()
and here is the problem I am trying to solve:
Create a program that begins by reading the ages of all of the guests in a group from the user, with one age entered on each line. The user will enter -1 to indicate that there are no more guests in the group. Then your program should display the admission cost for the group with an appropriate message. The cost should be displayed using two decimal places. Use the following sample run for input and output messages.
You need to move the prompt for input into the loop, otherwise age never changes within the while, creating an infinite loop.
def main():
age = 1
while age >= 0:
print("Enter your age: ")
age = float(input())
if (age<= 2.00) :
print("The guest whose age is",age,"is admitted without charge.")
elif ((age>= 3.00) and (age<= 12.00)):
print("A(n)",age," year old will cost $14.00 dollars for admission.")
elif (age>=65.00) :
print("A(n)",age,"year old will cost $18.00 dollars for admission.")
else :
print("A(n)",age,"year old will cost $23.00 dollars for admission.")
print("End of guest list")
main()
You never update age after its initial value and so the while loop continues forever, printing a line for each iteration.
You need to put a
age = float(input())
as the last line of the while loop.

Balance in data list is not reduced when it should

I want to make electricity payments by reducing the balance in the data list with bills in the electricity list.
data = [{"norek":"932012042", "name":"Ahmad Sujagad", "balance":5000000},
{"norek":"932012052", "name":"Basuki Pepeh", "balance":4000000},
{"norek":"932012099", "name":"Bambang Gentolet", "balance":3500000}]
data_ele =[{"noseri":"7932392", "name":"Ahmad Sujagad", "bill":320000},
{"noseri":"7932384", "name":"Basuki Pepeh", "bill":250000},
{"noseri":"7932345", "name":"Bambang Gentolet", "bill":180000}]
When I do transactions, the balance is reduced, but when I choose option 1, why is it not reduced?
print("1.Electric\n2.Water")
option = int(input("Please Select Menu :"))
if option == 1:
print("total bill : ",dlist['bill'])
bayar = input("Are You Sure You're Paying? (Y/T)")
if bayar == "Y" or bayar == "y":
print("No Seri : ",dlist['noseri'],"\n","name :",dlist['name'])
print("your remaining balance :",duser['balance']-dlist['bill'])
elif bayar == "T" or bayar == "t":
print("Payment Cancelled")
Console:
Please Select Menu :1
total bill : 320000
Are You Sure You're Paying? (Y/T)y
No Seri : 7932392
name : Ahmad Sujagad
your remaining balance : 4680000
when I check back in the option one, the balance is not reduced:
if option == 1:
print("your remaining balance :",duser['balance'])
Console:
Please Select Menu :1
your remaining balance : 5000000
In the following line:
print("your remaining balance :",duser['balance']-dlist['bill'])
...you are only showing the result, but you are not updating the balance. Replace this line with:
duser['balance'] -= dlist['bill'] # update!
print("your remaining balance :", duser['balance']) # show new balance

Script for an ATM in Python

I am doing a project for class and can't figure out where I am going wrong. The code works in sections, but when I run it all together it shuts down right after the first input.
I think I need to call functions somewhere - but how and where?
Below is all my code so far, with comments.
import sys
#account balance
account_balance = float(500.25)
##prints current account balance
def printbalance():
print('Your current balance: %2g'% account_balance)
#for deposits
def deposit():
#user inputs amount to deposit
deposit_amount = float(input())
#sum of current balance plus deposit
balance = account_balance + deposit_amount
# prints customer deposit amount and balance afterwards
print('Deposit was $%.2f, current balance is $%2g' %(deposit_amount,
balance))
#for withdrawals
def withdraw():
#user inputs amount to withdraw
withdraw_amount = float(input())
#message to display if user attempts to withdraw more than they have
if(withdraw_amount > account_balance):
print('$%.2f is greater than your account balance of $%.2f\n' %
(withdraw_amount, account_balance))
else:
#current balance minus withdrawal amount
balance = account_balance - withdraw_amount
# prints customer withdrawal amount and balance afterwards
print('Withdrawal amount was $%.2f, current balance is $%.2f' %
(withdraw_amount, balance))
#system prompt asking the user what they would like to do
userchoice = input ('What would you like to do? D for Deposit, W for
Withdraw, B for Balance\n')
if (userchoice == 'D'): #deposit
print('How much would you like to deposit today?')
deposit()
elif userchoice == 'W': #withdraw
print ('How much would you like to withdraw today?')
elif userchoice == 'B': #balance
printbalance()
else:
print('Thank you for banking with us.')
sys.exit()
This part should be as one userchoice = input ('What would you like to do? D for Deposit, W for Withdraw, B for Balance\n')
Not sure if you indented by accident, but python does not like that.
Also, advice for your code. Make it so user can either do uppercase or lowercase letters for input, also make sure it still grab input even if user put empty spaces after input string.
Your withdraw exit the program after entering the string character W.
Balance is not grabbing the correct Deposit.
Use for loops and condition to keep it looping and ask user when to exit.

Python fails to create file when the file being written isn't already there

For the better part of 3 months I've been slowly adding stuff in an attempt to make the system output a file to save that is human readable. I could save this all under one file but this was originally course work and has now just become so random piece of Franken-Code. So I have the program take the users family name and date of arrival and use that as the file name. So naturally the program will be writing to a file that doesn't yet exist and if it does it should add another entry as to insure bookings aren't. All I have found is people saying one of 2 things, either that it "w" or "a" should create the file or that a "+" is needed after the selection of opening type like so "a+" or "w+". I think the earlier is more likely as I think "w+" is read/write but not to sure and many different sources say different things.
#Comment Format
#
#Code
#
#Comment about above Code
from random import*
c_single = 47
c_double = 90
c_family = 250
discount = 10
VAT = 20
max_stay = 14
min_stay = 1
room_list = []
min_rooms = 1
max_rooms = 4
cost = 0
#Sets all need variables that would need to be changed if the physical business changes (e.g. Increase in number of rooms, Longer Max stay allowed, Change to Pricing)
print("Cost of room:")
print("Single - £", c_single)
print("Double - £", c_double)
print("Family - £", c_family)
#Prints prices based on above variables
name = input("What is the family name --> ")
arrival = input("Please enter date of arrival in the form dd/mm/yy --> ")
while len(arrival) != 8:
arrival = input("Please re-enter, in the case of the month or day not being 2 digits long insert a 0 before to insure the form dd/mm/yy is followed --> ")
#Gets the guests name and date of arrival for latter update into the business' preferred method of storage for bookings
nights = int(input("How many nights do you intend to stay in weeks --> "))
while nights > max_stay or nights < min_stay:
nights = int(input("That is too short or long, please re-enter stay in weeks -->"))
if nights >= 3:
discount_applic = 1
#Gets the guests ideal number of weeks stay, ensure that this would be possible then adds the discount if applicable
rooms = int(input("Please enter number of rooms required --> "))
while rooms < min_rooms or rooms > max_rooms:
rooms = int(input("That number of rooms is unachievable in one purchase, please re-enter the number of rooms you require --> "))
#Gets number of rooms desired and checks that it does not exceed the maximum allowed by the business or the minimum (currently 1, staying no nights doesn't work)
for room in range (rooms):
current_room = input("Please enter the room desired--> ")
current_room = current_room.upper()
if current_room == "SINGLE":
cost += c_single
elif current_room == "DOUBLE":
cost += c_double
elif current_room == "FAMILY":
cost += c_family
#Checks which room is desired
else:
while current_room != "SINGLE" and current_room != "DOUBLE" and current_room != "FAMILY":
current_room = input("Invalid room type, vaild entries are : single, double or family --> ")
current_room = current_room.upper()
#Ensures that the desired room is valid, if first inserted not correctly, repeats until valid entry is entered
room_list.append (current_room)
#Adds the wanted room type to the array room_list
cost = cost * nights
#calculates cost
booking = randrange(1000,9999)
print("Name: ", name)
print("You have booked from ", arrival)
print("You have booked stay for ", nights, "weeks")
print("You have booked", rooms, " room/s of these categories;")
print(str(room_list))
print("This will cost £", cost)
print("Booking referral: ", booking)
#Prints booking information
dateStr = str(arrival)
storageFileName = str(dateStr + name + ".txt")
storageFile = open(storageFileName, "w")
storageFile.write("Name: ", name)
storageFile.write("They have booked from ", arrival)
storageFile.write("They have booked stay for ", nights, "weeks")
storageFile.write("They have booked", rooms, " room/s of these categories;")
storageFile.write(str(room_list))
storageFile.write("This has cost them -- >£", cost)
storageFile.write("Booking referral: ", booking)
#saves the storage data to a server under the name and data.
The error:
Traceback (most recent call last):
File "H:\Computing\S4\Programs\Suite.py", line 89,
in storageFile = open(storageFileName, "w+")
FileNotFoundError: [Errno 2] No such file or directory: '15/10/17Daivdson.txt`'

Categories