change after purchase not giving the right breakdown - python

def main():
money1 = input("Purchase price: ")
money2 = input("Paid amount of money: ")
price = int(money1)
paid = int(money2)
change = paid - price
ten_euro = change // 10
five_euro = change % 10 // 5
two_euro = change % 5 // 2
one_euro = (change % 2)
if price < paid:
print("Offer change:")
if change >= 10:
print(ten_euro, "ten-euro notes")
if (change % 10) >= 5:
print(five_euro, "five-euro notes")
if (change % 5) >= 2:
print(two_euro, "two-euro coins")
if (change % 2) >= 2:
print(one_euro, "one-euro coins")
else:
print("No change")
if __name__ == "__main__":
main()
Create a program that asks how much purchases cost and the amount of paid money and then prints the amount of change. Simplify the program by only allowing the use of sums of 1, 2, 5, and 10 euros. Ensure that the total price is always in full euros.
My problem is with the one-euro coins, as it is not showing as expected.
Examples of how the program should work:
Purchase price: 12
Paid amount of money: 50
Offer change:
3 ten-euro notes
1 five-euro notes
1 two-euro coins
1 one-euro coins
Purchase price: 9
Paid amount of money: 20
Offer change:
1 ten-euro notes
1 one-euro coins

This line is incorrect: if (change % 2) >= 2.
This can never be true. You probably meant: if (change % 2) >= 1.
Apart from that I think you could simplify the program by decrementing the change variable as you calculate the different denominations. You can use the builtin method divmod for this.
You can also check if the ten_euro, five_euro, etc are greater than zero in the printout rather than re-calculating their amount.
ten_euro, change = divmod(change, 10)
five_euro, change = divmod(change, 5)
two_euro, change = divmod(change, 2)
one_euro = change
if price < paid:
print("Offer change:")
if ten_euro:
print(ten_euro, "ten-euro notes")
if five_euro:
print(five_euro, "five-euro notes")
if two_euro:
print(two_euro, "two-euro coins")
if one_euro:
print(one_euro, "one-euro coins")
else:
print("No change")

We got to calculate # one_euro count better and you are there.
Here is a working solution, included a check on the total change aswell.
def main():
money1 = input("Purchase price: ")
money2 = input("Paid amount of money: ")
price = int(money1)
paid = int(money2)
change = paid - price
ten_euro_count = change // 10
five_euro_count = change % 10 // 5
two_euro_count = change % 5 // 2
sum_of_change = 0
if price < paid:
print("Offer change:")
if change >= 10:
print(ten_euro_count, "ten-euro notes")
sum_of_change = sum_of_change + ten_euro_count * 10
if (change % 10) >= 5:
print(five_euro_count, "five-euro notes")
sum_of_change = sum_of_change + five_euro_count * 5
if (change % 5) >= 2:
print(two_euro_count, "two-euro coins")
sum_of_change = sum_of_change + two_euro_count * 2
if change - sum_of_change != 0:
one_euro_count = 1
print(one_euro_count, "one-euro coins")
else:
print("No change")
if __name__ == "__main__":
main()

Faulty decision structure;
if (change % 2) >= 2
Code change;
def main():
money1 = int(input("Purchase price: "))
money2 = int(input("Paid amount of money: "))
change = money2 - money1
ten_euro = change // 10
five_euro = (change % 10) // 5
two_euro = (change % 5) // 2
total = 0
if money1 < money2:
print("Offer change:")
if change >= 10:
print(ten_euro, "ten-euro notes")
total += ten_euro*10
if (change % 10) >= 5:
print(five_euro, "five-euro notes")
total += five_euro*5
if (change % 5) >= 2:
print(two_euro, "two-euro coins")
total += two_euro*2
if change - total > 0:
print(change-total, "one-euro coins")
else:
print("No change")
if __name__ == "__main__":
main()

Related

How to add a surcharge to fine calculator in Python?

I am trying to create a fine amount calculator, but I don't know how to add a surcharge to the calculations.
For each fine amount in the code, I need to add a victims surcharge that varies depending on fine amount. If the fine amount is between $0 and $99 surcharge is $40, between $100 and $200 surcharge is $50, $201 and $350 surcharge is $60, $351 and $500 surcharge is $80, and over $500 surcharge is 40%.
Any suggestions for the best way to implement this into my current code?
thank you!
def ask_limit():
limit = float(input ("What was the speed limit? "))
return limit
def ask_speed():
speed = float(input ("What was your clocked speed? "))
return speed
def findfine(speed, limit):
if speed > 35 + limit :
over35fine = ((speed - limit) * 8 + 170)
print("Total fine amount is:", over35fine)
elif speed > 30 + limit :
over30fine = ((speed - limit) * 4 + 100)
print("Total fine amount is:", over30fine)
elif speed > limit :
normalfine = ((speed - limit) * 2 + 100)
print("Total fine amount is:", normalfine)
elif speed <= limit:
print("No fine, vehicle did not exceed allowed speed limit.")
def main():
limit = ask_limit()
speed = ask_speed()
findfine(speed, limit)
main()
You can add a function to do that based on the fine value:
def ask_limit():
limit = float(input ("What was the speed limit? "))
return limit
def ask_speed():
speed = float(input ("What was your clocked speed? "))
return speed
def findfine(speed, limit):
if speed > 35 + limit :
return ((speed - limit) * 8 + 170)
elif speed > 30 + limit :
return ((speed - limit) * 4 + 100)
elif speed > limit :
return ((speed - limit) * 2 + 100)
elif speed <= limit:
0
def findSurcharge(fine):
if fine < 100:
return 40
elif fine < 200:
return 50
elif fine < 350:
return 60
elif fine < 500:
return 80
elif fine > 500:
return fine * 0.4
else:
return 0
def main():
limit = ask_limit()
speed = ask_speed()
fineAmount = findfine(speed, limit)
surcharge = findSurcharge(fineAmount)
print(f"fine: {fineAmount}, surcharge: {surcharge}")
main()
now you can print your message in the main function based on the surcharge and fine amount.
Note: adjust the if-elses in the findSurcharge function if they are not correct.

TypeError: check_location() missing 1 required positional argument: 'totalprices' in line 33, in <module>

What I am trying to do is calling in second method (return type from first method - variable which is totalprices). I am not sure if I am calling it right way. Any input would be appreciated. Thanks in advance:
class funda():
def __init__(self, house_type_list):
self.house_type_list = house_type_list
def total_buy_price(self):
totalprices = 0
homeprice = self.house_type_list[0]
maintance = self.house_type_list[1]
if homeprice < 20000 and maintance <= 150:
totalprices = homeprice + maintance
print("home is in budget and home price total is %s in euro " % totalprices)
else:
if homeprice >= 20000 and maintance == 100:
totalprices = homeprice + maintance
print("not in budget as price is high %s" % totalprices)
return totalprices
def check_location(self, totalprices):
self.total_buy_price()
parent_totalprice = totalprices
print("to check if value is coming correct " +str(parent_totalprice))
location = self.house_type_list[2]
if location == 'haarlem' and parent_totalprice <= 20000:
print("% location is best for rent and budget " %location)
else:
print("Not in budget")
house_type_list1 = [10000, 100, "Uithoorn"]
house_type_instance = funda(house_type_list1)
house_type_instance.total_buy_price()
house_type_instance.check_location()
print('\n')
house_type_list2 = [22000, 200, "Amsterdam"]
house_type_instance2 = funda(house_type_list2)
house_type_instance2.total_buy_price()
house_type_instance2.check_location()

Loop to add more input

I have 3 more cars that I have but I need to know how to loop things like the car input so it will allow you to input it again if you do the wrong input same thing with the extras so they have to be either 1 or 0.
print("===================================================")
print("==============Car Finance Calculations=============")
print(" Choose your veicle: ")
print(" SUV type 1 ")
print(" Hatch type 2 ")
print(" Sedan type 3 ")
print("===================================================")
caaaaaaaar = int(input(" Please enter Which car you want to finance: "))
years = int(input(" enter years of loan either 3 or 4 or 5 Years: "))
if caaaaaaaar == 1:
carsvalue = int(input("Please enter you cars value: "))
residual = carsvalue * 0.30
financing = carsvalue - residual
print(" financing value for the car is: ", round(financing,2))
print(" Intrest rate is 9% ")
n = years * 12
r = 9 / (100 * 12)
Financingcost = financing * ((r*((r+1)**n))/(((r+1)**n)-1))
print(" Your Montly financing rate is: ", round(Financingcost,2))
print("================================================================================")
print("Please Choose extras: ")
print("======================================================")
print(" If you would like fuel type 1 if not type 0")
print(" If you would like insurance type 1 if not type 0")
print(" if you would like Maintenance type 1 if not type 0")
print("======================================================")
if caaaaaaaar == 1:
x, y, z = [int(x) for x in input("Enter Your extras with spaces:").split()]
print("=======================================")
if x == 1:
print("Yes you want fuel")
fuelcost = 80 * 4.33
print("fuel cost is", round(fuelcost,2))
if x == 0:
print("you dont want fuel as an extra")
fuelcost = 0
print("Fuel cost is: ", fuelcost)
print("=======================================")
if y == 1:
print("yes you want insurance")
insurancecost = (1200 / 12)
print("Insurance cost is: ", round(insurancecost,2))
if y ==0:
print("you dont want insurance")
insurancecost = 0
print("insurance cost is: ",insurancecost)
print("=======================================")
if z == 1:
print("yes you want maintenance")
maintenancecost = (100 * 1)
print("Maintenance cost is: ", round(maintenancecost,2))
if z == 0:
print("you dont want maintenance")
maintenancecost = 0
print("maintenance cost is: ",maintenancecost)
print("=======================================")
total_cost_for_extras = fuelcost + maintenancecost + insurancecost
print("Total cost for the selected extras is: ", round(total_cost_for_extras,2))
TOTALFOREVERYTHING = total_cost_for_extras + Financingcost
print("Total monthly financing rate is: ", round(TOTALFOREVERYTHING,2))
You want to use a while loop.
Like this:
carsEntered = 0
while (carsEntered <= 4):
caaaaaaaar = int(input(" Please enter Which car you want to finance: "))
years = int(input(" enter years of loan either 3 or 4 or 5 Years: "))
carsEntered += 1
You could also use a for loop instead but that depends on what you want to do.
As per my understanding of the question you want to run an iteration until the user gives the right answer.
In that case, you can use flag variable in while.
flag = False
while(flag is False):
if(condition_statisfied):
flag = True
I suggest that you put your vehicle types in a dictionary:
vehicle_type_dict = {
1: "SUV type",
2: "Hatch type",
3: "Sedan type"
}
and do a while-loop to check if your input is in the dictionary:
while True:
caaaaaaaar = int(input(" Please enter Which car you want to finance: "))
if caaaaaaaar not in vehicle_type_dict:
continue #loop again if input not in the dictionary
#read next line of code if input is in the dictionary
#do something below if input is correct
years = int(input(" enter years of loan either 3 or 4 or 5 Years: "))
break #end loop
My recommendation is to take a functional approach to this problem. You are calling int(input()) multiple times and want to validate the user input before proceeding on to the next lines each time. You can do this in a function that will continue to loop until the input is confirmed as valid. Once the input is validated, you can exit the function's frame by returning the value using the return key word.
# This is the function definition.
# The code in this function does not execute until the function is called.
def prompt_int(
text,
minimum=0,
maximum=1,
error="The value you entered is not valid try again."
):
# when the function is called it will start a second while loop that will keep looping
# until valid input is entered
while True:
try:
val = int(input(text))
if minimum <= val <= maximum:
return val
raise ValueError
except ValueError:
print(error)
# This is the outer while loop. It will keep looping forever if the user so chooses.
while True:
# instead of calling print() a bunch one option is to assign a docstring to a variable
car_prompt = '''
===================================================
==============Car Finance Calculations=============
Choose your veicle:
SUV: 1
Hatch: 2
Sedan: 3
===================================================
Please enter the number for the car you want to finance or 0 to exit:\n
'''
# This is where we first call the function.
# Our docstring will be passed into the function to be used as a prompt.
# We also pass in some args for maximum and minimum params
caaaaaaaar = prompt_int(car_prompt, 0, 3)
# 0 is false so we can exit the while loop if the user enters 0
if not caaaaaaaar:
break
year_prompt = "Enter years of the car loan (3, 4 or 5):\n"
years = prompt_int(year_prompt, 3, 5)
if caaaaaaaar == 1:
val_prompt = "Please enter you cars value:\n"
carsvalue = prompt_int(val_prompt, 0, 2147483647)
residual = carsvalue * 0.30
financing = carsvalue - residual
print("Financing value for the car is: ", round(financing, 2))
print("Intrest rate is 9% ")
n = years * 12
r = 9 / (100 * 12)
Financingcost = financing * ((r * ((r + 1) ** n)) / (((r + 1) ** n) - 1))
print(" Your Montly financing rate is: ", round(Financingcost, 2))
print("================================================================================")
print("Please Choose extras: ")
print("======================================================")
x = prompt_int("If you would like fuel type 1 else type 0:\n")
y = prompt_int("If you would like insurance type 1 else type 0:\n")
z = prompt_int("If you would like Maintenance type 1 else type 0:\n")
print("======================================================")
if x == 1:
print("Yes you want fuel")
fuelcost = 80 * 4.33
print("fuel cost is", round(fuelcost, 2))
else:
print("you dont want fuel as an extra")
fuelcost = 0
print("Fuel cost is: ", fuelcost)
print("=======================================")
if y == 1:
print("yes you want insurance")
insurancecost = (1200 / 12)
print("Insurance cost is: ", round(insurancecost, 2))
else:
print("you dont want insurance")
insurancecost = 0
print("insurance cost is: ", insurancecost)
print("=======================================")
if z == 1:
print("yes you want maintenance")
maintenancecost = (100 * 1)
print("Maintenance cost is: ", round(maintenancecost, 2))
else:
print("you dont want maintenance")
maintenancecost = 0
print("maintenance cost is: ", maintenancecost)
print("=======================================")
total_cost_for_extras = fuelcost + maintenancecost + insurancecost
print("Total cost for the selected extras is: ", round(total_cost_for_extras, 2))
TOTALFOREVERYTHING = total_cost_for_extras + Financingcost
print("Total monthly financing rate is: ", round(TOTALFOREVERYTHING, 2))
elif caaaaaaaar == 2:
# Put your code for car 2 in this block.
# If it is like car 1 code except the value of a few variables
# then make another func
pass
else:
# Car 3 code...
pass

questions repeated 4x, float not callable, error on code

I dont understand why the code doesnt work and they have repeated the questions to me 4 times. and say that float is not callable. i have tried doing this for quite awhile but i dont seem to get anything at all. is there any easier way for python3? I just learnt this language 2 weeks ago. its not a whole new world to me but many of the things i am not familiar with. such as indentation
def get_taxi_info():
flag_down = float(input("What's the flag-down fare: $"))
within = float(input("What's the rate per 400 meters within 9.8km? $"))
beyond = float(input("What's the rate per 350 meters beyond 9.8km? $"))
distance = float(input("What's the distance traveled (in meters)? "))
peak = input("Is the ride during a peak period? [yes/no]")
mid6 = input("Is the ride between midnight and 6am? [yes/no]")
location = input("Is there any location surcharge? [yes/no]")
surloca = float(input("What's the amount of location surcharge?"))
return (flag_down, within, beyond, distance, peak == 'yes', mid6 == 'yes', location == 'yes', surloca)
def calculate_taxi_fare():
dist = get_taxi_info()
if dist[3] > 9800:
extra = (dist[3] - 9800) % 350
if extra == 0:
a = (extra//350) + 22
else:
a = (extra//350) + 23
return a
elif dist[3] <= 9800:
extra = (dist[3] - 1000) % 400
if extra == 0:
a = (extra//400)
else:
a = (extra//400) + 1
return a
def peakornot():
peak = get_taxi_info()
if peak[4] == True and peak[5] == False:
surcharge = 1.25
return surcharge
elif peak[4] == False and peak[5] == True:
surcharge = 1.50
return surcharge
taxifare = calculate_taxi_fare()
info = get_taxi_info()
peak1 = peakornot()
taxifare = calculate_taxi_fare()
if info[6] == True:
payable = ((info[0] + (info[1] * taxifare()) + (info[2] * taxifare())) * peak1[0]) + info[7]
print ("The total fare is $" + str(payable))
elif info[6] == False:
payable = ((info[0] + (info[1] * taxifare()) + (info[2] * taxifare())) * peak1[0]) + info[7]
print ("The total fare is $" + str(payable))
The function calculate_taxi_fare returns a float, so on this line taxifare is a float
taxifare = calculate_taxi_fare()
Therefore you cannot say taxifare() because it looks like a function call, so you can just use for example
info[1] * taxifare

MIT opencourseware - stuck on a basic issue, credit card minimum payment over a year calculation

Basically I'm pretty stuck on this issue, I've linked the question below, it's part 'b' I'm stuck on, or the second question in the document:
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00sc-introduction-to-computer-science-and-programming-spring-2011/unit-1/lecture-4-machine-interpretation-of-a-program/MIT6_00SCS11_ps1.pdf
If I'm honest it's just got to the point where I'm totally confused! I've put my code below:
balance = float(raw_input('Vot is the outstanding balance? '))
InrAn = float(raw_input('Vot is the annual interest rate as a decimal? '))
month = 1
monthPay = 10
monthInr = InrAn/12.0
newBalance = balance
while balance > 0:
newBalance = newBalance * (1 + monthInr) - monthPay
month +=1
if month > 12:
month = 1
newBalance = balance
monthPay += 10
This does essentially nothing, I know, and it's not yet complete. If I add a 'print month' statement it just seems to show that the code just goes up to 12, then starts at 1 again. Any tips/prods in the right direction?
monthly_payment = 10.0
while True:
current_balance = start_balance
for month in range(1, 13):
current_balance = current_balance * (1. + monthly_rate) - monthly_payment
current_balance = round(current_balance, 2)
if current_balance <= 0.0:
break
if current_balance <= 0.0:
print("RESULT")
print("Monthly payment to pay off debt in 1 year: {}".format(int(monthly_payment)))
print("Number of months needed: {}".format(month))
print("Balance: {:0.2f}".format(current_balance))
break
monthly_payment += 10.0

Categories

Resources