relatively new to programming in python, thank you for all the fast help that was provided on my last question I had on another python project. Anyways, Ive written a new program for a project in python that produces a bill for a catering venue. This is my code below, everything runs fine, and I get the intended results required for the project, The two problems I am experience are, 1. I need the cost of the desert to not print---> 3.0 but ---> $3.00, essentially, how can I print dollar signs, and round e.x 3.0 --> 3.00, or 45.0--> 45.00..and with dollar signs before prices. Sorry if something like this has been asked..
import math
# constants
Cost_Per_Desert = 3.00
Tax_Rate = .075
Gratuity_Tips = .15
Adult_Meal_Cost = 12.75
Child_Meal_Cost = .60*12.75
Room_Fee = 450.00
Less_Deposit = 250.00
def main():
# Input Section
Name = input("\n\n Customer:\t\t\t ")
Number_Of_Adults = int(input(" Number of Adults:\t\t "))
Number_Of_Children = int(input(" Number of Children:\t\t "))
Number_Of_Deserts = int(input(" Number of Deserts:\t\t "))
print("\n\nCost Of Meal Per Adult:\t\t" , Adult_Meal_Cost)
print("Cost of Meal Per Child:\t\t" , round(Child_Meal_Cost,2))
print("Cost Per Desert:\t\t" , round(Cost_Per_Desert,2))
# Processing/Calculations
Total_Adult_Meal_Cost = Adult_Meal_Cost* Number_Of_Adults
Total_Child_Meal_Cost = Child_Meal_Cost* Number_Of_Children
Total_Desert_Cost = Cost_Per_Desert* Number_Of_Deserts
Total_Food_Cost = Total_Adult_Meal_Cost + Total_Child_Meal_Cost + Total_Desert_Cost
Total_Taxes = Total_Food_Cost * Tax_Rate
Tips = Total_Food_Cost * Gratuity_Tips
Total_Bill = Total_Food_Cost + Total_Taxes + Tips + Room_Fee
# Output Section
print("\n\n Total Cost for Adult Meals: \t", Total_Adult_Meal_Cost)
print(" Total Cost for Childs Meals: \t", Total_Child_Meal_Cost)
print(" Total Cost for Desert: \t", Total_Desert_Cost)
print(" Total Food Cost: \t\t", Total_Food_Cost)
print("\n\n Plus 7.5% Taxes: \t\t", round(Total_Taxes,2))
print(" Plus 15.0% Tips: \t\t", round(Tips,2))
print(" Plus Room Fee: \t\t", Room_Fee)
print("\n\n Total Bill: \t\t\t", round(Total_Bill,2))
print(" Less Deposit: \t\t\t", Less_Deposit)
print("\n\nBalance Due: \t\t\t", round(Total_Bill - Less_Deposit,2))
print("\n\n\n\n\t\t Thank You For Using Passaic County Catering Services. ")
main()
input("\n\n\n\n\nPress Enter to Continue")
Let's say cost of desert is $3.00
cost = 3
print("${0:.2f}".format(cost))
Output:
$3.00
When you need to add a $ sign you just simply put a $ sign in your string.
If you would like to fix the decimal number places you just need basic string formatting, like:
print('pi is %.2f' % 3.14159)
and the output would be pi is 3.14
You might wanna like to read: https://docs.python.org/2.7/library/string.html#formatspec
Related
The following is a sample of a running program:
Welcome to the Fast Freight Shipping Company shipping rate program.
This program is designed to take your package(s) weight in pounds and
calculate how much it will cost to ship them based on the following rates.
2 pounds or less = $1.10 per pound
Over 2 pounds but not more than 6 pounds = $2.20 per pound
Over 6 pounds but not more than 10 pounds = $3.70 per pound
Over 10 pounds = $3.80 per pound
Please enter your package weight in pounds: 1
Your cost is: $ 1.10
Would you like to ship another package <y/n>? y
Please enter your package weight in pounds: 5
Your cost is: $ 11.00
Would you like to ship another package <y/n>? y
Please enter your package weight in pounds: 52
Your cost is: $ 197.60
Would you like to ship another package <y/n>? y
Please enter your package weight in pounds: 8
Your cost is: $ 29.60
Would you like to ship another package <y/n>? y
Please enter your package weight in pounds: 3
Your cost is: $ 6.60
Would you like to ship another package <y/n>? t
Invalid Input
Would you like to ship another package <y/n>? y
Please enter your package weight in pounds: 10
Your cost is: $ 37.00
Would you like to ship another package <y/n>? n
Thank you for your purchase, your total charge is $ 282.90
Goodbye!
This is what I have so far:
charges = 0
answer = "yes"
while (answer == "yes"):
packageWeight = eval (input ("Enter weight of package: "))
answer = input ("Do you have more items to input? <yes/no>? ")
if (packageWeight <=2):
charges = (packageWeight * 1.10)
print ("The cost is: $",charges)
elif (packageWeight >2) and (packageWeight<=6):
charges= (packageWeight * 2.20)
print ("The cost is: $", charges)
elif (packageWeight >6)and (packageWeight<=10):
charges = (packageWeight * 3.70)
print ("The cost is: $", charges)
else :
charges = (packageWeight * 3.80)
print ("The cost is: $", charges)
message = "Thank you for your purchase, your total charge is $"
sum= charges+charges
message += format(sum, ',.2f')
print(message)
print("Goodbye!")
how would I find the sum of all charges? And how would I be able to have the second question come after the cost?
So it would display:
Enter weight of package: 3
The cost is: 6.60
Do you have more items to input? yes/no
I did not quite understand this statement how would I find the sum of all charges, but I solved your second question.
Here is the code:
def get_charges(current_weight):
if (current_weight <= 2):
return (current_weight * 1.10)
elif (current_weight > 2) and (current_weight <= 6):
return (current_weight * 2.20)
elif (current_weight > 6) and (current_weight <= 10):
return (current_weight * 3.70)
else:
return (current_weight * 3.80)
charges = 0
answer = "yes"
while (answer == "yes"):
# Eval is not recommended, use a float and round if needed.
packageWeight = float(input("Enter weight of package: "))
charges += get_charges(packageWeight)
print("Current charges: ", charges)
answer = input("Do you have more items to input? <yes/no>? ")
print(f"Thank you for your purchase, your total charge is ${charges}")
print("Goodbye!")
eval() is not recommended for security reasons, so I changed it to float().
Let me know if you have any questions
trying to fix this code for tipping.
Let's add a tipping function. I've created the bare-bones of the function, which will take in the cost of the meal, and ask for a percentage to tip on the meal. You do the rest!
def tip(cost):
percentage = input("What percent would you like to tip? ")
tip = round(cost * percentage, 2)
print("The tip amount of", percentage, "% is ", tip)
return tip
the first part does not seem to work
after that, I run
cost, items = order(menu)
print("Your order is", items)
cost = round(cost + tax("vt", cost, tax_rate), 2)
cost = round(cost + tip(cost), 2)
print("Your total cost is", cost)
You have to convert the input to float in order to perform mathmatical operation . Otherwise it will multiply the string with number and return a repeated string.
def tip(cost):
percentage = float(input("What percent would you like to tip? "))
tip = round(cost * percentage, 2)
print("The tip amount of", percentage, "% is ", tip)
return tip
New to Python, doing Introduction to Programming with Python with Grok Learning.
I have this problem where I need to take input, convert to a list, convert to integers and then collect the sum of the integers. Here's what I have so far:
expenses = input("Enter the expenses: ")
expenses.split()
for expense in expenses:
print(int(expenses))
total = sum(expenses)
print("Total: $" + total)
I was told I have to loop over the array and then convert to integers. But I have no idea what this means, can someone please show me?
Since you already wrote that for loop I'm assuming you know what it means, so you simply need to create another list, for storing the int values:
intValues = []
for expense in expenses:
intValues.append(int(expense))
and then print(sum(intValues)) works the same. You could do the same in just one line using Python's list comprehension syntax:
intValues = [int(expense) for expense in expenses]
Firstly you need to indent total=sum(expenses) into the for loop and need to save the split result in a variable so modified program is:
expenses = input("Enter the expenses: ")
for expense in expenses.split:
print(int(expense))
total = sum(expense)
print("Total: $" + total)
Try this:
expenses = input('Enter the expenses: ')
expenses = expenses.split()
total = 0
for expense in expenses:
total += int(expense)
print('Total: $' + str(total))
When I did this challenge, this was my code:
money = input("Enter the expenses: ")
money = money.split()
total = sum([int(i) for i in money ])
print("Total:", "$" + str(total))
The first line is just the input of money. The second line splits each number into a list. The 3rd line calculates the sum of the input as an integer, then the 4th changes it back to a string and prints it.
To fix your error, try this:
expenses = input("Enter the expenses (separated by spaces): ")
total = 0
for expense in expenses.split():
total += int(expense)
print(expense)
print( "Total: $" + str(total) )
A sample session:
Enter the expenses (separated by spaces): 12 34 56
12
34
56
Total: $102
Trying to write this salary calculator script, but the output keeps on calculating taxes twice. It does what it is supposed to do, but I am misusing the concept of return statement, I reckon. I am kinda new to Python and just starting with the DSA. I tried searching for this problem a lot but apart from info for return statement, I couldnt solve this recurring statement problem. I would like your suggestions on the rest of the program as well.
Thanks!
Here is my code:
import math
# Personal Details
name = input("Enter your first name: ")
position= input("Enter your job position: ")
def regPay():
#Computes regular hours weekly pay
hwage= float(input("Enter hourly wage rate: "))
tothours=int(input("Enter total regular hours you worked this week: "))
regular_pay= float(hwage * tothours)
print ("Your regular pay for this week is: ", regular_pay)
return hwage, regular_pay
def overTime(hwage, regular_pay):
#Computes overtime pay and adds the regular to give a total
totot_hours= int(input("Enter total overtime hours this week: "))
ot_rate = float(1.5 * (hwage))
otpay= totot_hours * ot_rate
print("The total overtime pay this week is: " ,otpay )
sum = otpay + regular_pay
print("So total pay due this week is: ", sum)
super_pay = float((9.5/100)*sum)
print ("Your super contribution this week is:",super_pay)
return super_pay
def taxpay():
#Computes the taxes for different income thresholds, for resident Aussies.
x = float(input("Enter the amount of your yearly income: "))
while True:
total = 0
if x < 18200:
print("Congrats! You dont have to pay any tax! :)")
break
elif 18201 < x < 37000:
total = ((x-18200)*0.19)
print ("You have to pay AUD" ,total , "in taxes this year")
return x
break
elif 37001 < x < 80000:
total = 3572 + ((x-37000)*0.32)
print("You have to pay AUD",(((x-37000)*0.32) +3572),"in taxes this year")
return x
break
elif 80001 < x < 180000:
total = 17547+((x-80000)*0.37)
print ("You have to pay AUD" ,total ,"in taxes this year")
return x
break
elif 180001 < x:
total = 54547+((x-180000)*0.45)
print ("You have to pay AUD" , total ,"in taxes this year")
return x
break
else:
print ("Invalid input. Enter again please.")
break
def super(x):
#Computes super over a gross income at a rate of 9.5%
super_rate = float(9.5/100)
super_gross = float((super_rate)*(x))
print ("Your super contribution this year is: ",super_gross)
def main():
#Main function to pass vars from regPay to overTime and call.
hw , r_p = regPay()
overTime(hw, r_p)
taxpay()
y = taxpay()
super(y)
#Call main
main()
The output I get in powershell:
PS C:\Users\tejas\Desktop\DSA> python salary_calc.py
Enter your first name: tj
Enter your job position: it
Enter hourly wage rate: 23
Enter total regular hours you worked this week: 20
Your regular pay for this week is: 460.0
Enter total overtime hours this week: 20
The total overtime pay this week is: 690.0
So total pay due this week is: 1150.0
Your super contribution this week is: 109.25
Enter the amount of your yearly income: 20000
You have to pay AUD 342.0 in taxes this year
Enter the amount of your yearly income: 20000
You have to pay AUD 342.0 in taxes this year
Your super contribution this year is: 1900.0
From your output, I see it asks twice for the yearly income:
Enter the amount of your yearly income: 20000
You have to pay AUD 342.0 in taxes this year
Enter the amount of your yearly income: 20000
You have to pay AUD 342.0 in taxes this year
Looks like your problem is here:
def main():
#Main function to pass vars from regPay to overTime and call.
hw , r_p = regPay()
overTime(hw, r_p)
taxpay()
y = taxpay()
super(y)
You call taxpay(), then set y to another call of taxpay(). Did you mean just to call this once? If so, try this instead:
def main():
#Main function to pass vars from regPay to overTime and call.
hw , r_p = regPay()
overTime(hw, r_p)
y = taxpay()
super(y)
Simply put, both of the following call / execute the taxpay function, so this will repeat exactly the same output, unless you modify global variables, which doesn't look like you are.
Only the second line will return the value into the y variable.
taxpay()
y = taxpay()
Along with that point, here you call the function, but never capture its returned output
overTime(hw, r_p)
And, as an aside, you don't want to break the input loop on invalid input.
print ("Invalid input. Enter again please.")
break # should be 'continue'
I am making a macronutrient calculator. This this calculator if the user makes an error calculator simply restarts and goes back to the main(). However, I believe my use of main() in my code causes the display of 2 runs of the code
Here is the link to my code: http://pastebin.com/FMqf2aRS
*******Welcome to the MACRONUTRIENT CALCULATOR********
Enter your calorie deficit: 30
Percentage of Protein: 30
Percent of Carbohydrates: 40
Percentage of Fats: 40
Total percentages surpassed 100! Please reenter percentages.
*******Welcome to the MACRONUTRIENT CALCULATOR********
Enter your calorie deficit: 2200
Percentage of Protein: 30
Percent of Carbohydrates: 30
Percentage of Fats: 40
You must eat 660.0 calories of protein which is equivalent to 165.0 grams of protein.
You must eat 880.0 calories of fat which is equivalent to 97.7777777778 grams of fat.
You must eat 660.0 calories of carbohydrates which is equivalent to 73.3333333333 grams of carbohydrates.
You must eat 9.0 calories of protein which is equivalent to 2.25 grams of protein.
You must eat 12.0 calories of fat which is equivalent to 1.33333333333 grams of fat.
You must eat 12.0 calories of carbohydrates which is equivalent to 1.33333333333 grams of carbohydrates.
Is there a different way of approaching this to prevent this from happening?
Calling main() the way you are doing it is the wrong way to solve this. You're pushing more and more main() calls onto the stack - eventually the program will crash if you enter invalid entries too many times in a row. You should use a while loop as shown below
def main():
while True:
print "*******Welcome to the MACRONUTRIENT CALCULATOR********"
calorie_deficit = float(input("Enter your calorie deficit: "))
Percent_protein = float(input("Percentage of Protein: "))
Percent_carb = float(input("Percent of Carbohydrates: "))
Percent_fat = float(input("Percentage of Fats: "))
Macro_dict = {'Protein': Percent_protein, 'Carbohydrate': Percent_carb, 'Fats': Percent_fat}
Macro_sum = Percent_protein + Percent_carb + Percent_fat
if not Total_Macro_Check(Macro_sum):
continue
Macro_percentage_to_calorie(calorie_deficit, Percent_protein, Percent_carb, Percent_fat)
def Total_Macro_Check(total_val):
if total_val > 100:
print "Total percentages surpassed 100! Please reenter percentages."
return False
if total_val < 100:
print "Total precentages is less than 100! Please reenter precentages."
return False
return True
The code is doing exactly what you tell it to do:
def Total_Macro_Check(total_val):
if total_val > 100:
print "Total percentages surpassed 100! Please reenter percentages."
main()
if total_val < 100:
print "Total precentages is less than 100! Please reenter precentages."
main()
You call main again.