def main():
name = input("What is your first name?: ")
name2 = input("What is your last name?: ")
kg = float(input("What is your weight in kilograms?: "))
meters = float(input("What is your height in meters?: "))
mass = float(kg)
height = float(meters)
Health(BMI, Ponderal, Rohrer)
print(name2+",",name,"(BMI:",BMI,",",\
"Ponderal Index:",Ponderal,",","Rohrer's Index:",Rohrer,",",")")
***It should return something along the lines of
Last, First(BMI: 35.234, Ponderal Index: 16.5, Rohrer's Index: 114)
Im in a intro to python class and its really late to contact anyone else for help. The whole purpose of this exercise is to create functions and call back to them.
Edit: Thanks a lot for the help guys, I know a lot of the questions on here are normally far more advanced, but the quick replies and the amount of helpful tips is greatly appreciated.
If a function returns something, then you should put it somewhere. For example, in a variable!
Here, change your functions:
def main():
name = input("What is your first name?: ")
name2 = input("What is your last name?: ")
mass = float(input("What is your weight in kilograms?: "))
height = float(input("What is your height in meters?: "))
#mass = float(kg) #not needed
#height = float(meters) #not needed
result = health(mass, height)
#printing based on the return value. result[0] is bmi, and so on.
print("%s, %s (BMI: %d, Ponderal Index: %d, Rohrer's Index: %d"%(name2,name,health[0],health[1],health[2]))
def bmi (mass, height):
result = mass / (height ** 2)
return result
def ponderal (mass, height):
result = mass / height ** 3
return result
def rohrer(mass, height):
result = (mass * 10000) / ((height * 100) ** 3)
return result
def health (mass, height):
#calling the functions
bmi = bmi(mass, height) #store the returned value to a variable
ponderal = ponderal(mass, height)
rohrer = rohrer(mass, height)
return [bmi,ponderal,rohrer] #return it as a list.
Result:
>>> ================================ RESTART ================================
>>>
What is your first name?: Akhyar
What is your last name?: Kamili
What is your weight in kilograms?: 50
What is your height in meters?: 1.7
Kamili, Akhyar (BMI: 17.301038062283737 , Ponderal Index: 10.177081213108082 , Rohrer's Index: 0.1017708121310808 , )
>>>
Some advice:
Do NOT capitalize function names!
Don't name variables like the functions!
Your code will do better.
There are a lot of problems with your code; first off format it better make sure you have comments on your code (lines that start with #)
Also don't directly convert units from string to float. What if they enter something invalid handle exceptions.
Thirdly the way you format you output text is god awful it is extremely hard to read all the commas and paratheses.
Also the way you get the values you never set them to a variable you also use this health function which you do not need just call the values directly!
Also use sensical names for variables instead of name2 use first name etc
Your code should better look like this (note if this is for homework and you turn this in your professor will easily find it on stackoverflow; so don't)
# calculates the BMI of a person
def BMI (mass, height):
BMI = mass / (height ** 2)
return BMI
# calculates the Ponderal index of a person
def Ponderal (mass, height):
Ponderal = mass / height ** 3
return Ponderal
# calculates the Rohrer index of a person
def Rohrer (mass, height):
Rohrer = (mass * 10000) / ((height * 100) ** 3)
return Rohrer
# this isn't needed
def Health (BMI, Ponderal, Rohrer):
BMI (mass, height)
Ponderal (mass, height)
Rohrer (mass, height)
return Health
def main():
# get the names of people
first_name = input("What is your first name?: ")
last_name = input("What is your last name?: ")
# get their height and weight
kg = input("What is your weight in kilograms?: ")
meters = input("What is your height in meters?: ")
# convert mass and height to numbers
try:
mass = float(kg)
except ValueError:
print "Please enter a valid mass."
return
try:
height = float(meters)
except ValueError:
print "Please enter a valid height."
return
# call the BMI, Ponderal and Rohrer functions
# don't make the variable BMI as your function is also that name!
bmi_value = BMI(mass, height)
ponderal_value = Ponderal(mass, height)
rohrer_value = Rohrer(mass, height)
print( "%s, %s (BMI: %s, Ponderal Index: %s, Rohrer Index: %s)" % (last_name, first_name, bmi_value, ponderal_value, rohrer_value) )
# this print string is EXTREEMLY hard to read
# print(name2+",",name,"(BMI:",BMI,",", "Ponderal Index:",Ponderal,",","Rohrer's Index:",Rohrer,",",")")
# if we are running this script directly call main
if __name__ == "__main__":
main()
You're not calling the functions, you're only referencing them. For example:
Ponderal
# <function Ponderal at blah>
Compared to:
Ponderal()
# A number
Related
I'm trying to get it when you type RecPyrSA it will play the def RecPyrSA and I'm not sure how that could be done. I'm also new to python and not sure what to do so I just wanted to make a fun script.
from math import e
def RecPyrSA():
recpyrl=float(input("Base Length "))
recpyrw=float(input("Base Width "))
recpyrthl=float(input("Triangle Height On The Legth Side "))
recpyrthw=float(input("Triangle Height On The Width Side "))
recpyrsa=(recpyrl*recpyrw+recpyrthl*recpyrl+recpyrthw*recpyrw)
print(recpyrsa)
def ConeSA():
print ("type r then l")
x=float(input("r "))
y=float(input("l "))
csa=(3.14*x*x)+(3.14*y*x)
print(csa)
start=input("Type Here --> ")
while True:
print ("For the surface area of a rectangular pyramid type RecPyrSA")
SAstart=input("Type here ---> ")
if SAstart == "RecPyrSA"
RecPyrSA
break
else:
print ("Incorrect Code")
print ("Try Again")
You didn't call the function.
RecPyrSA
is simply a variable with a function object in it. Once you've referenced a function object, it is called with parens
RecPyrSA()
You need to call the function, which you do with parenthesis, function_name(). Also, you don't appear to use e from math, so you don't need to import that. You were also missing a colon at the end of the line: if SAstart == "RecPyrSA". You should also add space on either side of operators, as according to PEP 8. Also according to PEP 8, function names should be in snake_case.
Code with changes:
def rec_pyr_SA():
recpyrl = float(input("Base Length "))
recpyrw = float(input("Base Width "))
recpyrthl = float(input("Triangle Height On The Legth Side "))
recpyrthw = float(input("Triangle Height On The Width Side "))
recpyrsa = recpyrl * recpyrw + recpyrthl * recpyrl + recpyrthw * recpyrw
print(recpyrsa)
def cone_sa():
print("type r then l")
x = float(input("r "))
y = float(input("l "))
csa = (3.14 * x * x) + (3.14 * y * x)
print(csa)
while True:
print ("For the surface area of a rectangular pyramid type RecPyrSA")
SA_start = input("Type here ---> ")
if SA_start == "RecPyrSA":
rec_pyr_SA()
break
else:
print("Incorrect Code")
print("Try Again")
#create an EMPLOYEE object to store the name, hours worked, and hourly wage by passing them into the constructor. Be sure that the constructor prints the employee name, hours worked, and hourly wage. Then invoke the method that will calculate the employee’s pay. **
After calculating the pay for an employee, add it to the list created in step #1 above(lstPay)(add only the pay).
my code:
# STEP 2
class Employee(object):
def __init__(self, Name="", Hours="", Wage=""):
self.employeeName = Name`enter code here`
self.employeeHoursWorked = int(Hours)
self.employeeHourlyWage = float(Wage)
def Name(self):
print("Employee Name: ", self.employeeName.title())
def HoursWorked(self):
print("Hours worked: ", self.employeeHoursWorked)
def Wage(self):
print("Hourly wage: ", self.employeeHourlyWage)
def getEmpname(self):
return self.employeeName.title()
def setEmpname(self, epName):
self.employeeName = epName
def Emppay(self): # will calculate the employee pay based on info provided
if self.employeeHoursWorked <= 40:
print("Employee Pay :", self.employeeHoursWorked * self.employeeHourlyWage)
else:
print("Employee Pay :",
((self.employeeHoursWorked - 40) * (self.employeeHourlyWage * 1.5)) + (self.employeeHourlyWage * 40))
Empname = property(getEmpname, setEmpname)
# STEP 3
print()
strEmpName = input("Enter Employee Name: ")
intHoursWorked = int(input("Enter hours worked: "))
fltHourlyWage = float(input("Enter hourly wage: "))
objEmployee = Employee(strEmpName, intHoursWorked, fltHourlyWage) # the object objEmployee
objEmployee.Name()
objEmployee.HoursWorked()
objEmployee.Wage()
objEmployee.Emppay()
Do you mean this:
employees= list()
while True:
print()
strEmpName = input("Enter Employee Name: ")
if strEmpName.strip() == '':
break
else:
intHoursWorked = int(input("Enter hours worked: "))
fltHourlyWage = float(input("Enter hourly wage: "))
objEmployee = Employee(strEmpName, intHoursWorked, fltHourlyWage) # the object objEmployee
objEmployee.Name()
objEmployee.HoursWorked()
objEmployee.Wage()
objEmployee.Emppay()
employees.append(objEmployee)
The code above, would ask for employees as long as a name is entered, that is not an empty string and would append the records to list employees.
def main():
class BMI:
def __init__(self, firstName, lastName, age, height, weight):
self.firstName = firstName
self.lastName = lastName
self.fullName = firstName + " " + lastName
self.age = age
self.height = (height * 0.025) ** 2
self.weight = weight * 0.45
def setFullName(self, firstName, lastName):
self.firstName = firstName
self.lastName = lastName
self.fullName = firstName + " " + lastName
print(self.fullName)
def setAge(self, age):
self.age = age
def setHeight(self, height):
self.height = (height * 0.025) ** 2
def setWeight(self, weight):
self.weight = weight * 0.45
def getBMI(self):
bmi = self.weight // self.height
return bmi
def getStatus(self):
getBMI()
if bmi < 19:
print("You have an unhealthy BMI, gain some weight!")
elif bmi > 19 and bmi < 25:
print("You have a healthy BMI")
else:
print("You have an unhealthy BMI, lose some weight!")
firstName = input("Enter your first name: ")
lastName = input("Enter your last name: ")
age = int(input("Enter your age: "))
height = int(input("Enter your height in inches: "))
weight = int(input("Enter your weight in lbs: "))
userInputBMI = BMI(firstName, lastName, age, height, weight)
print(userInputBMI.setFullName(firstName, lastName))
print("Your BMI is:", userInputBMI.getBMI())
print(userInputBMI.getStatus())
main()
My problem is printing the status of the user based on the inputs they provide. The problem is coming from the method being run within the "getStatus" method.
My thoughts are that from that method within the "getStatus" it gets the bmi that is measured within the if-elif-else statements. The computer says that "getBMI" is not defined. If someone could teach me the right way to use methods how I am trying that would be awesome!
You need to tell Python that, inside your getStatus method, you want to access your getBMI method from the same class, and not a function (or any other callable object) named getBMI that's defined outside of your class. You do this by referencing the method as self.getBMI inside your class, like this:
def getStatus(self):
bmi = self.getBMI()
Notice that I also caught the return value of getBMI, because otherwise that value is lost. bmi is just a local variable inside the getBMI method which will be forgotten once it ends, unless you either:
return that value and catch the return with another variable upon executing the method;
save it as an instance attribute, writing (at some point) self.bmi = bmi inside your getBMI method.
I'd go with the first option, since it makes sense for a method named getBMI to return the bmi. It's also a bit easier to mess up and forget which attribute is which if you constantly write and rewrite the instance attributes - tho sometimes that's exactly why you would use objects and classes in the first place.
change the line:
getBMI()
to
bmi = self.getBMI()
I have years of experience in programming, but I am learning Python as a new language as you too. Correct me anybody, please, if I am wrong or you have something to add. Here are my suggestion of the right way to use methods and the language:
Read about Python naming convention: function names and variables are lowercase, method and instance variables too.
No need to pre-calculate and have instance variable full_name: just calculate and return it when you need one.
Don’t convert height to some part of the square height formula and keep it under name height. Just calculate BMI from height and weight when you need it and by BMI formula from inches and pounds.
Keep the calculation result in float since they use not 19, but 18.5 as threshold value.
No need to provide setAge, setHeight, setWeight in your code question, since you don’t need and don’t use it in the program yet. Actually, if you think: set_height, and set_weight (Python naming) you don’t need to provide at all. You create the person instance and it stays constant. Same probably with set_age, until you not creating some simulation game when your instances will age.
Print should be outside your class. You ask for value or string to be returned if you need something to display or print.
Last, but not least: think immediately about testing and write test function first. It is very boring to enter a first name, last name, age, height, and weight ... again, and again … QA will reuse your test later for unit testing.
Here is my suggestion in the form of code (I left one bug intentionally - I think it will be easy to catch. Sorry, if more than one - nobody is perfect):
class BodyMassIndex:
BMI_STATUS_LOSE = 0
BMI_STATUS_HEALTHY = 1
BMI_STATUS_GAIN = 2
def __init__(self, first_name, last_name, age, height, weight):
self._first_name = first_name
self._last_name = last_name
self._age = age
self._height = height
self._weight = weight
def get_full_name(self):
return self._first_name + " " + self._last_name
def get_bmi(self):
return (self._weight * 703) / self._height ** 2
def get_status(self):
bmi = self.get_bmi()
if bmi < 18.5:
status = BodyMassIndex.BMI_STATUS_LOSE
elif bmi < 25.0:
status = BodyMassIndex.BMI_STATUS_HEALTHY
else:
status = BodyMassIndex.BMI_STATUS_GAIN
return status
def get_report(self):
a = self.get_full_name()
b = "Your BMI is: {0:.1f}".format(self.get_bmi())
status_name = ['n unhealthy BMI, lose some weight!',
' healthy BMI',
'n unhealthy BMI, gain some weight!']
c = 'You have a' + status_name[self.get_status()]
return a + '\n' + b + '\n' + c
if __name__ == '__main__':
def first_test():
user_test_list = [
("Alex", "Fat", 21, 69, 170, 2),
("Josh", "Smart", 17, 69, 169, 1),
("Ann", "Full", 19, 69, 126, 1),
("Mary", "Skinny", 19, 69, 125, 0),
]
for first, last, age, height, weight, expected in user_test_list:
user = BodyMassIndex(first, last, age, height, weight)
print(user.get_report())
print()
first_test()
while True:
first = input("Enter your first name: ")
if not first:
break
last = input("Enter your last name: ")
age = int(input("Enter your age: "))
height = int(input("Enter your height in inches: "))
weight = int(input("Enter your weight in lbs: "))
user = BodyMassIndex(first, last, age, height, weight)
print(user.get_report())
I'm new to functions, so I'm not quite sure how or why this is happening and I do not know how t fix it. Can someone explain why this error keeps occuring?
def loan_payment(l):
loan = float(input("Please enter how much you expend monthly on loan payments:"))
return loan
def insurance_cost(i):
insurance = float(input("Please enter how much you expend monthly on insurance:"))
return insurance
def gas_cost(g):
gas = float(input("Please enter how much you expend monthly on gas:"))
return gas
def maitanence_cost(m):
maitanence = float(input("Please enter how much you expend monthly on maintanence:"))
return maitanence
def monthly_cost(l, i, g, m):
monthly_expenses = float(l + i + g + m)
print("You expend $"+format(monthly_expenses, '.2f')+" in a month.")
return float(monthly_expenses)
def yearly_cost(monthly_cost):
yearly_expenses = 12 * monthly_cost
print("At your current monthly expenses, in a year you will have paid $"+format(yearly_expenses, '.2f')+".")
return yearly_expenses
def main():
loan_payment(l)
insurance_cost(i)
gas_cost(g)
maitanence_cost(m)
monthly_cost(l, i, g, m)
yearly_cost(monthly_cost)
main()
This code returns the error:
line 24, in main
loan_payment(l) NameError: name 'l' is not defined
I think you may have gotten your wires a bit crossed on how python passes by assignment, you wouldn't be the first, and here's a great question to help, as well as how to assign values and defining methods. As best as I can tell, your main method should look more like:
def main():
l = user_in_loan_payment()
i = user_in_insurance_cost()
g = user_in_gas_cost()
m = user_in_maintanence_cost()
monthly_cost = calculate_monthly_cost(l, i, g, m)
yearly_cost = calculate_yearly_cost(monthly_cost)
I changed the method names to start with "calculate" or "user_in" to make it a little more readable.
That's exactly what the error says: l is not defined, like any other variable. If I get it right you are trying to enter values in first 4 functions and then use them in the next two functions for calculations.
If that's true, your code should be as following:
def loan_payment():
loan = float(input("Please enter how much you expend monthly on loan payments:"))
return loan
def insurance_cost():
insurance = float(input("Please enter how much you expend monthly on insurance:"))
return insurance
def gas_cost():
gas = float(input("Please enter how much you expend monthly on gas:"))
return gas
def maitanence_cost():
maitanence = float(input("Please enter how much you expend monthly on maintanence:"))
return maitanence
def monthly_cost(l, i, g, m):
monthly_expenses = float(l + i + g + m)
print("You expend $"+format(monthly_expenses, '.2f')+" in a month.")
return float(monthly_expenses)
def yearly_cost(monthly_cost):
yearly_expenses = 12 * monthly_cost
print("At your current monthly expenses, in a year you will have paid $"+format(yearly_expenses, '.2f')+".")
return yearly_expenses
def main():
l = loan_payment()
i = insurance_cost()
g = gas_cost()
m = maitanence_cost()
mc = monthly_cost(l, i, g, m)
yearly_cost(mc)
main()
def perd():
Personaldetails_file = open("Personaldetails_file.txt", "w")
Personaldetails_file = open("Personaldetails_file.txt", "a")
pd = input("Are you a new user?")
if pd == "yes":
print ("Add your details")
####################################
age = int(input("how old are you?"))
DOB = input("Date of birth:")
gender = input("Gender:")
weight = int(input("weight in kg:"))
height = int(input("height in cm:"))
Personaldetails = (age, DOB, gender, weight, height)
Personaldetails_file.write(str(Personaldetails))
Personaldetails_file.close()
#######################################
def td():
choice = input("which trainning event would you like to access?\n1.swimming\n2.cycling\n3.running\nplease type in the number before the event of which you want to choose\n")
if choice == "1":
Swimming_file= open("Swimming_file.txt", "w")
totaldistance = input("what was the total distance you swam in meters?")
totaltime = input("how long did you swim for in minutes?")
speed = totaldistance/totaltime
print ("on average you where running at a speed of", speed, "mps\nyou can look at the tables to see how many calouries you have burnt")
total = (totaldistance, totaltime, speed)
Swimming_file.write(str(total))
Swimming_file.close()
elif choice == "3":
Running_file= open("Running_file.txt", "w")
totaldistanceR = int(input("what was the total distance you ran in KM?"))
totaltimeR = int(input("how long did you run for in minutes?"))
totaltimeR1 = 60/totaltimeR
speedR1 = totaldistanceR/totaltimeR1
calburn = (speedR1 * 95)/(60/totaltimeR1)
print ("\nThe records have been saved")
print ("\non average you where running at a speed of", speedR1, "KMph\nyou burnt",calburn," calouries\n")
totalR = (totaldistanceR, totaltimeR, speedR1, calburn)
Running_file.write(str(totalR))
Running_file.close()
##############################################################
elif choice == "2":
Cycling_file= open("Cycling_file.txt", "w")
with open("Personaldetails_file.txt", "r") as f:
content = [x.strip('\n') for x in f.readlines()]
lines = f.readlines()
for line in lines:
words = line.split(",")
age = (line.split)(0)
weight = (line.split)(3)
height = (line.split)(4)
################################################################
totaldistancec = int(input("what was the total distance you cycled in KM?"))
totaltimec = int(input("how long did you cycle for in minutes?"))
calburn1 = (13.75 * weight) + (5 * height) - (6.67 * age)
speedc = totaldistancec/totaltimec
print ("on average you where running at a speed of", speedc, "KMph\nyou burnt", calburn1, " calouries")
totalc = (totaldistancec, totaltimec, speedc)
Cycling_file.write(str(totalc))
Cycling_file.close()
Personaldetails_file.close()
when I un the program an error appears.
line 84, in td
calburn1 = (13.75 * weight) + (5 * height) - (6.67 * age)
UnboundLocalError: local variable 'weight' referenced before assignment
does anyone know how I can fix this error?
the code which is relevant to the question surrounded by '#'
You declare weight here
def perd():
...
gender = input("Gender:")
weight = int(input("weight in kg:"))
height = int(input("height in cm:"))
...
but you try to use it here in this other function:
def tr():
....
calburn1 = (13.75 * weight) + (5 * height) - (6.67 * age)
....
this is a separate function that does not know about the variables within the perd() function, and why should it? It does not need any of them to operate as functions should isolate pieces of code and be able to be used by themselves. In other words once perd() runs its local variables go out of scope. Take a look at this question, Short Description of the Scoping Rules?. To solve this you either need to make the input taken in perd() global, not advisable because it is not very pythonic. Or you can pass the value in as a function parameter like this:
td(weight, height, age):
#code here
Now you have access to the value passed in as weight within the td function. But you need to realize that these are not the same variables, they may share the same name but they are NOT the same. You will need to pass in all values that you want to use from the perd function. This is preferable because you are designing your functions in a way that they can be used modularity, so one can handle getting input from the user while the other can perform calculations on data that it already knows are valid, this allows for easier to read code, which is what python is all about