I'm a Python beginner and trying to build upon my code below. I have the base working and want to collect the data from the calculator and store it in a dictionary. I created the last function to do this, but I can't pass the variables from bmi_metrics(). Why?
#Intro to BMI Calculator
print("Welcome to my BMI calculator!")
print("Give me your height and weight, I'll calculate your Body Mass Index")
# Gather BMI metrics from user and create two loops that only accept number inputs for height/weight
def bmi_metrics():
get_name = (input("\nWhat's your name? "))
while True:
try:
get_height = float(input(f"\nHi {get_name.title()}, please enter your height in inches: "))
break
except ValueError:
print("Oops, that doesn't look like a number, try again.")
while True:
try:
get_weight = float(input("Please enter your weight in pounds: "))
break
except ValueError:
print("Oops, that doesn't look like a number, try again.")
#Calculate BMI from height and weight input
BMI = (get_weight * 703) / (get_height ** 2)
#Display user BMI and weight category back to them
print(f"{get_name.title()}, your BMI is {BMI:.2f}")
if BMI <= 18.5:
print(f"A person with a BMI of {BMI:.2f} is underwieght ")
elif BMI <= 24.9:
print(f"A person with a BMI of {BMI:.2f} is normal weight ")
elif BMI <= 29.9:
print(f"A person with a BMI of {BMI:.2f} is overweight ")
else:
print(f"A person with a BMI of {BMI:.2f} is obese")
return get_name, get_height, get_weight, BMI
#Prompt user to run calculator again
def prompt_again():
while True:
run_again = input("\nWould you like to do another calculation (y/n)? ")
if run_again == 'y':
bmi_metrics()
elif run_again == 'Y':
bmi_metrics()
elif run_again == 'N':
break
elif run_again == 'n':
break
else:
print("Please enter 'y' or 'n' ")
print("Thanks for playing!")
#Collect Name/BMI data and place it in an empty dictionary
def calc_data():
calc_results = {"Name": " ", "BMI": " "}
get_name = name
bmi_metrics()
prompt_again()
Hello :) You are missing the storage of the returned values from the call at the end of the script:
get_name, get_height, get_weight, BMI = bmi_metrics()
Otherwise, the result is not stored. You have to keep in mind that all variables in python defined inside a method are local to the method unless you store them in an object, return them as result of the method or define them as global variables. If you want to use the resulting values in another function you need to pass them as arguments.
Related
I've made this BMI calculator and I want the user count at the bottom to count every time the user has used the BMI calculator by entering "y". I can't seem to get the code to work. Any help?
user_continue = "y"
counter = 0
while user_continue == "y":
weight = float(input("What is your weight? (KG) "))
height = float(input("What is your height? (Metres) "))
#formula to convert weight and height to users bmi
bmi = weight/(height*height)
print("Your BMI is", bmi)
#indicators to state if user is either underwieght, overweight or normal
if bmi < 18:
print("It indicates you underweight.")
elif bmi >= 18 and bmi < 25:
print("It indicates you are within normal bounds.")
elif bmi >= 25:
print("It indicates you are overweight.")
user_continue = input("Add Another BMI? y/n: ")
# add counter
if user_continue != "y":
counter+=1
print(counter)
print("\t\tThank You for using BMI calculator by Joe Saju!")
print("\n\t\t\t\tPress ENTER to Exit.")
break
You want to increase the counter in any iteration of the loop so you need increase the counter variable inside the loop but not in the ending if statement.
Tip: increase counter variable at the begining of the loop(like in the code below)
In your case the counter increase only if the user want exit. so it will counter only one time.
user_continue = "y"
counter = 0
while user_continue == "y":
# increase the counter at the begining
counter+=1
weight = float(input("What is your weight? (KG) "))
height = float(input("What is your height? (Metres) "))
#formula to convert weight and height to users bmi
bmi = weight/(height*height)
print("Your BMI is", bmi)
#indicators to state if user is either underwieght, overweight or normal
if bmi < 18:
print("It indicates you underweight.")
elif bmi >= 18 and bmi < 25:
print("It indicates you are within normal bounds.")
elif bmi >= 25:
print("It indicates you are overweight.")
user_continue = input("Add Another BMI? y/n: ")
if user_continue != "y":
# counter+=1 line removed and moved to the begining
print(counter)
print("\t\tThank You for using BMI calculator by Joe Saju!")
print("\n\t\t\t\tPress ENTER to Exit.")
break
I've been trying to put the data input into the program and append it to the lists, but I'm not sure how. My original plan was to create "while" loops and if the length in imperial was 0, then metric would be used to calculate bmi. If not, imperial would be used. I'm just having some trouble figuring out how to do that and how to append the data to their respective lists. It's really important to use lists for that data in this assignment, I just can't figure it out. Thank you!!!
def inputM():
print("Enter weight in kg")
weightm = float(input())
print("Enter height in meters")
heightm = float(input())
return weightm, heightm
def inputI():
print("Enter weight in pounds")
weighti = float(input())
print("Enter height in inches")
heighti = float(input())
return weighti, heighti
def healthindex (preference, bmi):
if preference == "b":
print("BMI " + str(round(bmi,2)))
elif preference == "h":
index = 0
print("your BMI is " + str(round(bmi,2)))
while index < len(BMIList):
if bmi < BMIValues[index]:
print ("And, you are " + BMIList[index])
return
index = index + 1
print("You are Obese")
else:
print("Invalid choice")
return
BMIList = ["severly underweight", "underweight", "healthy", "overweight", "obese"]
BMIValues = [15.99, 18.49, 24.99, 29.99, 500]
print("Welcome to BMI Calculator!")
print("Enter I for Imperial or M for Metric")
request = input().upper()
if request == "M":
weightm, heightm = inputM()
bmi = weightm/(heightm**2)
elif request == "I":
weighti, heighti = inputI()
bmi = (703*weighti)/(heighti**2)
else:
print("Invalid input")
print("Enter b to only see your bmi or enter h if you would like to see your bmi and your corresponding health index!")
preference = input()
healthindex (preference, bmi)
I would suggest that there are better ways to learn about the use and functionality of lists than to use them for user input, however, you could pass a list to the inputM() and inputI() functions, add the user input to those lists, and then calculate the BMI from the items in the list. Here's an example for the metric BMI calculation:
def inputM(user_input):
print("Enter weight in kg")
user_input.append(float(input()))
print("Enter height in meters")
user_input.append(float(input()))
user_input = []
if request == "M":
inputM(user_input)
bmi = user_input[0]/(user_input[1]**2)
This shows how inconvenient and clumsy it is to use lists to capture user input in this scenario. Firstly, an empty list must be created and passed to the function. The function relies on the mutability of lists to return values to the calling code. And then the calling code needs access the result in a cumbersome way by accessing elements of the list by index, or by unpacking the list into variables, e.g.
inputM(user_input)
weightm, heightm = user_input[-2:] # unpack the last 2 items in the list
I'm working on an assignment to create a code that receives input from the user on a name, weight, and height and then returns a BMI value and then loops back to ask for another name. I cannot seem to get my BMI function to return an output though.
def BMI(BMI):
num1, num2 = weight, height
BMI = (num1 * 706)/(num2^2)
return BMI
user = str
end = "x"
while user != end:
print()
user = input("Please enter player name or type 'X' to quit: ")
if user == end:
print("Report Complete")
break
else:
num1 = (float(input("Please enter weight: ")))
num2 = (float(input("Please enter height: ")))
if num1 >= 1:
print("BMI: "(BMI))
i receive this error: "" when I run the function.
I'm looking for an input that is along the lines of
Please enter player name or press 'X' to quit: xxx
Please enter weight: xxx
Please enter height: xxx
BMI: xxx
Please enter player name or press 'X' to quit:
Okay, so there are a few things that you'll want to fix for this to work.
When you are printing, you are not calling the function correctly and python thinks you're trying to use "BMI: " as a function. How you want to call BMI is like BMI(weight, height) where you pass in the values for weight and height as parameters. BMI returns a float, so you'll need to turn it into a string before appending it. The result of those changes are "BMI: "+ str(BMI(num1, num2))
In the definition of your BMI function, you'll want to pass in the weight and height as parameters like so: def BMI(weight, height):. This will allow you to use both weight and height in the function body.
The ^ in python does not mean power, it means bitwise xor. You want to use the ** operator like so: BMI = (num1 * 706)/(num2**2)
After making those changes, you should end up with something like this:
def BMI(weight, height):
num1, num2 = weight, height
BMI = (num1 * 706.0)/(num2**2)
return BMI
user = str
end = "x"
while user != end:
print()
user = input("Please enter player name or type 'X' to quit: ")
if user == end:
print("Report Complete")
break
else:
num1 = (float(input("Please enter weight: ")))
num2 = (float(input("Please enter height: ")))
if num1 >= 1:
print("BMI: " + str(BMI(num1, num2)))
My Bmi calculator that I am writing for school is producing my output backwards, it first calls for user information and than for name information. Please help, i need it to be the other way around.
user = str
end = False
def bmi_intro():
print("BMI Calculator")
while end == False:
user = input("Enter students name or '0' to quit: ")
if user == "0":
print("end of report!")
else:
def userName(str):
user = str
print("Lets gather your information,", user)
break
get_height = float(input("Please enter your height in inches: "))
get_weight = float(input("Please enter your weight: "))
body_mass_index = (get_weight * 703) / (get_height ** 2)
print ("Your bmi is: ", body_mass_index)
def main():
get_height = 0.0
get_weight = 0.0
body_mass_index = 0.0
bmi_intro()
There are a number of issues in your code:
You have not set the value of end
You have not indented correctly
The main function is redundant in this case
It should be as follows:
def bmi_intro():
end = False
print("BMI Calculator")
while end == False:
user = input("Enter student's name or '0' to quit: ")
if user == "0":
print("end of report!")
end = True
else:
print("Lets gather your information,", user)
get_height = float(input("Please enter your height in inches: "))
get_weight = float(input("Please enter your weight: "))
body_mass_index = (get_weight * 703) / (get_height ** 2)
print ("Your bmi is:", body_mass_index)
bmi_intro()
Additional suggestions
You may like to indicate the unit of measurement in your question for the weight i.e.:
get_weight = float(input("Please enter your weight in pounds (lbs): "))
A function is not required unless you plan on extending this code and/or adding additional functions. You could do away with the function definition and the function call if you wish.
Correction of indentation and removing break statement can solve your problem (I have tried to edit your code as less as possible, I think it will be helpful to you to understand the code):
user = str
end = False
def bmi_intro():
print("BMI Calculator")
while end == False:
user = input("Enter students name or '0' to quit: ")
if user == "0":
print("end of report!")
break
else:
def userName(str):
user = str
print("Lets gather your information,", user)
get_height = float(input("Please enter your height in inches: "))
get_weight = float(input("Please enter your weight: "))
body_mass_index = (get_weight * 703) / (get_height ** 2)
print ("Your bmi is: ", body_mass_index)
def main():
get_height = 0.0
get_weight = 0.0
body_mass_index = 0.0
bmi_intro()
Trying to add all the BMI results together and then display it, keep getting a error :
TypeError: 'float' object is not iterable
Also keep getting None printed when i run my program after a bmi is calculated>?
def bmirange():
if bmi >= 25.0:
print('Your BMI measurement shows that you are overweight')
elif bmi <18.0:
print('Your BMI measurement shows that you are underweight')
else:
print('Your BMI measurement shows that you are in the healty weight band')
weight = float(input('What is your weight in Kg? '))
height = float(input('What is your height in Meters? '))
bmi = weight / (height * height)
print(bmi)
print(bmirange())
bmiredo = input('Do you want to do another BMI measurement?, y / n ')
while bmiredo == 'y':
weight = float(input('What is your weight in Kg? '))
height = float(input('What is your height in Meters? '))
print(bmi)
print(bmirange())
bmiredo = input('Do you want to do anoher BMI measurement?, y / n ')
else:
print('ok, the total of your BMI results are')
print(sum(bmi))
input('press the enter key to exit')
The problem is here:
print(sum(bmi))
The bmi variable is a number, but if you want to use sum() you need a list of numbers. Here is how you can collect a list of numbers. The .append() method adds an element to the end of a list.
bmi_list = []
...
bmi = weight / height**2
bmi_list.append(bmi)
...
while ...:
....
bmi = weight / height**2
bmi_list.append(bmi)
...
...
print(sum(bmi_list))
Note
There is also an error with bmirange(): print() is called twice. You can either put the print() inside bmirange(), or you can print() the results of bmirange(), but doing both will result in None being printed out, which I assume is not what you want.
Solution 1
def bmirange():
if bmi >= 25.0:
print('Your BMI measurement shows that you are overweight')
elif bmi <18.0:
print('Your BMI measurement shows that you are underweight')
else:
print('Your BMI measurement shows that you are in the healty weight band')
...
bmirange() # will print itself
Solution 2
def bmirange():
if bmi >= 25.0:
return 'Your BMI measurement shows that you are overweight'
elif bmi <18.0:
return 'Your BMI measurement shows that you are underweight'
else:
return 'Your BMI measurement shows that you are in the healty weight band'
...
print(bmirange()) # will not print itself