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

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

Related

change after purchase not giving the right breakdown

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()

How to iterate code and save each output to a list

I'm just learning how to code and I've encountered a problem I can't seem to work around. I've built a strategy for a simple game of chance (similar to the Martingale strategy for those familiar) and I want to run the code n number of times and save the output of each iteration so I can aggregate the results. Note the current 'for' loop is part of my code, I tried using another 'for' loop to run the entire program n times to no avail. Thanks heaps in advance. Apologies if this is a silly question. Here is my code:
import math
import random
import heartrate
heartrate.trace(browser=True)
mult = 1.2
winChance = 0.8250
balance = 259
x = 0
for i in range (0,500):
bet1 = balance/259
balance = balance-bet1
print(balance)
n = random.random()
if n > winChance:
bet2 = (bet1*(1/(mult-1)))+bet1
balance = balance-bet2
n = random.random()
if n > winChance:
bet3 = ((bet1+bet2)*(1/(mult-1)))+bet1
balance = balance-bet3
n = random.random()
if n > winChance:
bet4 = ((bet1+bet2+bet3)*(1/(mult-1)))+bet1
balance = balance-bet4
n = random.random()
if n > winChance:
bet5 = ((bet1+bet2+bet3+bet4)*(1/(mult-1)))+bet1
balance = balance-bet5
print("end")
break
else:
balance = balance = bet4*mult
else:
balance = balance + bet3*mult
else:
balance = balance + bet2*mult
else:
balance = balance + bet1*mult
If I understand the question and code correctly (doubtful), this change would do what you ask for: Running your original code N times (with N = 10):
$ diff -u iterate.py.orig iterate.py
--- iterate.py.orig 2022-03-20 13:02:54.010642003 +0100
+++ iterate.py 2022-03-20 13:17:35.368615800 +0100
## -5,10 +5,12 ##
mult = 1.2
winChance = 0.8250
+end_balances = []
-balance = 259
-x = 0
-for i in range (0,500):
+for _ in range(10):
+ balance = 259
+ x = 0
+ for i in range (0,500):
bet1 = balance/259
balance = balance-bet1
print(balance)
## -35,7 +37,7 ##
break
else:
- balance = balance = bet4*mult
+ balance = balance + bet4*mult
else:
balance = balance + bet3*mult
## -47,3 +49,6 ##
else:
balance = balance + bet1*mult
+ end_balances.append(balance)
+
+print(end_balances)
Here is the full code:
import math
import random
import heartrate
heartrate.trace(browser=True)
mult = 1.2
winChance = 0.8250
end_balances = []
for _ in range(10):
balance = 259
x = 0
for i in range (0,500):
bet1 = balance/259
balance = balance-bet1
print(balance)
n = random.random()
if n > winChance:
bet2 = (bet1*(1/(mult-1)))+bet1
balance = balance-bet2
n = random.random()
if n > winChance:
bet3 = ((bet1+bet2)*(1/(mult-1)))+bet1
balance = balance-bet3
n = random.random()
if n > winChance:
bet4 = ((bet1+bet2+bet3)*(1/(mult-1)))+bet1
balance = balance-bet4
n = random.random()
if n > winChance:
bet5 = ((bet1+bet2+bet3+bet4)*(1/(mult-1)))+bet1
balance = balance-bet5
print("end")
break
else:
balance = balance + bet4*mult
else:
balance = balance + bet3*mult
else:
balance = balance + bet2*mult
else:
balance = balance + bet1*mult
end_balances.append(balance)
print(end_balances)
Note that you normally would extract the inner loop into a separate function.
Edit: Fixed the typo in the innermost else as well.
You can start by creating an empty list such as:
balance_end = []
And then appending the final balance after each iteration (I have fixed the first else which had a typo as well), such as:
else:
balance = balance + bet4*mult
balance_end.append(balance)
else:
balance = balance + bet3*mult
balance_end.append(balance)
else:
balance = balance + bet2*mult
balance_end.append(balance)
else:
balance = balance + bet1*mult
balance_end.append(balance)
Finally, you can safely assume that the balance_end index will match the number of iteration - 1 and the value, is the corresponding value of said iteration.
Here's my attempt to simplify things (to be honest, the code is quite convoluted and difficult to understand):
def bet(win_chance, previous_bets, mult):
if random.random() > win_chance:
this_bet = -1 * ((sum(previous_bets)*(1/(mult-1)))+previous_bets[0])
else:
this_bet = previous_bets[-1]*mult
return this_bet
# initialise variables
mult = 1.2
win_chance = 0.8250
balance = 259
for i in range(500):
previous_bets = []
previous_bets.append(balance/259)
balance -= previous_bets[0]
for i in range(5):
lost = bet(win_chance, previous_bets, mult)
balance += previous_bets[-1]
if not lost:
break
else:
# lost streak after 5 attempts
print('end')
print(balance)
create a list and append balance values to it
import math
import random
import heartrate
heartrate.trace(browser=True)
mult = 1.2
winChance = 0.8250
balance = 259
x = 0
values = list()
for i in range (0,500):
stop = False
bet1 = balance/259
balance = balance-bet1
print(balance)
n = random.random()
if n > winChance:
bet2 = (bet1*(1/(mult-1)))+bet1
balance = balance-bet2
n = random.random()
if n > winChance:
bet3 = ((bet1+bet2)*(1/(mult-1)))+bet1
balance = balance-bet3
n = random.random()
if n > winChance:
bet4 = ((bet1+bet2+bet3)*(1/(mult-1)))+bet1
balance = balance-bet4
n = random.random()
if n > winChance:
bet5 = ((bet1+bet2+bet3+bet4)*(1/(mult-1)))+bet1
balance = balance-bet5
print("end")
stop = True
else:
balance = balance = bet4*mult
else:
balance = balance + bet3*mult
else:
balance = balance + bet2*mult
else:
balance = balance + bet1*mult
values.append(balance)
if stop:
break

Compound Interest calculator has problems in Python

I have been experimenting with creating an investment calculator, and I want to print the annual totals as well as the annual compounded interest. It's doing the annual totals fine, but not the annual interest. My inputs are $10000.00 principle, at 5% interest over 5 years.
start_over = 'true'
while start_over == 'true':
principle = int(input("Type the amount you are investing: "))
rate = float(input("Type interest rate"))
addition = int(input("Type annual Addition"))
time = int(input("Enter number of years to invest"))
real_rate = rate * 0.01
i = 1
print('total', principle * (1 + real_rate))
while i < time:
principle = (principle + addition) * (1 + real_rate)
i = i + 1
print('total', principle)
for i in range(time):
amount = i * (((1 + rate/100.0) ** time)) * principle
ci = amount - principle
i += 1
print("interest = ",ci)
redo_program = input('To restart type y or to quit type any key ')
if redo_program == 'y':
start_over = 'true'
else:
start_over = 'null'
Here are my outputs:
Type the amount you are investing: 10000
Type interest rate5
Type annual Addition0
Enter number of years to invest5
total 10500.0
total 10500.0
total 11025.0
total 11576.25
total 12155.0625
interest = -12155.0625
interest = 3358.21965978516
interest = 18871.50181957032
interest = 34384.78397935548
interest = 49898.06613914064
To restart type y or to quit type any key
Give this a go:
# Calculate year's values based on inputs and the current value of the account
def calc(current, addition, rate, year):
multiplier = 1 + rate/100 # The interest multiplier
new_total = (current + addition) * multiplier # Calculate the total
interest = round((new_total - current - addition), 2) # Interest to nearest penny/cent
return new_total, interest
def main():
# Inputs
principle = int(input("Type the amount you are investing: "))
rate = float(input("Type interest rate: "))
addition = int(input("Type annual Addition: "))
invst_time = int(input("Enter number of years to invest: "))
# Sets current account value to principle
current = principle
# Prints values for each year of investment
for i in range(invst_time):
total, interest_gained = calc(current, addition, rate, i+1)
print("At the end of Year: ", i+1)
print("Total: ", total)
print("Interest: ", interest_gained)
print("------")
current = total # Updates value of account
# Restart Program check
while 1:
repeat_choice = input("Would you like to restart and check with different values? (Y/N)")
if repeat_choice == "Y":
main()
elif repeat_choice == "N":
print("Thanks for using the calculator")
break
else:
print("Enter Y or N!") # Error handler
continue
main()

name is not defined i have already defined the name

PFB the below code I am trying to calculate tax. why do I get the NameError: name 'tax' is not defined.
I have defined tax below still it throws the error tax not defined.
hw = float(input("Please enter total hours worked"))
hp = float(input("Please enter the hourly rate"))
# Pay and OT Calculations
rp = hp * hw
if hw == 40 or hw <40 :
ot = 0
tp = rp + ot
elif hw > 40 and hw <50 :
ot = (hw-40)*(hp*1.5)
tp = rp + ot
elif hw > 50 and hw < 60 :
ot = (hw-40)*(hp*2)
tp = rp + ot
elif hw > 60 or hw == 60 :
ot = (hw-40)*(hp*2.5)
tp = rp + ot
else :
print ("Thanks")
# tax Calculations
if tp == 200 :
tax = float((tp/100)*15)
elif tp > 200 and tp < 300 :
tax = ((tp-200)/100*20) + ((200/100)*15)
elif tp >300 and tp < 400 :
tax = ((tp-300)/100*25) + (((tp-200)-(tp-300))/100*20) + ((200/100)*15)
elif tp >400 and tp == 400 :
tax = ((tp-400)/100*30) + (((tp-200)-(tp-300)-(tp-400))/100*25) + (((tp-200)-(tp-300)/100)*20) + ((200/100)*15)
else :
print ("Thanks")
# Printing Results
print ("Your Salary has been credited")
print ("Regular Pay = ", rp)
print ("Overtime =", ot)
print ("Gross Salary before tax deductions = ", tp)
print ("Income Tax applicable =", tax)
you are using your variables across the entire function but are only defining them in the if/else cases. This adds a lot of room for error of missing a definition somewhere within a case as in
...
if tp == 200 :
tax = float((tp/100)*15)
elif tp > 200 and tp < 300 :
tax = ((tp-200)/100*20) + ((200/100)*15)
elif tp >300 and tp < 400 :
tax = ((tp-300)/100*25) + (((tp-200)-(tp-300))/100*20) + ((200/100)*15)
elif tp >400 and tp == 400 :
tax = ((tp-400)/100*30) + (((tp-200)-(tp-300)-(tp-400))/100*25) + (((tp-200)-(tp-300)/100)*20) + ((200/100)*15)
else :
# NO tax defined here
print ("Thanks")
...
You should define the function-scope variables on the top of your function as:
hw = float(input("Please enter total hours worked"))
hp = float(input("Please enter the hourly rate"))
rp = 0
ot = 0
tp = 0
tax = 0
# Pay and OT Calculations
...
# Printing Results
print ("Your Salary has been credited")
print ("Regular Pay = ", rp)
print ("Overtime =", ot)
print ("Gross Salary before tax deductions = ", tp)
print ("Income Tax applicable =", tax)
By setting these default values you are sure to never miss the variable initialization in your code and you will not need to add extra logic to handle the tax variable in the edge cases where it should not be changed (the else case in your question.

Function not defined, although its been defined... Going Insane

So I am quite new to python and have been working on this assignment for a week now on and off and can't quite get it to run correctly. I am now getting errors that tell me the function get_in_code is not defined although I've defined it. Any help would be greatly appreciated!
SENTINEL = 'XXX'
DAY_CHARGE = 1500.00
#Define get_days
def get_days():
good_data = False
while not good_data:
try:
n_days = int(input("Please enter the number of days you stayed: "))
except ValueError:
print("Error, Bad Data")
else:
if n_days > 0:
good_data = True
else:
print("This is bad data, please re enter data")
return n_days
#define get_cost(p)
def get_cost():
cost = float(input("Please enter the cost for the procedures: "))
while cost < 0:
print("Procedure cost cant be negative: ")
cost = float(input("Please enter the cost for the procedures: "))
return cost
#define med cost
def med_cost():
med_cost = float(input("Enter the cost of your medicine: "))
while med_cost < 0:
print("Medicine cost cant be negative: ")
med_cost = float(input("Enter the cost of your medicine: "))
return med_cost
#Find day cost
def find_day_cost(in_code, n_days):
day_cost = n_days * DAY_CHARGE
if in_code == 'ZH':
p_day_cost = day_cost * 0.20
in_day_cost = day_cost *0.80
elif in_code == 'HH':
p_day_cost = day_cost * 0.10
in_day_cost = day_cost * 0.90
elif in_code == 'CH':
p_day_cost = day_cost * 0.25
in_day_cost = day_cost * 0.75
else:
p_day_cost = day_cost
in_day_cost = 0
return p_day_cost, in_day_cost
#find procedure cost
def find_proc_cost(in_code, cost):
if in_code == 'ZH':
p_proc_cost = 0
in_proc_cost = cost
elif in_code == 'HH':
p_proc_cost = cost * 0.10
in_proc_cost = cost * 0.90
elif in_code == 'CH':
p_proc_cost = cost * 0.50
in_proc_cost = cost * 0.50
else:
p_proc_cost = cost
in_proc_cost = 0
return p_proc_cost, in_proc_cost
#find medicine cost
def find_med_cost(in_code, med_cost):
if in_code == 'ZH':
p_med_cost = 0
in_med_cost = med_cost
elif in_code == 'HH':
p_med_cost = med_cost * 0.10
in_med_cost = med_cost * 0.90
elif in_code == 'CH':
p_med_cost = med_cost * 0.50
in_med_cost = med_cost * 0.50
else:
p_med_cost = med_cost
in_med_cost = 0
return p_med_cost, in_med_cost
#Display pat_info
def display_pat_info(pat_name, in_name):
print("City Hospital - Patient Invoice")
print("Patient Name: ", pat_name)
print("Insurance: ", in_name)
#display day cost
def display_day_cost(p_day_cost, in_day_cost):
print("Patient Day Cost: ", p_day_cost,"\tInsurance Day Cost: ", in_day_cost)
#display procedure cost
def display_proc_cost(p_proc_cost, in_proc_cost):
print("Patient Procedure Cost: ", p_proc_cost, "\tInsurance Procedure Cost: ", in_proc_cost)
#display medicine cost
def display_med_cost(p_med_cost, in_med_cost):
print("Patient Medicine Cost: ", p_med_cost, "\tInsurce Medicine Cost: ", in_med_cost)
#Display totals
def display_totals(total_pat, total_in):
print("Total Billed To Patient: ", total_pat, "\tTotal Billed To Insurance: ", total_in, "\tTotal Bill: ", (total_pat + total_in))
#display day_totals
def display_day_totals(total_zip, total_happy, total_cheap, total_pat):
print("City Hospital - End Of Day Billing Report")
print("Total Dollar Amount Billed Today: ", total_zip+total_happy+total_cheap+total_pat)
print("Total Billed To Zippy Healthcare: ", total_zip)
print("Total Billed To Happy Healthcare: ", total_happy)
print("Total Billed To Cheap Healthcare: ", total_cheap)
print("Total Billed To Uninsured: ", total_pat)
#display day_counts()
def display_day_counts(zip_count, happy_count, cheap_count, no_in_count):
print("The total amount of Zippy Healthcare patients is: ", zip_count)
print("The total amount of Happy Healthcare patients is: ", happy_count)
print("The total amount of Cheap Healthcare patients is: ", cheap_count)
print("The total amount of Uninsured patients is: ", no_in_count)
#def main
def main():
#Counters and accumulators
total_zip= 0.00
total_cheap= 0.00
total_happy= 0.00
total_pat= 0.00
zip_count= 0
cheap_count= 0
happy_count= 0
no_in_count= 0
total_in = 0
#Open file
try:
Pat_File = open('PatientBill.txt', 'w')
except ValueError:
print("*****ERROR***** - Corrupt File")
else:
file_exist = True
#Priming read
pat_name = input("Please enter the patients name: (XXX to stop program)")
#Processing loop
while pat_name != SENTINEL:
#Input data
in_code = get_in_code()
num_days = get_days()
proc_cost = get_cost()
med_cost = med_cost()
#find each cost
pat_day, insure_day = find_day_cost(in_code, num_days)
pat_proc, insure_proc = find_proc_cost(in_code, proc_cost)
pat_med, insure_med = find_med_cost(in_code, med_cost)
#update accumulators and totals
total_pat += pat_day + pat_proc + pat_med
if in_code == 'ZH':
zip_count += 1
total_zip += in_day_cost + in_proc_cost + in_med_cost
in_name = 'Zippy Healthcare'
elif in_code == 'HH':
happy_count += 1
total_happy += in_day_cost + in_proc_cost + in_med_cost
in_name = 'Happy Healthcare'
elif in_code == 'CH':
cheap_count += 1
total_cheap += in_day_cost + in_proc_cost + in_med_cost
in_name = 'Cheap Healthcare'
else:
no_in_count += 1
in_name = 'Uninsured'
total_in = total_zip + total_happy + total_cheap
#displays patients invoice
display_pat_info(pat_name,in_name)
display_day_cost(pat_day, insure_day)
display_proc_cost(pat_proc, insure_proc)
display_med_cost(pat_med, insure_med)
display_totals(pat_day + pat_proc + pat_med, insure_day + insure_proc + insure_med)
#Write output to file
if file_exist:
Pat_File.write(pat_name, pat_day+pat_med+pat_proc )
#Get next patients name
pat_name = input("Please enter the patients name: (XXX to stop program)")
#Close the output file
if file_exist:
Pat_File.close()
#display the accumlators and totals
display_day_totals(total_zip, total_happy, total_cheap, total_pat)
display_day_counts(zip_count,happy_count,cheap_count,no_in_count)
#define get_in_code
def get_in_code():
in_code = input("Please enter one of the insurance codes, ZH, CH, HH, XX")
while in_code not in ('ZH', 'HH', 'CH', 'XX'):
print("***Please enter a proper insurance code***")
in_code = input("Please enter one of the insurance codes, ZH, CH, HH, XX")
return in_code
main()
Python is a interpreted language. You need to define function prior to its usage. Just move a function definitions at the top of a file.
The problem is also with indentation. You're defining your methods inside while, just after a return statement. Actual functions aren't defined at all - interpreter doesn't reach those lines.
Besides, the code is "dirty". Split the code into separate classes/modules. Create well defined areas of responsibility, that would improve the code and it'll be easier to work with it.

Categories

Resources