Variable is not defined in function - python

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?

Related

BMI Calculator with Arrays and for Loops, getting TypeError [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I'm trying to build a BMI calculator for a project. It must prompt the user to enter the height and weight of 6 members (the elements in the array), calculate the input and print the BMI of each member. I've got that part taken care of, but I'm stumbling on the part where we use that to populate a second array and count the number of individuals that are underweight, overweight, or normal weight. Here is what I have so far:
Names = ["Jim", "Josh", "Ralph", "Amber", "Chris", "Lynn"]
Hs = []
Ws = []
UW = 18.5
OW = 25
for Name in Names:
Hs.append(int(input("What is your height in inches, " + Name + ": ")))
Ws.append(int(input("What is your weight in pounds, " + Name + ": ")))
def BMI(Ws, Hs):
for W, H in zip(Ws, Hs):
bmi_total = (W * 703) / (H ** 2)
for Name in Names:
print("The BMI for " + Name + " is: ", bmi_total)
BMI(Ws, Hs)
BMIScore = [bmi_total]
countUW = 0
countHW = 0
countOW = 0
for i in BMIScore:
if i <= UW:
countUW = countUW + 1
print("There are ", countUW, "underweight individuals.")
if i > UW and i < OW:
countHW = countHW + 1
print("There are ", countHW, "individuals with a healthy weight.")
if i >= OW:
countOW = countOW + 1
print("There are ", countOW, "overweight inividuals.")
And here is the output I get:
What is your height in inches, Jim: 5
What is your weight in pounds, Jim: 5
What is your height in inches, Josh: 5
What is your weight in pounds, Josh: 5
What is your height in inches, Ralph: 5
What is your weight in pounds, Ralph: 5
What is your height in inches, Amber: 5
What is your weight in pounds, Amber: 5
What is your height in inches, Chris: 5
What is your weight in pounds, Chris: 5
What is your height in inches, Lynn: 5
What is your weight in pounds, Lynn: 5
The BMI for Jim is: 140.6
The BMI for Josh is: 140.6
The BMI for Ralph is: 140.6
The BMI for Amber is: 140.6
The BMI for Chris is: 140.6
The BMI for Lynn is: 140.6
Traceback (most recent call last):
File "C:\Users\Crase\AppData\Local\Programs\Python\Python39\Final Project.py", line 30, in <module>
if i <= UW:
TypeError: '<=' not supported between instances of 'tuple' and 'float'
Additionally, is there a way to add whether a particular individual from the array is overweight or underweight in the line "print("The BMI for " + Name + " is: ", bmi_total)" ?
Any assistance would be appreciated. And please pardon me if my presentation is a bit sloppy. It's my first time posting.
If you can't use an object-oriented approach, you can use lists of tuples to represent a person:
names = ["Jim", "Josh", "Ralph", "Amber", "Chris", "Lynn"]
people = []
for name in names:
height = int(input("What is your height in inches, " + name + ": "))
weight = int(input("What is your weight in pounds, " + name + ": "))
# Calculate the BMI while iterating over the list of names
bmi = (weight * 703) / (height ** 2)
people.append((name, height, weight, bmi))
Then, you can use a dictionary to store the overs, healthies and unders:
UW_LIM = 18.5
OW_LIM = 25
stats = {"OW": 0, "HW": 0, "UW": 0}
for name, _, _, bmi in people:
print("The BMI for", name, "is", bmi)
key = "UW" if (bmi < UW_LIM) else "HW" if (UW_LIM < bmi < OW_LIM) else "OW"
stats[key] += 1
Finally, just print 'em out:
print("There are", stats["UW"], "underweight individuals.")
print("There are", stats["HW"], "individuals with a healthy weight.")
print("There are", stats["OW"], "overweight inividuals.")
For fun, here's an OOP approach:
class Person:
def __init__(self, name: str, height: float, weight: float):
self.name = name
self.height = height
self.weight = weight
#property
def bmi(self):
return (self.weight * 703) / (self.height ** 2)
#property
def classification(self):
return 0 if (bmi < UW_LIM) else 1 if (UW_LIM < bmi < OW_LIM) else 2
names = ["Jim", "Josh", "Ralph", "Amber", "Chris", "Lynn"]
# UW HW OW
stats = [ 0, 0, 0]
for name in names:
height = int(input("What is your height in inches, " + name + ": "))
weight = int(input("What is your weight in pounds, " + name + ": "))
person = Person(name, height, weight)
print("The BMI for", person.name, "is", person.bmi)
stats[person.classification] += 1
print("There are", stats[0], "underweight individuals.")
print("There are", stats[1], "individuals with a healthy weight.")
print("There are", stats[2], "overweight inividuals.")
Answering the first question you might want to try changing i into float(i). I'm not sure this will work with all of the loops, but you need to define the type of variable "i" is. And to answer the second question, can you could provide more information about what "overweight" and "underweight" is, but you could add a statement like this:
if bmi_total <= 150:
#etc.
Your bmi_total is defined within your BMI function but then used outside of it. The error I got when trying your code specifically pointed to that. To solve that you could make bmi_total a global so it is accessible outside of the function like this:
Names = ["Jim", "Josh", "Ralph", "Amber", "Chris", "Lynn"]
Hs = []
Ws = []
UW = 18.5
OW = 25
for Name in Names:
Hs.append(int(input("What is your height in inches, " + Name + ": ")))
Ws.append(int(input("What is your weight in pounds, " + Name + ": ")))
def BMI(Ws, Hs):
for W, H in zip(Ws, Hs):
# changed bmi_total to be a global variable here
global bmi_total
bmi_total = (W * 703) / (H ** 2)
for Name in Names:
print("The BMI for " + Name + " is: ", bmi_total)
BMI(Ws, Hs)
BMIScore = [bmi_total]
countUW = 0
countHW = 0
countOW = 0
for i in BMIScore:
if i <= UW:
countUW = countUW + 1
print("There are ", countUW, "underweight individuals.")
if i > UW and i < OW:
countHW = countHW + 1
print("There are ", countHW, "individuals with a healthy weight.")
if i >= OW:
countOW = countOW + 1
print("There are ", countOW, "overweight inividuals.")
However, it would be better form to have the BMI function calculate the BMI and return that. Most programmers are either directly or indirectly fans of the KISS (Keep It Stupid Simple) principle. Basically, seperate each chunk of functionality into a logical function (like BMI()) and have it do one thing and one thing only (in this case, calculate the BMI).
As others have stated, you will also probably want to group your names, weights, heights, and BMI for each person into a container to keep things more organized. That could be a list of lists, a dictionary, a class, or any number of other ways of keeping associated information together. Great start though!

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

I do not know what to put as a parameter in order to assign value to a variable

I right now have them set as global but I do not know how to set up the argument and parameters in order to save the variable bmr in order to use it in another function such as get_calorie_requirement. I know i have a lot of inputs in order to get the bmr. Should I define the formula get_bmr? I am stuck on something simple because I am trying to do bmr= get_bmr(bmr) but that is wrong.
import math
def get_bmr():
gender = input("What is your gender: M or F?")
age = int(input("What is your age?"))
height = int(input("What is your height in inches?"))
weight = (int(input("What is your weight in pounds?")))
bmr_wght_constant = 4.536
bmr_hght_constant = 15.88
bmr_age_constant = 5
if gender == 'M':
bmr = int((bmr_wght_constant * weight) + (bmr_hght_constant * height) - (bmr_age_constant * age) + 5)
elif gender == 'F':
bmr = int((bmr_wght_constant * weight) + (bmr_hght_constant * height) - (bmr_age_constant * age) - 161)
else:
print("Please try again.")
return bmr
def get_daily_calorie_requirement():
dcr_1 = 1.2
dcr_2 = 1.375
dcr_3 = 1.55
dcr_4 = 1.725
dcr_5 = 1.9
act_lvl = int(input("What is your activity level?"))
if act_lvl == 1:
daily_calorie_requirement = int(bmr * dcr_1)
elif act_lvl == 2:
daily_calorie_requirement = int(bmr * dcr_2)
elif act_lvl == 3:
daily_calorie_requirement = int(bmr * dcr_3)
elif act_lvl == 4:
daily_calorie_requirement = int(bmr * dcr_4)
elif act_lvl == 5:
daily_calorie_requirement = int(bmr * dcr_5)
else:
print("Please choose a number 1-5.")
return daily_calorie_requirement
def main():
print("Hello, welcome to my intergration project!")
print("The purpose of this program is to help the user reach their goal and provide helpful suggestions.")
print("It will do this by taking your age, gender, height and your level of physical activity in order to calculate your Basal Metabolic Rate(BMR)")
print("Your BMR is how many calories you burn in a single day. Combining your BMR with your goals we can suggest a meal plan and excercises that will help reach your goals")
print("Let's get started! I will start by asking you a few questions in order to make a profile and give you the best informed advice.")
if gender == 'M':
bmr = int((bmr_wght_constant * weight) + (bmr_hght_constant * height) - (bmr_age_constant * age) + 5)
elif gender == 'F':
bmr = int((bmr_wght_constant * weight) + (bmr_hght_constant * height) - (bmr_age_constant * age) - 161)
else:
print("Please try again.")
print("Your BMR is: ", bmr)
print("Great! Now that we have calculated your Basal Metabolic Rate, let's calculate your daily calorie requirement!")
print("This is the calories you should be taking in to maintain your current weight")
print("How active are you on a scale of 1-5?")
print("1 being you are sedentary (little to no exercise)")
print("2 being lightly active (light exercise or sports 1-3 days a week)")
print("3 being moderately active (moderate exercise 3-5 days a week)")
print("4 being very active (hard exercise 6-7 days a week)")
print("5 being super active (very hard exercise and a physical job)")
print("Exercise would be 15 to 30 minutes of having an elevated heart rate.")
print("Hard exercise would be 2 plus hours of elevated heart rate.")
daily_calorie_requirement = get_daily_calorie_requirement()
It would be more helpful to show us the error you're facing, it's hard to tell what the issue could be since the code isn't working either. If you have a traceback, that would be useful in solving this Question.
Assigning simply occurs when there is a variable on the left hand side of an =. When calling a method such as get_bmr() what ever is return'ed by this function will be assigned.
Your code could be failing since you're trying to get gender but this isn't defined in under function main. You can replace the if gender "M" elif "F" with simply the following. (Since you call all this in get_bmr)
bmr = get_bmr()
If you're wanting to pass bmr into the next function would creating an argument for get_daily_calorie_requirement resolve the issue?
def get_daily_calorie_requirement(bmr):
dcr_5 = 1.9
return int(bmr * dcr_5)
def main():
bmr = get_bmr()
daily_calorie_requirement = get_daily_calorie_requirement(bmr)
if __name__ == '__main__':
main()
If you want to simplify it you could move some of the parameters into arguments:
def get_bmr(gender, age, height, weight):
""" Calculate BMR using the following formula:
bmr = weight_const*weight ... etc.
"""
gender_coef = 5 if gender == "M" else -161
return int((4.536 * weight) + (15.88 * height) - (5 * age) + 5)
gender = input("What is your gender: M or F?")
while gender not in ["M", "F"]:
print("Please try again, accepted values: M/F")
gender = input("What is your gender: M or F?")
age = int(input("What is your age?"))
height = int(input("What is your height in inches?"))
weight = int(input("What is your weight in pounds?"))
bmr = get_bmr(gender, age, height, weight)
Few things that can be tricky, naming variables the same as your functions, or simply forgetting to return in a function.

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

Python function/argument 'not defined' error

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

Categories

Resources