I have tried the following code to update the number of available cars based on the previous operations. So, for instance, if I have 3 available cars and the user rented one already, then the code should be updated to display 2 cars to the user. But whenever I ran my code, the number of available cars is always the same.
Here is my code:
if option_no==1:
print("Select one of the available cars: ")
print("--------------------------------------------------------------------------------------------------------------")
print("Model \t\tAvailable \tPrice/day \tLiability insurance/day \tComprehensive insurance/day")
print("--------------------------------------------------------------------------------------------------------------")
camery_price = 90
camery_availability = 3
camery_liability_insurance = 20
camery_comprhensive_insurance = 50
print("1. Camery \t\t\b\b\b\b",camery_availability, "\t\t\t\b\b\b\b\bQR90 \t\tQR20 \t\t\t\t\t\b\b\b\bQR50")
pajero_price = 150
pajero_liability_insurance = 30
pajero_comprhensive_insurance = 70
print("2. Pajero \t\t\b\b\b\b2 \t\t\t\b\b\b\b\bQR150 \t\tQR30 \t\t\t\t\t\b\b\b\bQR70")
altima = 70
altima_liability_insurance = 20
altima_comprhensive_insurance = 50
print("3. Altima \t\t\b\b\b\b2 \t\t\t\b\b\b\b\bQR70 \t\tQR20 \t\t\t\t\t\b\b\b\bQR50")
car_type = int(input("Enter car type: "))
No_of_days = int(input("Enter how many days: "))
insurance_type = input("Enter 'L' for Liability insurance and 'F' for full insurance: ")
if car_type==1:
if insurance_type=='L' or insurance_type=='l':
cost = No_of_days*camery_price
insurance_cost = No_of_days*camery_liability_insurance
tax = cost*0.05
total = cost+insurance_cost+tax
print("Cost: QR", format(cost, '.2f'))
print("Insurance: QR", format(insurance_cost, '.2f'))
print("Tax: QR", format(tax, '.2f'))
print("--------------------------------")
print("Total: ", format(total, '.2f'))
elif insurance_type=='F' or insurance_type=='f':
cost = No_of_days*camery_price
insurance_cost = No_of_days*camery_comprhensive_insurance
tax = cost*0.05
total = cost+insurance_cost+tax
print("Cost: QR", format(cost, '.2f'))
print("Insurance: QR", format(insurance_cost, '.2f'))
print("Tax: QR", format(tax, '.2f'))
print("--------------------------------")
print("Total: ", format(total, '.2f'))
else:
print("Error. Please enter the correct character")
operation = input("More operation? [Y/N] ")
if operation=='N' or operation=='n':
break
camery_availability = camery_availability - 1
Related
I am trying to create a program that inputs the price and tax rate and returns the item number, price, tax rate, and item price in an orderly format.
Here is the criteria:
The user can enter multiple items until the user says otherwise.
It calculates and display the total amount of purchased items on the bottom.
The price gets a 3% discount if the total amount is 1000 or more
I am not allowed to use arrays to solve this problem and I must separate the inputs from the outputs on the screen.
An example output is shown here:
Enter the price: 245.78
Enter the tax rate: 12
Are there any more items? (y/n) y
Enter the price: 34
Enter the tax rate: 10
Are there any more items? (y/n) y
Enter the price: 105.45
Enter the tax rate: 7
Are there any more items? (y/n) n
Item Price Tax Rate % Item Price
====================================
1 245.78 12% 275.27
2 34.00 10% 37.40
3 105.45 7% 112.83
Total amount: $425.51
Here is my code so far:
price= float(input('Enter the price: '))
taxRate= float(input('Enter the tax rate: '))
itemPrice = price * (1 + taxRate/100)
acc= 0
while True:
query=input('Are there any more items? (y/n)')
if query== 'y':
price= float(input('Enter the price: '))
taxRate= float(input('Enter the tax rate: '))
itemPrice = price * (1 + taxRate/100)
print(itemPrice )
acc+=1
elif query=='n':
break
print ("Item Price Tax Rate% Item Price")
print ("=========================================")
print( (acc+1) , format(price,'10.2f'), format(taxRate,'10.2f') ,
format(itemPrice,'14.2f') )
for num in range(0,acc):
print (acc, price, taxRate, itemPrice)
The output is shown as this:
Enter the price: 245.78
Enter the tax rate: 12
Are there any more items? (y/n)y
Enter the price: 34
Enter the tax rate: 10
37.400000000000006
Are there any more items? (y/n)y
Enter the price: 105.45
Enter the tax rate: 7
112.8315
Are there any more items? (y/n)n
Item Price Tax Rate% Item Price
=========================================
3 105.45 7.00 112.83
2 105.45 7.0 112.8315
2 105.45 7.0 112.8315
I just have a hard time trying to do this without using an array.. can anyone be of assistance?
You could build a string as a buffer for the output?
Like this:
out = ""
acc = 0
totalAmount = 0
query = 'y'
while query == 'y':
price = float(input('Enter the price: '))
taxRate = float(input('Enter the tax rate: '))
itemPrice = price * (1 + taxRate/100)
acc += 1
totalAmount += itemPrice
out += f"{acc:>4} {price:9.2f} {taxRate:11.2f}% {itemPrice:13.2f}\n"
query = input('Are there any more items? (y/n) ')
print("Item Price Tax Rate% Item Price")
print("=========================================")
print(out)
print(f"Total amount: ${totalAmount:.2f}")
if totalAmount >= 1000:
print(" Discount: 3%")
print(f"Total amount: ${totalAmount*0.97:.2f} (after discount)")
im learning python and for my homework i wanna make a food ordering program and get the receipt of the products purchased with the prices for the total. im struggling to get the billing process as i cannot get all the products chosen by the user displayed on the receipt
import datetime
x = datetime.datetime.now()
name = input("Enter your name: ")
address = input("Enter your address: ")
contact = input("Enter your phone number: ")
print("Hello " + name)
print("*"*31 + "Welcome, these are the items on on the menu."+"*" * 32 )
print("Menu:\n"
"1.Burger:150.\n"
"2.Fried Momo:120.\n"
"3.coffee:60.\n"
"4.Pizza:180.\n"
"5.Fried Rice:150.\n"
"6.French Fries:90.\n"
"7.Steamed Dumplings:150.\n"
"8.Chicken drumsticks:120.\n"
"9.Chicken Pakoras:120.\n"
"10.American Chop Suey:200.\n")
prices = {"1.Burger":150,
"2.Fried Momo":120,
"3.coffee":60,
"4.Pizza":180,
"5.Fried Rice":150,
"6.French Fries":90,
"7.Steamed dumplings":150,
"8.Chicken drumsticks":120,
"9.Chicken Pakoras":120,
"10.American Chop Suey":200
}
continue_order = 1
total_cost, total = 0, 0
cart = []
while continue_order != 0:
option = int(input("Which item would you like to purchase?: "))
cart.append(option)
if option >= 10:
print('we do not serve that here')
break
elif option == 1:
quantity = int(input("Enter the quantity: "))
total = quantity * 150
print("The price is: ₹" + str(total))
elif option == 2:
quantity = int(input("Enter the quantity: "))
total = quantity * 120
print("The price is: " + str(total))
elif option == 3:
quantity = int(input("Enter the quantity: "))
total = quantity * 60
print("The price is: " + str(total))
elif option == 4:
qquantity = int(input("Enter the quantity: "))
total = quantity * 180
print("The price is: " + str(total))
elif option == 5:
quantity = int(input("Enter the quantity: "))
total = quantity * 150
print("The price is: " + str(total))
elif option == 6:
quantity = int(input("Enter the quantity: "))
total = quantity * 90
print("The price is: " + str(total))
elif option == 7:
quantity = int(input("Enter the quantity: "))
total = quantity * 150
print("The price is: " + str(total))
elif option == 8:
quantity = int(input("Enter the quantity: "))
total = quantity * 120
print("The price is: " + str(total))
elif option == 9:
quantity = int(input("Enter the quantity: "))
total = quantity * 120
print("The price is: " + str(total))
elif option == 10:
quantity = int(input("Enter the quantity: "))
total = quantity * 200
print("The price is: " + str(total))
total_cost += total
continue_order = int(input("Would you like another item? enter Yes--> (1) or--> No (0):"))
print('='*30)
print('='*30)
print("Your receipt:\n")
print("Date: " + str(x))
print("Name: " + name.title())
print("Adress: " + address)
print("Contact number: " + contact)
for option in cart:
print ("Item: %s. Price: %s") % (option, prices[option])
print("Quantity: ",quantity)
print("Total Price: ", total_cost)
print('='*30)
print("Thank you for shopping here, have a great day ")
print('='*30)
but i get an error line 95, in
print ("Item: %s. Price: %s") % (option, prices[option])
KeyError: 1
any solution or better ways to improve the code would be really great
Try using F-Strings. They let you format text far more easily. Here's an example.
x = "hello!"
print(f"shr4pnel says {x}")
>>> shr4pnel says hello!
The problem in this case is that option == 1. 1 isn't a key in the dictionary so nothing is output. Hope this helps. This is because the dictionary does not have 1 as a key. To access the item the dictionary would have to be formatted like this.
prices = {1: "burger", 2: "hot dog"}
print(prices[1])
>>> burger
def main():
def input_stocks():
tot_pr = 0
while True:
stock_name = input("\nEnter Stock Name: ")
shares_bought = float(input("\nNumber of Shares bought: "))
stock_pp = float(input("Enter stock purchasing price: "))
stock_sp = float(input("Enter stock selling price: "))
commision = float(input("Enter broker Commision: "))
peaceout = input("Continue or exit? (case sensitive):")
if peaceout == 'quit':
return stock_name,shares_bought,stock_pp,stock_sp,commision
def calc():
amount_paid = shares_bought * stock_pp
paid_commision_bought = amount_paid * commision
stock_sold = shares_bought * stock_sp
paid_commision_sold = stock_sold * commision
pl = (stock_sold - paid_commision_sold) - (amount_paid + paid_commision_bought)
tot_pr = tot_pr + pl
def output():
print("\nStock Name:", stock_name)
print("Amount paid: $", format(amount_paid,',.2f'))
print("Paid commision bought: $", format(paid_commision_bought,',.2f'))
print("Stock sold $", format(stock_sold,',.2f'))
print("Paid commision sold: $", format(paid_commision_sold,',.2f'))
print("Profit or Loss: $", format(pl,',.2f'))
print("Total Profit thus far: $", format(tot_pr,',.2f'))
return stock_name,amount_paid,paid_commision_bought,paid_commision_sold,pl,tot_pr
output()
main()
>
NameError: name 'stock_name' is not defined (I'd assume others won't be defined as well...
What can I do to fix this error, and how can I prevent this in the future? I am quite new to this so I want to learn from my mistakes
stock_name and the other variables in output() will not be defined until the input_stocks() function is actually run. Just defining a function does not actually run it.
def load():
tot_pr = 0
peaceout = ''
while peaceout != 'exit':
stock_name = input("\nEnter Stock Name: ")
shares_bought = float(input("\nNumber of Shares bought: "))
stock_pp = float(input("Enter stock purchasing price: "))
stock_sp = float(input("Enter stock selling price: "))
commision = float(input("Enter broker Commision: "))
peaceout = input("Continue or exit? (case sensitive):")
return stock_name,shares_bought,stock_pp,stock_sp,commision,tot_pr
def calc(shares_bought,stock_pp,stock_sp,commision,tot_pr):
amount_paid = shares_bought * stock_pp
paid_commision_bought = amount_paid * commision
stock_sold = shares_bought * stock_sp
paid_commision_sold = stock_sold * commision
pl = (stock_sold - paid_commision_sold) - (amount_paid + paid_commision_bought)
tot_pr = tot_pr + pl
return amount_paid,paid_commision_bought,stock_sold,paid_commision_sold,pl,tot_pr
def output(stock_name,amount_paid,paid_commision_bought,stock_sold,paid_commision_sold,pl,tot_pr):
print("\nStock Name:", stock_name)
print("Amount paid: $", format(amount_paid,',.2f'))
print("Paid commision bought: $", format(paid_commision_bought,',.2f'))
print("Stock sold $", format(stock_sold,',.2f'))
print("Paid commision sold: $", format(paid_commision_sold,',.2f'))
print("Profit or Loss: $", format(pl,',.2f'))
print("Total Profit thus far: $", format(tot_pr,',.2f'))
return stock_name,amount_paid,paid_commision_bought,paid_commision_sold,pl,tot_pr
def main():
stock_name,shares_bought,stock_pp,stock_sp,commision,tot_pr = load()
amount_paid,paid_commision_bought,stock_sold,paid_commision_sold,pl,tot_pr = calc(shares_bought,stock_pp,stock_sp,commision,tot_pr)
output(stock_name,amount_paid,paid_commision_bought,stock_sold,paid_commision_sold,pl,tot_pr)
main()
I rewrote my program, and the only problem now is it won't loop if I type in continue?
#Joran Beasley
#MattDMo
#Program to calculate cost of gas on a trip
#Created by Sylvia McCoy, March 31, 2015
#Created in Python
#Declare Variables
Trip_Destination = 0
Number_Miles = 0
Current_MPG = 0.0
Gallon_Cost = 0.0
Total_Gallons = 0.0
Total_Cost = 0.0
#Loop to enter destinations
while True:
Trip_Destination = input("Enter where you would like to travel: ")
Number_Miles = float(input("Enter how many miles to your destination: "))
Gallon_Cost = float(input("Enter how much a gallon of gas costs: "))
Current_MPG = float(Number_Miles / Gallon_Cost)
print("Your trip to: " + Trip_Destination)
print("Your total miles: " + Number_Miles)
print("Your MPG: " + Current_MPG)
Error in line 20 and 21...stated earlier as float, how do I get them to print? Have to do the work in Python. Thanks!
You can't use the + operator to combine a string with a float.
It can only be used to combine two of a single type (eg.2 strings, 2 floats, etc.)
With that said, to get your desired output, you can simplify ALL the conversions you need into one line, like so:
Trip_Destination = 0
Number_Miles = 0
Current_MPG = 0.0
Gallon_Cost = 0.0
Total_Gallons = 0.0
Total_Cost = 0.0
#Loop to enter destinations
while True:
Trip_Destination = input("Enter where you would like to travel: ")
Number_Miles = input("Enter how many miles to your destination: ")
Gallon_Cost = input("Enter how much a gallon of gas costs: ")
Current_MPG = str(float(Number_Miles) / float(Gallon_Cost))
print("Your trip to: " + Trip_Destination)
print("Your total miles: " + Number_Miles)
print("Your MPG: " + Current_MPG)
Using the input() function by itself will let you get a value from the user (already in the form of a string). This way, you won't have to format/convert it later.
Check this out
while True:
Trip_Destination = input("Enter where you would like to travel: ")
Number_Miles = float(input("Enter how many miles to your destination: "))
Gallon_Cost = float(input("Enter how much a gallon of gas costs: "))
Current_MPG = float(Number_Miles / Gallon_Cost)
print("Your trip to: " + Trip_Destination)
print("Your total miles:{}".format(Number_Miles))
print("Your MPG:{}".format(Current_MPG))
print("your string {}".format(x))
its called string formatting
Concatenation
You are trying to add a string and a float, in Python the two won't be automatically casted.
print("Your total miles: " + str(Number_Miles)) # same for miles per gallon
String Formats
Otherwise, you can also use string formatting in order to interpolate the desired variable.
print("Your total miles: {0}".format(Number_Miles)) # same miles per gallon
I've been having some trouble with Else and Elif statements in Python 3.3.3 lately.
Here's my code:
# ATM was programmed by Jamie Mathieson
# introduction
sleep (1)
print ("-----------------------------------------------")
print ("\n ATM ")
print ("\n-----------------------------------------------")
sleep (3)
print ("\nWelcome to ATM. ATM is a mathematical system that handles data.")
sleep (5)
print ("\n Your ATM card has is being inserted. Please wait...")
sleep (3)
print ("Your ATM card has been inserted.")
sleep (5)
print ("Type 'options' to view available commands.")
# variables
balance = print("Balance £", money)
money = 200
options = ("Options: 1) Withdraw <amount> 2) Deposit <amount> 3) Balance 4) Exit")
# statements
option=int(input("Please enter an option: "))
if Option==1:
print("Balance £", money)
if Option==2:
print("Balance £", money)
Withdraw=float(input("Please enter the amount of money you would like to withdraw: £ "))
if Withdraw>0:
newbalance=(money-Withdraw)
print("New Balance: £",remainingbalance)
elif: Withdraw>money
print("No Balance Remaining")
else:
print("Withdraw canceled.")
if Option==3:
print("Balance £", money)
Deposit=float(input("Please enter the amount of money you would like to deposit: £ "))
if Deposit>0:
newbalance=(money+Deposit)
print("New Balance: £",newbalance)
else:
print("Deposit canceled.")
if Option==4:
print("ATM is ejecting your card. Please wait...")
sleep(5)
exit()
The error I'm getting is "invalid syntax" and it highlights both the Else and Elif statements. What is it that I'm doing wrong?
You have to put the : at the end, and correct the identation.
if Option==2:
print("Balance £", money)
Withdraw=float(input("Please enter the amount of money you would like to withdraw: £ "))
if Withdraw>0:
newbalance=(money-Withdraw)
print("New Balance: £",remainingbalance)
elif Withdraw>money:
print("No Balance Remaining")
else:
print("Withdraw canceled.")
There are several issues with the code. As #Daniel pointed out, your indentation must be corrected. Also, your condition for the elif block is placed after the colon.
Beyond that, you're assigning the user's response to a variable called option and then writing conditions on Option. Those are two different things.
Finally balance = print("Balance £", money) is going to throw an error. It looks like you're trying to define balance as a function that will print "Balance £" followed by the balance amount. If so, you could do something like this:
balance = lambda x: print("Balance £{}".format(x))
Edit: To answer your question re: sleep, use
from time import sleep
while True:
# Reading id from user
id = int(input("\nEnter account pin: "))
# Loop till id is valid
while id < 1000 or id > 9999:
id = int(input("\nInvalid Id.. Re-enter: "))
# Iterating over account session
while True:
# Printing menu
print("\n1 - View Balance \t 2 - Withdraw \t 3 - Deposit \t 4 - Exit ")
# Reading selection
selection = int(input("\nEnter your selection: "))
# Getting account object
for acc in accounts:
# Comparing account id
if acc.getId() == id:
accountObj = acc
break
# View Balance
if selection == 1:
# Printing balance
print(accountObj.getBalance())
# Withdraw
elif selection == 2:
# Reading amount
amt = float(input("\nEnter amount to withdraw: "))
ver_withdraw = input("Is this the correct amount, Yes or No ? " + str(amt) + " ")
if ver_withdraw == "Yes":
print("Verify withdraw")
else:
break
if amt < accountObj.getBalance():
# Calling withdraw method
accountObj.withdraw(amt)
# Printing updated balance
print("\nUpdated Balance: " + str(accountObj.getBalance()) + " n")
else:
print("\nYou're balance is less than withdrawl amount: " + str(accountObj.getBalance()) + " n")
print("\nPlease make a deposit.");
# Deposit
elif selection == 3:
# Reading amount
amt = float(input("\nEnter amount to deposit: "))
ver_deposit = input("Is this the correct amount, Yes, or No ? " + str(amt) + " ")
if ver_deposit == "Yes":
# Calling deposit method
accountObj.deposit(amt);
# Printing updated balance
print("\nUpdated Balance: " + str(accountObj.getBalance()) + " n")
else:
break
elif selection == 4:
print("nTransaction is now complete.")
print("Transaction number: ", random.randint(10000, 1000000))
print("Current Interest Rate: ", accountObj.annualInterestRate)
print("Monthly Interest Rate: ", accountObj.annualInterestRate / 12)
print("Thanks for choosing us as your bank")
exit()
# Any other choice
else:
print("That's an invalid choice.")
# Main function
main()