python sum function is giving error when summing user input - python

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

Related

Shipping Charges calculator not producing the correct result

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

Python : Amount input with While

Beginner here. I'm trying to build a loop where the chekout displays a total amount that has to be over 0$. For example, if I start with 450$ the code works. But if I start with say -12 it will ask me again (which is what I want), but then if I enter 450 as the third essay; the first condition keeps runing. Why is that? Thanks in advance.
amount = input("What's the total amount of the bill ? :")
value = float(amount)
while (value < 0):
print("Please enter an amount higher than 0$ !")
amount = input("What's the total amount of the bill ? :")
else:
print("Total amount of the bill:{0}".format(value))
You forgot to update the variable "value" so your while loop condition remains true even after inputting 450 (value is still -12). You can convert the input to a float in the same line too, which removes the need for the "amount" variable
value = float(input("What's the total amount of the bill ? :"))
while (value < 0):
print("Please enter an amount higher than 0$ !")
value = float(input("What's the total amount of the bill ? :"))
else:
print("Total amount of the bill:{0}".format(value))

My while loop is keeps looping. What am I doing wrong?

In this the total amount is the amount the user need to pay. If user pay lesser than the total amount the system needs to subtract the payment and show their balance and keep on looping until the payment is completed. But, when I run my codes its keep on looping while showing the balance.
print ("Your total amount is:", total_amount)
print ("")
payment = int(input("Please insert your payment: "))
count = 0
while payment != total_amount:
count = total_amount - payment
print ("Your balance:", count)
payment = int(input("Please insert your payment: "))
if payment == total_amount:
print ("Successful")
does the program outputs "Successful" if the user inputs the total amount on the first input?
if the user doesnt input the total amount on the first input, what could happen is that the variable named payment will never be equal to the total payment, but the count will eventually reach the total amount yes, but the while loop does not has variable count working is logic statement, it uses payment as the variable for its logic. if someones buys a something from a store, and the total is 5 dollars,, and the buyer has 1 dollar bills, the buyer will first put one dollar on the counter, then the other 1, and so on... but the buyer will not put 1 dollar on the counter, and then 5 dollars on the counter, because that would be 6 dollars
You are not updating either payment or total_amount correctly in the loop. I believe this should work.
payment = int(input("Please insert your payment: "))
while payment <= total_amount:
diff = total_amount - payment
print("Your balance:", diff)
payment += int(input("Please insert your payment: "))
if payment == total_amount:
print("Successful")
 Based on your code, only if I pay the correct amount in one go, should I successfully pay. Of course this is wrong. I have modified and added some details to your code like this:
print("Your total amount is: $%.2f \n" % (total_amount))
count = 0
while count < total_amount:
payment = int(input("Please insert your payment: $"))
count += payment
print ("Your balance: $%.2f" % (total_amount - count))
print("Successful")
if count > total:
print("Your change is $%.2f" % (count - total))

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'

While loop runs continuously in Python, good input or bad?

I'm writing a code that asks the user for a percentage, and keeps asking until an acceptable input is entered by the user. However when I run this, the while loop does not break no matter what kind of input I enter.
Here is my code:
import math
while True:
try:
entered = float(raw_input("Please enter the velocity (as a percentage of the speed of light): "))
except ValueError:
print("Sorry, an acceptable input was not entered. Try again.")
continue
if entered > 100:
print("Sorry, a velocity greater than the speed of light cannot be used. Try again.")
continue
elif entered <= 0:
print("Sorry, a percent cannot be negative. Try again.")
continue
else:
#the percent entered is valid, break out of while loop
break
print("Ship is traveling at ", entered, "% the speed of light.")
print(" ")
speedOfLight = 299792458 #speed of light constant
percentage = entered / 100 #turn entered percent into decimal
speed = speedOfLight * percentage #actual speed (in m/s)
denominator = math.sqrt(1 - (percentage ** 2)) #denominator of factor equation
factor = 1 / denominator #solve for given factor equation
shipWeight = 70000 * factor #given ship weight * factor
alphaCentauri = 4.3 / factor # given times divided by the factor
barnardsStar = 6.0 / factor
betelgeuse = 309 /factor
andromeda = 2000000 / factor
print("At this speed: ")
print(" Weight of the shuttle is ", shipWeight)
print(" Perceived time to travel to Alpha Centauri is ", alphaCentauri, " years.")
print(" Perceived time to travel to Barnard's Star is ", barnardsStar, " years.")
print(" Perceived time to travel to Betelgeuse is ", betelgeuse, " years.")
print(" Perceived time to travel to Andromeda Galaxy is ", andromeda, " years.")
You are checking the inputs of your data inside your except. You are never going to get inside your except unless the casting to float raises a ValueError.
You simply want to move your conditions outside of the except block, so you can check the data that passes the float casting:
while True:
try:
entered = float(input("Please enter the velocity (as a percentage of the speed of light): "))
except ValueError:
print("Sorry, an acceptable input was not entered. Try again.")
continue
if entered > 100:
print("Sorry, a velocity greater than the speed of light cannot be used. Try again.")
continue
elif entered <= 0:
print("Sorry, a percent cannot be negative. Try again.")
continue
else:
#the percent entered is valid, break out of while loop
break
Your indentation is a little wonky, and the code never reaches the break statement because you continue the loop before then. Luckily, you can use and else keyword to make it work:
while True:
try:
entered = float(raw_input("Please enter the velocity (as a percentage of the speed of light): "))
except ValueError:
print("Sorry, an acceptable input was not entered. Try again.")
continue
else: # no exception
if entered > 100:
print("Sorry, a velocity greater than the speed of light cannot be used. Try again.")
continue
elif entered <= 0:
print("Sorry, a percent cannot be negative. Try again.")
continue
else:
#the percent entered is valid, break out of while loop
break
You don't even need the continues/breaks to make this work. You also will need to "import math" which will matter once you eventually break out of the while loop.
What you do need to do is watch the indention. The try/except were out of position -- if that reflects how the code was actually written that would account for your never ending while loop.
The below works as you desired with only indention fixes and "import math"
import math
valid = False
while not valid:
try:
entered = float(raw_input("Please enter the velocity (as a percentage of the speed of light): "))
except ValueError:
print("Sorry, an acceptable input was not entered. Try again.")
continue
if entered > 100:
print("Sorry, a velocity greater than the speed of light cannot be used. Try again.")
elif entered <= 0:
print("Sorry, a percent cannot be negative. Try again.")
else:
#the percent entered is valid, break out of while loop
valid = True
print("Ship is traveling at ", entered, "% the speed of light.")
print(" ")
speedOfLight = 299792458 #speed of light constant
percentage = entered / 100 #turn entered percent into decimal
speed = speedOfLight * percentage #actual speed (in m/s)
denominator = math.sqrt(1 - (percentage ** 2)) #denominator of factor equation
factor = 1 / denominator #solve for given factor equation
shipWeight = 70000 * factor #given ship weight * factor
alphaCentauri = 4.3 / factor # given times divided by the factor
barnardsStar = 6.0 / factor
betelgeuse = 309 /factor
andromeda = 2000000 / factor
print("At this speed: ")
print(" Weight of the shuttle is ", shipWeight)
print(" Perceived time to travel to Alpha Centauri is ", alphaCentauri, " years.")
print(" Perceived time to travel to Barnard's Star is ", barnardsStar, " years.")
print(" Perceived time to travel to Betelgeuse is ", betelgeuse, " years.")
print(" Perceived time to travel to Andromeda Galaxy is ", andromeda, " years.")

Categories