Need guidance to solve my error in python code - python

I am a beginner in python and need help to solve the error in my code. I have to write the code from the given flowchart such the user gets the minimum amount of coins in return, but I didn't get the accurate answer, so can you please help me to figure out my mistake and guide me.
[1]: https://i.stack.imgur.com/AUq44.png
Here is my code:
print("amount: ",amount)
payment = input("amount of Payment: ")
payment = float(payment)
change = payment - amount
change = round(change,2)
if change>0:
d = change // 1
change = change - d
if change>0:
q = change // 0.25
i = change // 0.10
n = change // 0.05
change = change - q * 0.25 + i * 0.10 + n * 0.05
n = n+round(change*2,1)*10
print("you got",d,"dollars",q,"quaters,",i,"dimes, and",n,"nickels back in change")
else: print("you got",d,"dollars",q,"quaters,",i,"dimes, and",n,"nickels back in change")
else: print('No change owed')

I won't write the code for you as this will be the best way for you to take benefit from my answer and the help from the community, as well as respecing your work and your classmates'.
There are two main flaws which might cause the problems you are experiencing.
You are calculating all the sub-unities of your currency based on the same value, i.e. the whole amount of change.
q = change // 0.25
i = change // 0.10
n = change // 0.05
The expected output of this section is to have, for a 2 dollars payment:
q = 8
i = 20
n = 40
But if we sum them up togheter, we obtain 8*0.25 + 20*0.1 + 40*0.05 = 6$! How's that?
Pointer: You need to make sure to update your change value, after you have performed the remainderless division.
There is a chance that you get NameError: name 'q' is not defined
if change>0:
q = change // 0.25
i = change // 0.10
n = change // 0.05
change = change - q * 0.25 + i * 0.10 + n * 0.05
n = n+round(change*2,1)*10
print("you got",d,"dollars",q,"quaters,",i,"dimes, and",n,"nickels back in change")
else:
print("you got",d,"dollars",q,"quaters,",i,"dimes, and",n,"nickels back in change")
Taking a look at the above code, assume that change is equal to 0. You are however asking your Python script to print the value of d,q,i and n. But have you initialised these variables in this case?

This is close to a manual division. That means that you should substract the big divisor part before using next divisor. You did int correctly for the dollar part (change = change -d), but failed to do it for the smaller coins. It should be:
if change>0:
q = change // 0.25
change -= q * .25
i = change // 0.10
change -= i * .10
n = change // 0.05
change -= n * .25
Anyway, you are using floating point values for money operations, which is bad because floating point is inaccurate
As soon as you want exact operations in cents, you should either use integer number of cents, or use the Decimal class from the Standard Library.

Related

How to loop in python to target amount?

I'm having difficulty with the below problems and not sure what I'm doing wrong. My goal is to figure out how many periods I need to compound interest on a deposit using loops to reach a target deposit amount on a function that takes three arguments I have to create. I've included what I have below but can't seem to get my number of periods.
Example:
period(1000, .05, 2000) - answer 15
where d is initial deposit, r is interest rate and t is target amount.
new_deposit = 0
def periods (d,r,t):
while d*(1+r)<=t:
new_deposit = d*(1+r) - d
print(new_deposit)
return periods
I'm very new to this so not sure where I'm going wrong.
You were close, but your return statement would throw an error as you never set periods.
def periods(d,r,t):
count_periods = 1
current_ammount = d
while current_ammount*(1+r)<=t:
current_ammount = current_ammount*(1+r)
count_periods+=1
print(current_ammount)
return count_periods
print(periods(100, 0.01, 105))
I renamed the return variable, as to not overlap with the function name itself.
EDIT: sorry your logic was flawed all the way through the code, rewrote it.
def periods(d, r, t):
p = 0
while d < t:
d *= (1 + r)
p += 1
return p
periods(100, .01, 105) # 5

"Name can be undefined" problem in python

I'm trying to improve my code so this is about a 'problem notification' telling me that a variable can be undefined.
This is my code:
print('\nWindow types')
print('1:1200 x 1300 mm')
print('2:800 x 1000 mm')
print('3:2100 x 1500 mm')
Window_Dimension = float(input('Select window type: '))
if Window_Dimension == 1:
A = 1200
B = 1300
elif Window_Dimension == 2:
A = 800
B = 1000
elif Window_Dimension == 3:
A = 2100
B = 1500
else:
print('Invalid input!')
Lip_height = float(input('\nEnter lip eight (mm): '))
SWind_velocity = 80 # m/s Static wind velocity
print('Assuming a peak wind velocity of: 80 m/s')
Wind_pressure = (SWind_velocity ** 2) / 1600 # kN/m^2
print('Wind pressure (kN/m^2):', Wind_pressure)
a = A - (2 * Lip_height)
b = B - (2 * Lip_height)
Lip_area = (A * B) - (a * b) # m^2
Lip_pressure = (Wind_pressure * (A * B) / 1000000) / (Lip_area / 1000000) # kN/m^2
print('Uniform pressure on the lip (kN/m^2): ', round(Lip_pressure, 3))
and it works just fine, but I keep getting a problem notification about this two lines:
a = A - (2 * Lip_height)
b = B - (2 * Lip_height)
telling me that A and B can be undefined. I don't know if there's is a way to fix this, or even if I should fix it, but I'm new in python and I'm trying to avoid future "coding bad habits". Thanks
Don't simply print an error message and proceed when something goes wrong. Throw an exception. Instead of
print('Invalid input!')
Consider
raise Exception('Invalid input!')
As far as I can tell, it works perfectly. I don't get any error. Perhaps you need to define the variables right at the beginning.
Right at the beginning, add this in:
a = 0
b = 0
This set the variables right at the beginning, without a calculation. Later on, it would only rewrite the variable, not create it.
Let me know if this worked!

Why does using float() remove my formatted decimal places?

I am trying to write a simple program that compares shipping costs. I have a default float value that is premium and two functions that check against it and gives the user the cheapest value based on the weight of their product.
My code is below:
premium_shipping = 125.00
def ground_shipping(weight):
if weight <= 2.0 and weight >= 0:
return float('{:.2f}'.format((weight * 1.50) + 20))
elif weight > 2.0 and weight <= 6.0:
return float('{:.2f}'.format((weight * 3.00) + 20))
elif weight > 6.0 and weight <= 10.0:
return float('{:.2f}'.format((weight * 4.00) + 20))
elif weight > 10:
return float('{:.2f}'.format((weight * 4.75) + 20))
else:
return "Your package doesn't weigh anything!"
def drone_shipping(weight):
if weight <= 2.0 and weight >= 0:
return float('{:.2f}'.format(weight * 4.50))
elif weight > 2.0 and weight <= 6.0:
return float('{:.2f}'.format(weight * 9.00))
elif weight > 6.0 and weight <= 10.0:
return float('{:.2f}'.format(weight * 12.00))
elif weight > 10:
return float('{:.2f}'.format(weight * 14.25))
else:
return "Your package doesn't weigh anything!"
def cheapest_shipping(weight):
if ground_shipping(weight) < drone_shipping(weight) and ground_shipping(weight) < premium_shipping:
return f'The cheapest shipping method is ground shipping. It would cost {ground_shipping(weight)} to ship your item.'
elif drone_shipping(weight) < ground_shipping(weight) and drone_shipping(weight) < premium_shipping:
return f'The cheapest shipping method is drone shipping. It would cost {drone_shipping(weight)} to ship your item.'
elif premium_shipping < ground_shipping(weight) and premium_shipping < drone_shipping(weight):
return f'The cheapest shipping method is premium shipping. It would cost {premium_shipping} to ship your item.'
else:
return "Error. You have input an invalid weight."
print(ground_shipping(4.8))
# 34.4
print(cheapest_shipping(4.8))
# The cheapest shipping method is ground shipping. It would cost 34.4 to ship your item.
print(cheapest_shipping(41.5))
When I do this, I technically get my answer however I want it to be at 2 decimal places
When I remove the float() from the two functions, the value I get back is to 2 decimal places but is a str. When I include the float() it returns my number as a float with 1 decimal place and I am unsure on how to change it to include 2 decimal points.
Thanks in advance!
There is no difference between the float values 2, 2.0, 2.00000000000000000, and 200e-2. If you want to present a float in a certain way, that's best done at formatting time, with any of (in order of preference):
>>> pi = 3.14159
>>> f"{pi:.2f}" # f-strings, introduced in Python 3.6.
'3.14'
>>> "{:.2f}".format(pi) # str.format, use f-strings in preference.
'3.14'
>>> "%.2f" % (pi) # VERY old method, avoid if possible.
'3.14'
Provided you're using a recent enough version of Python, f-strings are the way to go. Unlike % and str.format(), they keep the data item localised to where it will be printed in the string so you don't have to go searching for it in the argument list. Contrast the following:
f"Hello, {name}, today is {dayOfWeek}"
"Hello, {}, today is {}".format(name, dayOfWeek)
You seem to have some confusion between what a float is and how it is displayed. A float is a binary number with 53 bits of decimal precision that can hold a wide variety of values. You can display a float however you want. For example:
float('{:.2f}'.format(weight * 14.25))
Here you take a float value weight * 14.25, convert it to a string with two decimal places using the format method, and then back with the float function. This may or may not truncate the digits after the second decimal place, since most decimal fractions are not representable exactly in binary.
You display your values without the same consideration, however:
print(ground_shipping(4.8))
If you want to print this as a two-digit number, you should format it the same way as you did previously:
print(f'{ground_shipping(4.8):0.2f}')
OR
print('{:0.2f}'.format(ground_shipping(4.8)))

It is not working as expected. How can i fix this code?

I want the code to increase my semi_annual_income every six months, by making the the semi_annual income increase every six months with by specific percentage. so it was suppose to be according to my math 1000(1.2)^i/6 this equation would increase my income by 0.2 every 6 months where the i is divisible by 6.
I tried to both the expressions when I use the expression 1000(1.2)^i/6 it will give me a very huge number. and the expression 1000(1 +0.2) is giving me the exact answer that 1000(1 + 0.2) should have given me.
number_of_months = 0
total_cost = 100000
semi_annual_income = 1000
starting_salary = 10
semi_annual_rise = 0.2
while semi_annual_income < total_cost:
for i in range(100):
if float(i)%6 == 0:
power_number = float(i)/6
# i am using this to make it increase the semi_annual income just only every six months
semi_annual_income = semi_annual_income *(float(1) + float(semi_annual_rise))
print(power_number)
print(semi_annual_income)
#semi_annual_income = (semi_annual_income *(float(1) + float(semi_annual_rise))** float(power_number))
#The above written code is giving me a very huge number i want it to give me the answer as 1000(1 + 0.2)^i/6
break
I got the answer I wanted from the code but I don't understand why is it giving me the answer without the power and the one with the power is not giving me the answer.
number_of_months = 0
total_cost = 100000
semi_annual_income = 1000
starting_salary = 1000
semi_annual_rise = 0.2
number_of_months = 0
while semi_annual_income < total_cost:
for i in range(1,100):
if float(i)%6 == 0:
power_number = float(i)/6# i am using this to make it increase the
semi_annual income just only every six months
number_of_months = number_of_months + 1
semi_annual_income = starting_salary *(float(1) +
float(semi_annual_rise))**(power_number)
print(power_number)
print(semi_annual_income)
print(number_of_months)
# I think my mistake was the i used semi_annual-income instead of starting salary, this code works as i wanted it to be.
break

Using Taylor expansion to calculate pi with an user set precision value

The input is the precision to which pi is calculated and I need to output the value of calculated pi and the number of terms to reach that value.
This is the code that I have made and it is supposed to print out (3.33968, 5). Could someone check where I have went wrong?
t_precisionstr = input("Precision Value for Taylor: ")
t_precision = float(t_precisionstr)
t_list = []
def taylor(t_precision):
t_number1 = 0
t_number2 = 1
t_final = 0
while t_final <= abs(m.pi - t_precision):
t_number1 = t_number1 + 1
t_answer = t_number2 + ((-1)**t_number1 / (2*t_number1+1))
print(t_answer)
t_number = t_number1 + t_number2
t_number2 = 0
t_list.append(t_answer)
t_final = 4 * (sum(t_list))
return(t_final,t_number+1)
print(taylor(t_precision))
I think the first issue is that your code is difficult to read and therefore difficult to debug. It's always better to use meaningful variable names and to try to minimize declaration of unnecessary ones.
Here is a working implementation of your problem as stated by the title, e.g. calculating pi up to a given precision:
# Pi/4 = 1 - 1/3 + 1/5 - 1/7 + ...
import numpy as np
def taylor(precision):
t_pi, factor, error, order = 0, 0, np.pi, 0
while (error >= precision):
t_pi += 4 * (-1)**factor / (2*factor + 1)
error = abs(np.pi - t_pi)
order += 1
factor += 1
return t_pi, order
taylor(0.2)
>>> (3.3396825396825403, 5)
And this is the corrected version of your code:
def taylor(t_precision):
t_list = []
t_number = 0
t_final = 0
while t_precision <= abs(np.pi - t_final):
t_answer = (-1)**t_number / (2*t_number+1)
print(t_answer)
t_list.append(t_answer)
t_final = 4 * (sum(t_list))
t_number = t_number + 1
return (t_final,t_number)
t_precision = 0.2
taylor(t_precision)
>>> (3.3396825396825403, 5)
The errors were:
The condition of the while loop. You are checking the your final approximation against the difference between the actual value of pi and the desired precision. e.g. if you approximation is 2.6 and the precision 0.1 then the condition is already true, while the error is bigger than the precision required
The return statement is wrongly indented, so the loop exits at the first execution no matter what.

Categories