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

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.

Related

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.

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

i want to add a simple Y or N loop to my python code

So here is my code ive tried so many loop options and just cant seem to get it to loop the whole thing when any help would be apreciated
# Displays the Program Header
print('----------------------------------------------------------------------')
print('The Innovation University of Australia (IUA) Grade System')
print('----------------------------------------------------------------------')
# These print commands display the spaces to divide the sections
print()
# Asks the lecturer to input all marks out of 100
print('Please enter all marks out of 100.')
#Asks to input stydents ID and name
#Asks the to input the marks for Assignment 1 and Assignment 2
# and the Final Exam and stores them as floats
studentID = input('Please enter the student ID: ')
studentname = input('Please enter the student name: ')
assignment1 = float(input('Please enter the marks for Assignment 1: '))
assignment2 = float(input('Please enter the marks for Assignment 2: '))
final_exam = float(input('Please enter the marks for the Final Exam: '))
print()
# Displays the Thank You! message
print('Thank You!')
print()
# Calculates the weighted mark for Assignment 1, Assignment 2, and the
# total weighted mark of the Assignments by mutiplying by 20% and 30%
weighted_assignment1 = 0.2 * assignment1
weighted_assignment2 = 0.3 * assignment2
total_weighted_assignments = weighted_assignment1 + weighted_assignment2
# Displays the weighted mark for Assignment 1, Assignment 2, and the total
# weighted mark of the Assignments
print('Weighted mark for Assignment 1:', int(weighted_assignment1))
print('Weighted mark for Assignment 2:', int(weighted_assignment2))
print('Total weighted mark of the assignements:', int(total_weighted_assignments))
print()
# Calculates the weighted mark for the Final Exam and the total weighted
# mark for the subject
weighted_final_exam = 0.5 * final_exam
total_weighted_subject = total_weighted_assignments + weighted_final_exam
# Displays the weighted mark of the Final Exam and the total weighted mark
# for the subject
print('Weighted mark for Final Exam is:', int(weighted_final_exam))
weightedtotal = print('Total weighted mark for the subject:', int(total_weighted_subject))
print()
# Calculates the bonus mark for the subject depending on how high the
# total mark is
if total_weighted_subject > 50 and total_weighted_subject <= 70:
bonus_mark = (total_weighted_subject - 50) * 0.1
elif total_weighted_subject > 70 and total_weighted_subject <= 90:
bonus_mark = (total_weighted_subject - 70) * 0.15 + 2
elif total_weighted_subject > 90 and total_weighted_subject <= 100:
bonus_mark = (total_weighted_subject - 90) * 0.20 + 5
else:
bonus_mark = 0
# Displays the bonus mark for the subject
print('Bonus mark:', format(bonus_mark, '.1f'))
# Calculates the total mark for the subject with the bonus mark
total_with_bonus = total_weighted_subject + bonus_mark
# Check if total mark with bonus is greater than maximum
# possible mark of 100 and if it is set to 100 and display
# total mark with bonus
if total_with_bonus > 100:
total_with_bonus = 100
print('Total mark with bonus:', format(total_with_bonus, '.1f'))
else:
print('Total mark with bonus:', format(total_with_bonus, '.1f'))
print()
outFile = open("TestFile.txt", "w")
outFile.write("student \t student \t A1 \t A2 \t final \t weighted \t weighted total\n" )
outFile.write("id \t name \t \t exam \t total \t with bonus\n")
outFile.write("-----------------------------------------------------------------------------------------------\n")
outFile.close()
content = str(studentID) + "\t" "\t" + str(studentname) + "\t" + str(assignment1) + "\t" + str(assignment2) + "\t" + str(final_exam) + "\t" + str(weightedtotal)
outFile = open("TestFile.txt", "a")
outFile.write(content)
outFile.close()
#Displays Goodbye. message
print('Goodbye.')
How about something like this pattern:
while True:
# Your code here
if enter_more_data == 'N':
break

Python Repetition Structures and Files

I have a question about my python program . I have trouble finding the total and ntotal in this program. Rest works fine. Is there any way i can fix this? I have this program due soon. I'd appreciate any tips I can get :D Thanks
midSalary = 50000
maxSalary = 60000
def main():
inFile = open('program7.txt', 'r')
lineRead = inFile.readline()
total = 0.0
ntotal = 0.0
count = 0
while lineRead != '':
words = lineRead.split()
for word in words:
num = float(word)
total += num
count += 1
print("\nFaculty Member # ",count, ": $" , format(num, '.2f'), sep ="")
if num >= maxSalary:
payIncrease(num, .04)
elif num >= midSalary:
payIncrease(num, .07)
else:
payIncrease(num , .055)
lineRead = inFile.readline()
#averagePayRaise = (ntotal - total) / count
inFile.close()
for divider in range(45):
print("-", end ='')
print("\nTotal Faculty payroll : $", format(total , ",.2f"),sep ="")
print("The New Total Faculty payroll : $", format(ntotal , ",.2f"),sep ="")
print("Average Pay Raise : $", format(averagePayRaise, ",.2f"), sep ="")
def payIncrease(amount, prcnt):
print("Pay Raise Percent : ", format(prcnt*100, ".1f")+"%")
total = 0.0
ntotal = 0.0
count = 0
salRaise = amount * prcnt
newSal = amount + salRaise
print("Pay Raise : $", format(salRaise, ',.2f'), sep ="")
print("New Salary : $", format(newSal, ',.2f'), sep = "")
total += amount
count += 1
ntotal += newSal
averagePayRaise = (ntotal - total) / count
main()
By default, names that you assign to in Python are local to the function in which they are declared. So, if you have:
def main():
total = 0
def payIncrease():
total = 0
total += amount
then you have two independent values named total. One way to solve this is to make it global:
total = 0
def main():
global total
total = 0
def payIncrease():
global total
total += amount
Note that you don't want to assign total = 0 inside payIncrease(), because that would reset your running total to 0. You probably added that when you broke out your code into the payIncrease() function because Python gave you an error without that.
def payIncrease(salary):
if current_sal >= maxSalary: return 0.04
if current_sal >= midSalary: return 0.07
return 0.055
def processSalaryData(line):
"""take a line and return current salary and new salary (note that a line is actually just a float)"""
try:
current_sal = float(line)
except ValueError:
return None
return current_sal,current_sal + current_sal*payIncrease(current_sal)
def main():
salaryData = [processSalaryData(line) for line in open("salaries.txt")]
salaryData = filter(None,salaryData) #filter out invalid data
adjustments = [b-a for a,b in salaryData]
old_salaries,new_salaries = zip(*salaryData)
print "OLD TOTAL PAYROLL :",sum(old_salaries)
print "NEW TOTAL PAYROLL :",sum(new_salaries)
print "AVG ADJUSTMENT:",sum(adjustments)/len(adjustments)
print "MAX SALARY:",max(new_salaries)
print "MIN SALARY:",min(new_salaries)

Categories

Resources