Shipping Charges calculator not producing the correct result - python

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

Related

my program keeps looping and I don't know why

the user is required to input package weight and after I input the packages it gives me the correct answer but the answer keeps on repeating.
heres the code:
more = "y"
count = 0
total = 0
x = 0
while(more == "y"):
lbs = eval(input("Please enter the weight of the package: "))
if (lbs >= 1 and lbs <= 2):
op1:(lbs * 1.10)
x = op1
count += 1
total += x
print("The current package shipping cost is:",op1)
if (lbs > 2 and lbs <= 6):
op2 = (lbs * 2.20)
x = op2
count += 1
total += x
print("The current package shipping cost is:",op2)
if (lbs > 6 and lbs <= 10):
op3 =(lbs * 3.70)
x = op3
count += 1
total += x
print("The current package shipping cost is:",op3)
if (lbs > 10):
op4 =(lbs * 3.80)
x = op4
count += 1
total += x
print("The current package shipping cost is:",op4)
if (lbs == 0):
print("your package cannot be delivered")
more = input ("Do you want to enter another Package? <y/n>: ")
while(more == "n"):
print("Your total shipping cost is:",total,"for",count,"packages")
This line -
while(more == "n"):
print("Your total shipping cost is:",total,"for",count,"packages")
You do not need the while loop. Just do -
print("Your total shipping cost is:",total,"for",count,"packages")
Additionally, you do not need eval(), just use int() -
lbs = int(input("Please enter the weight of the package: "))
You could use range() function instead of the >= <= ... etc. things. For e.g. -
if lbs in range(1,2+1): # Not really useful, still you could use this
# code
It is not significant, so to keep it simple, you do not need to use the range function
why don't you just start with
while True:
and place a break after each if evaluation, then you get only correct input, and in case of incorrect input the while loop starts again with the input question.
The input question also requires the information that the weight needs to be in lbs.
Since you deleted your previous question about your code is giving you errors and functions are not working...here I will explain what are your errors and the new program.
1.Your first error is you used def greeting function and you didn't complete the function and you have to define what the function should do when you call the function. You used def Greeting(): but you didn't complete it,if you are using a def function you always have to complete it after():
2.Your 2nd error is your while loop is not correct.It has some logical errors
3.Your 3rd error is your functions(op1.op2,op3,op4) are in the wrong format that's why your program didn't work as you expect
🎁here i update your previous question which was asked on 22nd October 2021...please go through this code and compare it to your one and learn your errors.
Good Luck buddy and always learn from your errors:)
new code:
def Greeting():
print('good morning')
Greeting()
n=str(input("please input full name: "))
print("hello",n,"this program will allow you to input package weight and display price")
package_count=0
total=0
more=False
while more==False:
more = input ("Do you want to enter another Package? <y/n>: ")
if(more == "y"):
lbs = int(input("Please enter the weight of the package: "))
else:
print('your total shipping cost is:',total,"for",package_count,'packages')
break
if (lbs>=1 and lbs<=2):
op1=(lbs*1.10)
print('The current package shipping cost is: ',op1)
package_count=package_count+1
total=op1
elif(lbs>2 and lbs<=6):
op2 = (lbs * 2.20)
print('The current package shipping cost is:',op2)
package_count=package_count+1
total=total+op2
elif(lbs > 6 and lbs <= 10):
op3 =(lbs * 3.70)
print("The current package shipping cost is:",op3)
package_count=package_count+1
total=total+op3
elif(lbs>10):
op4=(lbs*3.80)
print("The current package shipping cost is:",op4)
package_count=package_count+1
total=total+op4
else:
print("your package cannot be delivered")
more=False

I am not getting the print statement I want by using inputs for a shipping calculator

The Speedy Shipping Company will ship packages based on how much they weigh and how far they are being sent. They will only ship light packages up to 10 pounds. You have been tasked with writing a program that will help Speedy Shipping determine how much to charge per delivery.
The charges are based on each segment of 500 miles shipped. Shipping charges are not pro-rated; i.e., 600 miles is the same charge as 900 miles; i.e., 600 miles is counted as 2 segments of 500 miles.
Your program should prompt the user for inputs (weight and miles), accept inputs from the keyboard, calculate the shipping charge, and produce accurate output.
Test:Prompts / Inputs:
Please enter package weight in pounds: 1.5
Please enter number of miles to ship: 200 (This is one 500-mile segment.)
Expected result:
To ship a 1.5 pound package 200 miles, your shipping charge is $1.50.
Helpful Hints:
You can use integer (floored) division. For example: 1200 // 500 = 2
So I have typed the code to the best of my knowledge however my print statement just prints (1.5). I need help in understanding why my print statement won't print the results.
# Package of Weight Rate per 500 miles shipped
# 2 pounds or less $1.50
# More than 2 but not more than 6 $3.75
# More than 6 but not more than 10 $5.25
weight_of_package = int(input("1.5"))
num_miles_ship = int(input("200"))
shipping_rate = 0
if weight_of_package > 0 and weight_of_package <= 2:
shipping_rate = 1.50
elif weight_of_package > 2 and weight_of_package <= 6:
shipping_rate = 3.75
elif weight_of_package > 6 and weight_of_package <= 10:
shipping_rate = 5.25
else:
print('Sorry, we only ship packages of 10 pounds or less')
shipping_charge = weight_of_package//num_miles_ship * shipping_rate
print(("To ship a " +str(weight_of_package) + "pound package" + str(num_miles_ship)
+ "your shipping charge is" + str(shipping_charge,".2f")))
There are several problems with your code.
The input method does probably do something else than you think. I does not convert anything, but it ask the user (you) for input and return this input. a=input("enter value for a:") will just open a prompt that will let you type something on your keyboard and when you press enter this will be copied into variable a here. So you may want to do weight_of_package=int(input("enter weight of package: ")) etc.
In your if/elif sequence: careful! python uses indentation to understand your scoping! This is critical in python and wrong in your code. You have to intend code in the if/elif blocks.
You can save some typing in the elif statements, since all the weight_of_package > XXX statements have no effect because of the preceding if statements (this would be just the else)
Before you second-last line shipping_charge = ... you need to protect against shipping_rate equal to zero. This will happen for a weight_of_package > 10 and will just fail in the calculation. Thus you need to add if shipping_rate>0: ...
Division operator in python is / not //
Best leave away the ,"2.f" in str(shipping_charge,".2f") since this does not do what you believe. If you do want to use formatted output use the standard python format syntax "{:.2f}".format(shipping_charge)`. Please consult https://docs.python.org/3/library/string.html#formatspec which is very interesting and relevant.
Here is the full example:
# Package of Weight Rate per 500 miles shipped
# 2 pounds or less $1.50
# More than 2 but not more than 6 $3.75
# More than 6 but not more than 10 $5.25
weight_of_package = int(input("please enter weight of package: "))
num_miles_ship = int(input("please enter miles to ship: "))
shipping_rate = 0
if weight_of_package > 0 and weight_of_package <= 2:
shipping_rate = 1.50
elif weight_of_package <= 6:
shipping_rate = 3.75
elif weight_of_package <= 10:
shipping_rate = 5.25
else:
print('Sorry, we only ship packages of 10 pounds or less')
if shipping_rate > 0:
shipping_charge = weight_of_package / num_miles_ship * shipping_rate
print("To ship a {} pound package {} miles "
"your shipping charge is {:.2f} ".format(
weight_of_package, num_miles_ship, shipping_charge))
Your print statement is probably not being executed at all right now
I am guessing that 1.5 which you are probably seeing is the result of this line probably
weight_of_package = int(input("1.5"))
The input() function in python takes an argument that tells the user about the input being required. So, if you change it to
weight_of_package = float(input("Enter the weight of package"))
and then run the program. You'll be prompted to Enter the weight of package following which you need to give the program input for the weight of the package ( and you'll enter 1.5 )
Also, you need to use float instead of int in that line as 1.5 is a decimal value
Making this change, it'll be easier for you to debug the print statements that are at the bottom of the code as 1.5 won't confuse you.

python sum function is giving error when summing user input

print ("Budget Analysis Program")
print()
budget = float(input("Enter amount budgeted for the month: $"))
print()
print("<<<<Your Expenses for the month>>>>")
amount = float(input("Enter an amount spent (0 to quit): $"))
#calculate the amount left in budget
while (amount>0):
amount = float(input("Enter an amount spent (0 to quit): $"))
while (amount<0):
amount = float(input("Enter an amount spent (0 to quit): $"))
print()
sum =0
total = sum(amount)
print("Budgeted: $", budget)
print(" Spent: $", total)
print()
def left(float):
left = (budget - total)
if (left > 0):
print ("You are $",left,"under budget. WELL DONE!")
elif (left == 0):
print ("Spending matches budget. Good Planning!")
else:
print ("You are $",abs (left),"over budget. PLAN BETTER NEXT TIME!")
Here is the program I am writing, but I am getting an error saying that "function" can't be combined with "float" or something of that sort. The error is with my sum command, can someone help guide me in the right direction?
Thank you

How to use the return function but avoid repetition of a function?

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'

Printing out a proper bill producing program in python

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

Categories