Python function/argument 'not defined' error - python

I'm very new to coding, and am working on an assignment in Python 3.5.2 and am getting a 'display_results not defined' error. Am I placing it in the wrong section?
Thanks in advance.
hourly_pay_rate = 7.50
commission_rate = 0.05
withholding_rate = 0.25
def startup_message():
print('''This program calculates the salesperson's pay.
Five values are displayed.
Hourly pay, commission, gross pay, withholding, and net pay.\n''')
def main():
startup_message()
name = input('Enter name: ')
sales_amount = float(input('Enter sales amount: '))
hours_worked = float(input('Enter hours worked: '))
hourly_pay_amount = hours_worked * hourly_pay_rate
commission_amount = sales_amount * commission_rate
gross_pay = hourly_pay_rate + commission_rate
withholding = gross_pay * withholding_rate
net_pay = gross_pay - withholding
display_results#<-----'not defined' error for calculations
def display_results(): #(parameters)
print('Hourly pay amount is: ', \
format(hourly_pay_amount, ',.2f'))
print('Commission amount is: ', \
format(commission_amount, ',.2f'))
print('Gross pay is: ', \
format(gross_pay, ',.2f'))
print('Withholding amount is: ', \
format(withholding, ',.2f'))
print('Net pay is: ', \
format(net_pay, ',.2f'))
main()
input('\nPress ENTER to continue...')

First, to call display_results, you need to provide an empty set of parentheses:
display_results()
It appears you have an indentation error as well, as it seems you intended to call display_results() from inside the call to main:
def main():
startup_message()
# ...
net_pay = gross_pay - withholding
display_results()
Without the indentation, you were attempting to access the name display_results immediately after defining main, but before you actually defined display_results.

Look at this very short program:
def main():
r = 2 + 2
show_result
def show_result():
print("The result of 2+2 is {}", format(r))
main()
This program will not work!! However, if you can fix all the bugs in this program you will have understood how to fix most of the problems in your longer example.
Here is an annotated solution:
def main():
r = 2 + 2
show_result(r) # Must indent. Include brackets and pass the
# variable
def show_result(r): # Include a parameter list.
print("The result of 2+2 is: {}".format(r)) # format is a string method
main()
You need to indent and pass parameters to display_results and use the correct syntax for format strings. In your case something like:
print('Hourly pay amount is: {.2f}'.format(hourly_pay_amount))

Your display_result is unindented. Correct the indentation and it should work
def main():
startup_message()
name = input('Enter name: ')
sales_amount = float(input('Enter sales amount: '))
hours_worked = float(input('Enter hours worked: '))
hourly_pay_amount = hours_worked * hourly_pay_rate
commission_amount = sales_amount * commission_rate
gross_pay = hourly_pay_rate + commission_rate
withholding = gross_pay * withholding_rate
net_pay = gross_pay - withholding
display_results()#<-----'not defined' error for calculations

Indent and execute () the function.
def main():
startup_message()
name = input('Enter name: ')
sales_amount = float(input('Enter sales amount: '))
hours_worked = float(input('Enter hours worked: '))
hourly_pay_amount = hours_worked * hourly_pay_rate
commission_amount = sales_amount * commission_rate
gross_pay = hourly_pay_rate + commission_rate
withholding = gross_pay * withholding_rate
net_pay = gross_pay - withholding
display_results() #<-----'not defined' error for calculations

Related

NameError: name 'product_name' is not defined, but I defined it?

this is my code:
def get_input():
product_name = input('Enter the name of a product: ')
price_product = float(input('Enter the current price of the product: ')) #five
price_one_year_ago = float(input('Enter the price of the product from one year ago: '))
price_two_years_ago = float(input('Enter the price of the product two years ago: '))
results(product_name, price_product, price_one_year_ago, price_two_years_ago)
for i in range(0,5):
get_input()
results(product_name, price_product, price_one_year_ago, price_two_years_ago)
print('Product 1 year ago to current Two years ago to current Change')
output_results()
def results(product_name, price_product, price_one_year_ago, price_two_years_ago):
inflation_one_year = ((price_product - price_one_year_ago)/price_one_year_ago* 100)
inflation_two_years = ((price_product - price_two_years_ago)/price_one_year_ago * 100)
if inflation_one_year > inflation_two_years:
change = 'decrease'
else:
change = 'increase'
results = product_name + ' ' + str(inflation_one_year) + ' ' + str(inflation_two_years)+ ' '+ change + '\n'
def output_results():
print(results)
aFile = open('inflation.txt', 'a')
aFile.write(data + '\n')
aFile.close()
get_input()
try:
fh = open('inflation.txt')
for line in fh:
print(line)
except IOError:
print("file could not be read")
You have some syntax errors. So I change the code, it's working, please check the logic of the changed code, maybe it doesn't meet the requirements of the essence of the task.
#declaring functions
def results(product_name, price_product, price_one_year_ago, price_two_years_ago):
inflation_one_year = ((price_product - price_one_year_ago)/price_one_year_ago* 100)
inflation_two_years = ((price_product - price_two_years_ago)/price_one_year_ago * 100)
return inflation_one_year, inflation_two_years
def get_input():
product_name = input('Enter the name of a product: ')
price_product = float(input('Enter the current price of the product: ')) #five
price_one_year_ago = float(input('Enter the price of the product from one year ago: '))
price_two_years_ago = float(input('Enter the price of the product two years ago: '))
return product_name, price_product, price_one_year_ago, price_two_years_ago
def output_results():
print(results)
aFile = open('inflation.txt', 'a')
aFile.write(data + '\n')
aFile.close()
#program starts from here
for i in range(0,5):
product_name, price_product, price_one_year_ago, price_two_years_ago = get_input()
inflation_one_year, inflation_two_years = results(product_name, price_product, price_one_year_ago, price_two_years_ago)
if inflation_one_year > inflation_two_years:
change = 'decrease'
else:
change = 'increase'
data = f'Product {product_name} 1 year ago to current {inflation_one_year}. Two years ago to current {inflation_two_years} change {change}.'
output_results()
try:
fh = open('inflation.txt')
for line in fh:
print(line)
except IOError:
print("file could not be read")
You have defined product_name and other variables in the get_input() method scope.
Declare them globally and then pass them into the get_input() method to assign input values.

Rewrite a pay computation with time-and-a-half for overtime and create a function called computepay which takes two parameters(hours and rate0

Here is my code (btw I am new to Stackoverflow and coding in general so forgive me if I made some mistakes in formatting this question):
hours = int(input('Enter hours:'))
rate = int(input('Enter rate:'))
pay =('Your pay this month' + str((hours + hours/2) * rate))
def computepay(hours,rate):
pay =('Your pay this month' + str((hours + hours/2) * rate))
return pay
print(pay)
To take into account overtime versus regular rates of pay it seems like you will need to know how much time the employee worked in each category. With that in mind, here is a simplified example to illustrate some of the key concepts.
Example:
def computepay(hours, rate):
return hours * rate
regular_rate = float(input("Hourly rate in dollars: "))
regular_hours = float(input("Regular hours worked: "))
overtime_hours = float(input("Overtime hours worked: "))
regular_pay = computepay(regular_hours, regular_rate)
overtime_pay = computepay(overtime_hours, regular_rate * 1.5)
total_pay = regular_pay + overtime_pay
print(f"This pay period you earned: ${total_pay:.2f}")
Output:
Hourly rate in dollars: 15.00
Regular hours worked: 40
Overtime hours worked: 10
This pay period you earned: $825.00
My teacher told me to solve it in one function, computerpay . so try this .
def computepay(hours, rate):
if hours > 40:
reg = rate * hours
otp = (hours - 40.0) * (rate * 0.5)
pay = reg + otp
else:
pay = hours * rate
return pay
Then The input Output Part
sh = input("enter Hours:")
sr = input(" Enter rate:")
fh = float(sh)
fr = float(sr)
xp = computepay(fh,fr)
print("Pay:",xp)
def computepay(hours, rate) :
return hours * rate
def invalid_input() :
print("Input Numeric Value")
while True :
try :
regular_rate = float(input("Hourly rate in dollars: "))
break
except :
invalid_input()
continue
while True :
try :
regular_hours = float(input("Regular Hours Worked: "))
break
except :
invalid_input()
continue
while True :
try :
overtime_hours = float(input("Overtime hours worked :"))
break
except :
invalid_input()
continue
overtime_rate = regular_rate * 1.5
regular_pay = computepay(regular_hours, regular_rate)
overtime_pay = computepay(overtime_hours, overtime_rate)
total_pay = regular_pay + overtime_pay
print("PAY : ", total_pay)
This code calculates the regular wage with flat rates and overtime with time-and-half for any work hours over forty(40) hours per work week.
hour = float(input('Enter hours: '))
rate = float(input('Enter rates: '))
def compute_pay(hours, rates):
if hours <= 40:
print(hours * rates)
elif hours > 40:
print(((hours * rate) - 40 * rate) * 1.5 + 40 * rate)
compute_pay(hour, rate )
This code calculates the regular wage with flat rates and overtime with time-and-half for any work hours over forty(40) hours per work week.
hour = float(input('Enter hours: '))
rate = float(input('Enter rates: '))
def compute_pay(hours, rates):
if hours <= 40:
pay = hours * rates
return pay
elif hours > 40:
pay = ((hours * rate) - 40 * rate) * 1.5 + 40 * rate
return pay
pay = compute_pay(hour, rate)
print(pay)

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

Variable is not defined in function

I'm currently working on the last function here, timeToRun.
I cannot figure out why I am receiving
NameError: name 'caloriesBurned' is not defined
I'm attempting to calculate the number of minutes it would take someone of a certain weight to burn off a number of calories while running.
weight = (int(input("Enter your weight in pounds ")))
while weight <= 40:
weight = int(input("Please reenter, weight must be higher than 40. "))
height = (int(input("Enter your height in inches ")))
while height <= 30:
height = int(input("Please reenter, height must be higher than 30. "))
age = (int(input("Enter your age in years ")))
while age <= 1:
age = int(input("Please reenter, age must be higher than 1. "))
def CalorieBurn(user_weight, user_height, user_age):
calories = 655 + (4.3 * user_weight) + (4.7 * user_height) - (4.7 * user_age)
print(calories)
def burnedRuns(user_weight):
caloriesBurned = user_weight * .095
print(caloriesBurned)
def burnedJogs(user_weight):
caloriesBurned = user_weight * .0775
print(caloriesBurned)
def burnedWalks(user_weight):
caloriesBurned = user_weight * .054
print(caloriesBurned)
def timeRequiredRun(caloriesDaily, user_weight):
caloriesBurned = user_weight * .095
timeToRun = calories / caloriesBurned
print(timeToRun)
timeRequiredRun(caloriesBurned, user_weight)
Your last line timeRequiredRun(caloriesBurned, user_weight) uses a variable called caloriesBurned which does not exist. I think you are looking for something like this:
def CalorieBurn(user_weight, user_height, user_age):
calories = 655 + (4.3 * user_weight) + (4.7 * user_height) - (4.7 * user_age)
return calories
def timeRequiredRun(calories, user_weight):
caloriesBurned = user_weight * .095
timeToRun = calories / caloriesBurned
print(timeToRun)
calories = CalorieBurn(weight, height, age)
timeRequiredRun(calories, user_weight)
You have defined caloriesBurned inside a function. This means it is only in that local scope and you cannot call it outside that function. You can use the return keyword to return that variable at the end of the function if you want, like return caloriesBurned. If you then set a variable as the function eg var = func() and the function had return caloriesBurned at the end then it will now be equal to the variable.
It appears that you have perhaps used the wrong variable in your call to timeRequiredRun(caloriesBurned, user_weight). Maybe you have forgotten to ask the user how many calories they consume per day?

Calculating overttime wages in python

I am having some problem in my code, it is returning the regular hours and not overtime pay. I am new , and I belive I am not calling the function properly , any help will be appreciated. Thanks All...
def computepay(rate, hours):
if hours > 40:
salary = rate * hours
return salary
else:
return (hours-40)*1.5*rate + salary
hours = raw_input("Enter Hours:")
hourly = raw_input("Enter Rate:")
hours = float(hours)
hourly = float(hourly)
p = computepay(hourly,hours)
print p
You have got the code wrong here. The correct code will be:
def compute pay(rate, hours):
if hours <= 40:
return rate*hours
else:
return (hours-40)*1.5*rate + (40*rate)
In your code, in the else condition, you are using salary without defining/declaring it.

Categories

Resources