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.
Related
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()
I am trying to produce a list that is recursively populated taking input from a method variable. (I believe)
My code:
class Register:
cur_unit = [100, 50, 20, 10, 5, 1, .25, .10, .05, .01]
reg_amount = []
def load_reg(self):
self.reg_amount = float(input('Enter amount of money in register...\n'))
def transaction(self):
trans_amount = float(input('Enter the cost of the transaction...\n'))
if trans_amount > self.reg_amount:
print("I'm sorry, but we don't have enough money in the register to allow this transaction...\n")
else:
cash_paid = float(input('Enter how much money you will pay with...\n'))
change_due = cash_paid - trans_amount
new_reg_amount = self.reg_amount - change_due
if new_reg_amount < 0:
print("I'm sorry, but we don't have enough money in the register to allow this transaction...\n")
else:
new_reg_amount = round(new_reg_amount, 2)
change_due = round(change_due, 2)
print('\n' + str(new_reg_amount))
print(change_due)
for i in self.cur_unit:
if change_due - i >= 0:
return [i] + [cash_paid - i]
reg = Register()
reg.load_reg()
res = reg.transaction()
print(res)
Result which produces an undesirable result:
Enter amount of money in register...
200
Enter the cost of the transaction...
24.24
Enter how much money you will pay with...
50
174.24
25.76
[20, 30.0] # undesired result
Process finished with exit code 0
Desired result which would run through cur_unit and bring back each unit if the unit can be subtracted from cash_paid without change_due being equal to or less than 0: (this is for more details needed)
[20, 5, .25, .25, .25, .01]
As Prune pointed out in the comments, this problem is better solved by iteration than with recursion. I wrote methods to do it either way in case you were curious: split_change_r is a recursive function and split_change is a cleaner iterative solution. Note that they assume your cur_unit list is already sorted.
class Register:
cur_unit = [100, 50, 20, 10, 5, 1, .25, .10, .05, .01]
reg_amount = []
def load_reg(self):
self.reg_amount = float(input('Enter amount of money in register...\n'))
def split_change_r(self, amount, l = []):
next_cur = [a for a in self.cur_unit if a <= amount][0]
if next_cur == amount:
return l + [next_cur]
else:
# here is the recursive call
return self.split_change_r(round(amount - next_cur, 2), l + [next_cur])
def split_change(self, amount):
r = []
while(amount != 0):
next_cur = [a for a in self.cur_unit if a <= amount][0]
amount = round(amount - next_cur, 2)
r.append(next_cur)
return r
def transaction(self):
trans_amount = float(input('Enter the cost of the transaction...\n'))
if trans_amount > self.reg_amount:
print("I'm sorry, but we don't have enough money in the register to allow this transaction...\n")
else:
cash_paid = float(input('Enter how much money you will pay with...\n'))
change_due = cash_paid - trans_amount
new_reg_amount = self.reg_amount - change_due
if new_reg_amount < 0:
print("I'm sorry, but we don't have enough money in the register to allow this transaction...\n")
else:
new_reg_amount = round(new_reg_amount, 2)
change_due = round(change_due, 2)
print('\n' + str(new_reg_amount))
print(change_due)
return self.split_change(change_due)
reg = Register()
reg.load_reg()
res = reg.transaction()
print(res)
Example output:
Enter amount of money in register...
200
Enter the cost of the transaction...
24.24
Enter how much money you will pay with...
50
174.24
25.76
[20, 5, 0.25, 0.25, 0.25, 0.01]
class creditCard:
def __init__(self, limit, apr, balance):
self.limit = limit
self.apr = apr
self.balance = balance
self.charges = {}
self.payments = {}
def charge(self, amount, day):
# Charges the card, and stores the charge and day the charge was made in a dictionary.
# Returns false if the amount charged is greater than the limit.
if amount > self.limit - self.balance:
return False
self.charges[day] = amount
self.balance += amount
def payment(self, amount, day):
# When a payment is made the payment is stored in the payments dictionary with the corresponding day.
# Returns false is the payment amount is greater than the balance owed/limit.
if amount > self.limit - self.balance:
return False
self.payments[day] = amount
self.balance -= amount
def interest(self, balance):
# calculates and returns interest
return (balance * self.apr) / 365
def days_balance(self, balance_day):
balance_to_date = 0
months_interest = 0
for day in range(1, balance_day+1):
balance_to_date += self.charges.get(day, 0)
balance_to_date -= self.payments.get(day, 0)
months_interest += self.interest(balance_to_date)
if day % 30 == 0:
balance_to_date += months_interest
months_interest = 0
balance_to_date = round(balance_to_date, 2)
return "${}".format(balance_to_date)
I am supposed to be returning 411.99 for my second test case and I am getting 411.89 due to the dictionary not applying the interest for the first day. I can not figure out why it is doing that what so ever. Any help would be greatly appreciated. Below is my test case.
customer opens a credit card with 1k limit and 35% APR
customer charges $500 on opening day
15 days after opening he pays $200 (balance now 300)
25 days after opening he charges another $100 (balance now 400)
total balance at the end of the month is 411.99
customer1 = creditCard(1000, 0.35, 0)
customer1.charge(500, 1)
print(customer1.days_balance(30))
for i in customer1.charges:
print(customer1.charges.keys(), customer1.charges.values())
customer2 = creditCard(1000, 0.35, 0)
customer2.charge(500, 1)
customer2.payment(200, 15)
customer2.charge(100, 25)
print("Customers Balance on Day 26: " + customer2.days_balance(26))
print("Customers Balance on Day 30 with Interest: " +
customer2.days_balance(30))
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
I am trying to make a simple calculator for working out the tax due on a salary. Please see the code below:
I keep getting this error and I don't know what is wrong, please help :) thanks!
Traceback (most recent call last):
File "python", line 13
elif salary > 11000 and salary < 43000:
^
SyntaxError: invalid syntax
CODE:
salary = raw_input ("What is your salary?")
print "So your gross annual salary is %r GBP" % (salary)
print "\nNow we need to calculate what your net salary is."
def taxes(salary):
salary >= 0
while true:
if salary < 11000:
tax = 0
elif salary > 11000 and salary < 43000:
tax = (0.2 * income) - 2200
elif salary > 43000 and salary < 150000:
tax = (0.4 * (salary - 43000)) + 6400
elif salary > 150000:
tax = ((salary - 150000) * 0.45) + 6400 + 42800
return tax
Steps to correct your code
step1 : the salary data type should be of int, to correct..use the following code
step 2: Indentation is compulsory in python, so indent your code very well
step 3: Add an else statement after the conditional statements
step 4: indent return statement
change your code to this one
salary = int(raw_input ("What is your salary?"))
print "So your gross annual salary is %r GBP" % (salary)
print "\nNow we need to calculate what your net salary is."
def taxes(salary):
salary >= 0
while true:
if salary < 11000:
tax = 0
elif salary > 11000 and salary < 43000:
tax = (0.2 * income) - 2200
elif salary > 43000 and salary < 150000:
tax = (0.4 * (salary - 43000)) + 6400
elif salary > 150000:
tax = ((salary - 150000) * 0.45) + 6400 + 42800
else :
tax = undefined
return tax
It felt like there was a better way of doing this, so I came up with an alternative route:
tax_bands = [11000, 43000, 150000]
tax_amts = [0.2, 0.4, 0.45]
salary = 43001
Placing the thresholds and amounts into a list means that you can change them more easily if you need to.
The function below creates a list of the tax calculations, tax_list, and then a separate list of the maximum tax liability in each band called max_tax (the upper band has no maximum).
It then compares the values in the lists, and overwrites the tax_list if the corresponding value is larger than the maximum.
Then it calculates the sum of all values in tax_list greater than zero and returns it.
def taxes(salary, tax_bands, tax_amts):
tax_list = [(pct * (salary - band)) for (band, pct) in zip(tax_bands, tax_amts)]
max_tax = []
for index, sal in enumerate(tax_bands[:-1]):
max_tax.append(tax_bands[index + 1] - sal)
max_tax = [segment * tax for segment, tax in zip(max_tax, tax_amts[:-1])]
for index, value in enumerate(tax_list):
try:
if value > max_tax[index]:
tax_list[index] = max_tax[index]
except:
pass
tax_to_pay = sum([x for x in tax_list if x > 0])
return tax_to_pay
print taxes(salary, tax_bands, tax_amts)
salary = input ("What is your salary?")
print "So your gross annual salary is %r GBP" % (salary)
print "\nYour net annual salary is: {} GBP".format(salary - taxes(salary, tax_bands, tax_amts))
To be super safe, you could also have the first line in the function call int(salary) using a try except just to check that it's the right type and that someone hasn't entered 43,000.
That because there are indent error in line number 12, now you can just copy pust this :
note : salary > 11000 and salary < 43000 equivalent to 11000 < salary < 43000 in python:
salary = raw_input ("What is your salary?")
print "So your gross annual salary is %r GBP" % (salary)
print "\nNow we need to calculate what your net salary is."
def taxes(salary):
while true:
if salary < 11000:
tax = 0
elif 11000 < salary < 43000:
tax = (0.2 * income) - 2200
elif salary > 43000 and salary < 150000:
tax = (0.4 * (salary - 43000)) + 6400
elif salary > 150000:
tax = ((salary - 150000) * 0.45) + 6400 + 42800
return tax
As the comments have already stated, your indentation is incorrect. See below:
def taxes(salary):
salary >= 0
tax = 0
if salary < 11000:
tax = 0
elif salary > 11000 and salary < 43000:
tax = (0.2 * income) - 2200
elif salary > 43000 and salary < 150000:
tax = (0.4 * (salary - 43000)) + 6400
elif salary > 150000:
tax = ((salary - 150000) * 0.45) + 6400 + 42800
print("Value of tax is: " + str(tax))
return tax
salary = raw_input ("What is your salary?")
print "So your gross annual salary is %r GBP" % (salary)
print "\nNow we need to calculate what your net salary is."
print("\nHere is your net salary after taxes: %r" % (taxes(int(salary))))
With python, indentations are how you tell the interpreter which blocks of code fall where (unlike with Java for example with semicolons being the end of line delimiter). By not indenting properly on your elif statements, you are essentially telling the program there is an elif without an if hence your syntax problem.