Adding floating numbers in python - python

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

Related

Variables aren't passing from one function to another why?

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.

How do you add user counter to BMI calculator?

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

BMI Index in Python

I need help with doing the code for my homework, I have a feeling I could be missing something, your help/feedback would be greatly appreciated!
Sincerely
Meredith
def calc_BMI():
weight=requestNumber("Enter weight (kg)")
height=requestNumber("Enter Height (meters)")
bmi=(weight/(height*height))
print 'Your BMI in %2f' % bmi
if bmi=<15
print('Your weight status is Very Severely Underweight')
elif bmi>=15.0 and bmi<=16.0
print ('Your weight status is Severely Underweight')
elif bmi>=16.0 and bmi<=18.5
print ('Your weight status is Underweight')
elif bmi>= 18.5 and bmi <=25
print('Your weight staus is Normal')
elif bmi >=25 and bmi <=30
print ('Your weight status is Overweight')
elif bmi>=30 and bmi <=35
print ('Your weight status is Moderately Obese')
elif bmi >=35 and bmi<=40
print ('Your weight status is Severely Obese')
elif bmi <=40
print ('Your weight status is Very Severely Obese')
Your code has multiple issue:
Will list them out here:
requestNumber is not a method in python. Either import a library which has this method. Or use the default input method.
weight = requestNumber("Enter weight (kg)")
instead
weight = input("Enter weight (kg)")
at the end of if coundition you should have a ':'
eg: if bmi <= 15:
Also if bmi=<15 is wrong. it should be if bmi <= 15:
remove the enter code here part from your questions.
elif bmi >=35 and bmi<=40 enter code here
Bug in your code in the last but 1 line. It should be >=
elif bmi <=40
print ('Your weight status is Very Severely Obese')
Working code:
def calc_BMI():
weight = input("Enter weight (kg)")
height = input("Enter Height (meters)")
bmi = (int(weight)/(float(height)**2))
print('Your BMI in %2f' % bmi)
if bmi <= 15:
print('Your weight status is Very Severely Underweight')
elif bmi >= 15.0 and bmi <= 16.0:
print ('Your weight status is Severely Underweight')
elif bmi >= 16.0 and bmi<= 18.5:
print ('Your weight status is Underweight')
elif bmi >= 18.5 and bmi <= 25:
print('Your weight staus is Normal')
elif bmi >= 25 and bmi <= 30:
print('Your weight status is Overweight')
elif bmi >= 30 and bmi <= 35:
print('Your weight status is Moderately Obese')
elif bmi >= 35 and bmi <= 40:
print('Your weight status is Severely Obese')
elif bmi >= 40:
print('Your weight status is Very Severely Obese')
Output:
calc_BMI()
Enter weight (kg)78
Enter Height (meters)1.8
Your BMI in 24.074074
Your weight staus is Normal
Helpful notes:
Try to follow coding convention like pep-8 maybe [Link]
Indent your code properly. See how I have added space before and after '>='. This is also a part of pep-89 convention.
eg: if weight >= 40:
There were several errors in your code,I have commented the problems:
def calc_BMI():
weight=int(input("Enter weight (kg)"))#make sure value taken is int
height=float(input("Enter Height (meters)"))#make sure value taken is float
bmi=(weight/(height**2))#use the power operator for squaring instead
print ('Your BMI in %2f' % bmi)
if bmi <= 15 :#colon eexpected
print('Your weight status is Very Severely Underweight')
elif bmi>=15.0 and bmi<=16.0:#colon eexpected
print ('Your weight status is Severely Underweight')
elif bmi>=16.0 and bmi<=18.5:#colon eexpected
print ('Your weight status is Underweight')
elif bmi>= 18.5 and bmi <=25 :#colon eexpected
print('Your weight staus is Normal')
elif bmi >=25 and bmi <=30:#colon eexpected
print ('Your weight status is Overweight')
elif bmi>=30 and bmi <=35:#colon eexpected
print ('Your weight status is Moderately Obese')
elif bmi >=35 and bmi<=40:#colon eexpected
print ('Your weight status is Severely Obese')
else:#no need for a elif,rather use else for the rest
print('Your weight status is Very Severely Obese')
calc_BMI()# call the function to run

Im tring to make a BMI BMR calculator in Pythion3

well i am trying to make a bmi & bmr calculator.
I have got the code down yet when i select bmi, it goes through the bmi process then immediately after it has finished it runs the mbr, then the program crashes?
HALP?
#menu
#Ask weather to print BMI or BMR
output = str(input('Calulate BMI or BMR or Exit: '))
print (output)
#BMI
if output == 'BMI' or 'bmi':
#Get height and weight values
height = int(input('Please enter your height in inches: '))
weight = int(input('Please enter your weight in pounds: '))
#Do the first steps of the formula
heightSquared = (height * height)
finalWeight = (weight * 703)
#Fiqure out and print the BMI
bmi = finalWeight / heightSquared
if bmi < 18:
text = 'Underweight'
if bmi <= 24: # we already know that bmi is >=18
text = 'Ideal'
if bmi <= 29:
text = 'Overweight'
if bmi <= 39:
text = 'Obese'
else:
text = 'Extremely Obese'
print ('Your BMI is: ' + str(bmi))
print ('This is: ' + text)
#bmr
if output == 'bmr' or 'BMR':
gender = input('Are you male (M) or female (F) ')
if gender == 'M' or 'm':
#Get user's height, weight and age values.
height = int(input('Please enter your height in inches'))
weight = int(input('Please enter your weight in pounds'))
age = int(input('Please enter your age in years'))
#Figure out and print the BmR
bmr = 66 + (6.2 * weight) + (12.7 * height) - (6.76 * age)
print (bmr)
if gender == 'F' or 'f':
#Get user's height, weight and age values.
height = int(input('Please enter your height in inches'))
weight = int(input('Please enter your weight in pounds'))
age = int(input('Please enter your age in years'))
#Figure out and print the BmR
bmr = 655 + (4.35 * weight) + (4.7 * height) - (4.7 * age)
print (bmr)
#exit
elif output == 'exit' or 'Exit' or 'EXIT':
exit()
Any help is welcome!
Cheers!
There are many bugs or inconsistencies within your code, here are a few main ones.
The or logical operator cannot be used like that, this is most prominent in the main if statements. Here is a tutorial to get you started on that.
The if and elif are very badly used, if is for a condition, elif is run if the subsequent if hasn't been satisfied, and if the code within the elif has, while the third one, else is more of a default statement, per se, if nothing was satisfied go to this one. Here is some documentation about it.
You are reusing the same code way too much, this should be fixed.
There are a few other tidbits that will show themselves in the code below, I've heavily commented the code so you can understand it thoroughly.
# Menu
# Ask whether to print BMI, BMR, or to exit
output = str(input('Calulate BMI or BMR or Exit: '))
print ('You entered: ' + output) # Try not to print 'random' info
# Exit, I put it up here to make sure the next step doesn't trigger
if output == 'exit' or output == 'Exit' or output == 'EXIT':
print('Exiting...') # Try to always notify the user about what is going on
exit()
# Check if the input is valid
if output != 'BMI' and output != 'bmi' and output != 'BMR' and output != 'bmr':
print('Please enter a valid choice.')
exit()
# Get user's height, weight and age values
# Never write code more than once, either place it in a function or
# take it elsewhere where it will be used once only
height = int(input('Please enter your height in inches: '))
weight = int(input('Please enter your weight in pounds: '))
# BMI
if output == 'BMI' or output == 'bmi':
# Do the first steps of the formula
heightSquared = (height * height)
finalWeight = (weight * 703)
# Figure out and print the BMI
bmi = finalWeight / heightSquared
if bmi < 18: # First step, is it less than 18?
text = 'Underweight'
elif bmi <= 24: # If it isn't is it less than or equal to 24?
text = 'Ideal'
elif bmi <= 29: # If not is it less than or equal to 29?
text = 'Overweight'
elif bmi <= 39: # If not is it less than or equal to 39?
text = 'Obese'
else: # If none of the above work, i.e. it is greater than 39, do this.
text = 'Extremely Obese'
print ('Your BMI is: ' + str(bmi))
print ('This is: ' + text)
# BMR
elif output == 'bmr' or output == 'BMR':
gender = str(input('Are you male (M) or female (F): '))
age = int(input('Please enter your age in years: '))
bmr = 0 # Initialize the bmr
if gender == 'M' or gender == 'm':
# Figure out and print the BMR
bmr = 66 + (6.2 * weight) + (12.7 * height) - (6.76 * age)
if gender == 'F' or gender == 'f':
# Figure out and print the BMR
bmr = 655 + (4.35 * weight) + (4.7 * height) - (4.7 * age)
print ('Your BMR is: ' + bmr)

How to add a counter function?

So i need to count how many times BMI is calculated and for it to print at the end of this loop. Any ideas?
print("Hello and welcome to the BMI calculator!!")
user = input("Would you like to go again, Y/N: ")
while user == "y":
height = int(input("Please put in your height in Meters: "))
weight = int(input("Please put in your weight in Kilogram: "))
BMI = weight/ (height*height)
if BMI < 18:
print("Your BMI is:", BMI, "Eat some more Big Macs, you are too skinny!")
elif BMI > 25:
print("Your BMI is:", BMI, "Stop eating all those Big Macs, you are far too fat!")
elif BMI >18 < 25:
print("Your BMI is:", BMI, "You are a normal and healthy weight, congratulations!!!")
user = input("Would you like to go again, Y/N: ")
input("\nPress the enter key to exit")
Fairly simple. Just make a variable outside the loop, and increment it every time the loop begins.
print("Hello and welcome to the BMI calculator!!")
count = 0;
user = input("Would you like to go again, Y/N: ")
while user == "y":
count += 1 #Increase count by one
height = int(input("Please put in your height in Meters: "))
weight = int(input("Please put in your weight in Kilogram: "))
BMI = weight/ (height*height)
if BMI < 18:
print("Your BMI is:", BMI, "Eat some more Big Macs, you are too skinny!")
elif BMI > 25:
print("Your BMI is:", BMI, "Stop eating all those Big Macs, you are far too fat!")
elif BMI >18 < 25:
print("Your BMI is:", BMI, "You are a normal and healthy weight, congratulations!!!")
user = input("Would you like to go again, Y/N: ")
print("You checked your BMI", count, "times.")
input("\nPress the enter key to exit")

Categories