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)
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'm building a BMI Calculator in Python and after choosing the metric or imperial system it won't post. The code is 100% functional other than that.
I added the option to choose if you want to use the imperial system or the metric system.
How could I improve the code?
def WeightCalMetric() :
print("BMI-Calculator")
while True:
try:
UserHeight = float(input("What's your height in meters? "))
break
except:
print("Your height has to be a number")
while True:
try:
UserWeight = float(input("What's your weight in Kg? "))
break
except:
print("Your weight has to be a number")
Bmi = UserWeight / (UserHeight ** 2)
FloatBmi = float("{0:.2f}".format(Bmi))
if FloatBmi <= 18.5:
print('Your BMI is', str(FloatBmi),'which means you are underweight.')
elif FloatBmi > 18.5 and FloatBmi < 25:
print('Your BMI is', str(FloatBmi),'which means you are a healthy weight.')
elif FloatBmi > 25 and FloatBmi < 30:
print('your BMI is', str(FloatBmi),'which means you are overweight.')
elif FloatBmi > 30:
print('Your BMI is', str(FloatBmi),'which means you are obese.')
def WeightCalImperial() :
print("BMI-Calculator")
while True:
try:
UserHeight = float(input("What's your height in inches? "))
break
except:
print("Your height has to be a number")
while True:
try:
UserWeight = float(input("What's your weight in Lbs? "))
break
except:
print("Your weight has to be a number")
Bmi = 703 * (UserWeight / (UserHeight ** 2))
FloatBmi = float("{0:.2f}".format(Bmi))
if FloatBmi <= 18.5:
print('Your BMI is', str(FloatBmi),'which means you are underweight.')
elif FloatBmi > 18.5 and FloatBmi < 25:
print('Your BMI is', str(FloatBmi),'which means you are a healthy weight.')
elif FloatBmi > 25 and FloatBmi < 30:
print('your BMI is', str(FloatBmi),'which means you are overweight.')
elif FloatBmi > 30:
print('Your BMI is', str(FloatBmi),'which means you are obese.')
print("Hi welcome to this BMI Calculator")
print("First choose if you want to use the metric system or the imperial system")
print('Write "Metric" for the metric system or write "Imperial" for the imperial system')
KgOrLbs = None
while KgOrLbs not in ("metric", "Metric", "imperial", "Imperial"):
KgOrLbs = input("Metric or Imperial? ")
if KgOrLbs == "metric, Metric":
WeightCalMetric()
elif KgOrLbs == "imperial" "Imperial":
WeightCalImperial()
I'm supposed to add more details, but I don't really have any more details, to be honest, so now I'm just writing all of this just so I can post this
You should change the while loop where you check the inputs. The code below lowercases the input and checks whether it is "metric" or "imperial", so there is no need to check for capitalized parameters
KgOrLbs = input("Metric or Imperial? ")
while KgOrLbs.lower() not in ["metric", "imperial"]:
KgOrLbs = input("Metric or Imperial? ")
if KgOrLbs.lower() == "metric":
WeightCalMetric()
elif KgOrLbs.lower() == "imperial":
WeightCalImperial()
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()
Hi all! My goal is to loop age so that male_cal or fem_cal (implicit) print correctly. Please help! Much thanks --> Pythonidaer <--
print("\nWelcome to the Daily Caloric Intake Calculator!")
I don't know how to loop age like I did sex.
age = int(input("\nHow old are you in years? "))
sex = input("\nAre you a male or a female? Enter 'male' or 'female'. ").lower()
if sex == "female" or sex == "f":
sex = "female"
elif sex == "male" or sex == "m":
sex = "male"
else:
sex = input("Sorry, there's only two choices: MALE or FEMALE. ").lower()
The equation requires age be an integer. How can I foolproof?
height = float(input("\nHow tall are you in inches? "))
metric_height = float(height * 2.54)
weight = float(input("\nWhat is your weight in pounds? "))
metric_weight = int(weight * 0.453592)
activity_level = float(input("""
Please select your activity level:
Sedentary (enter '1.2')
Moderatively Active (enter '1.3')
Active? (enter '1.4')
"""))
male_cal = 10 * metric_weight + 6.25 * metric_height - 5 * age - 161
fem_cal = 10 * metric_weight + 6.25 * metric_height - 5 * age + 5
if (sex == "male"):
carbs = int(male_cal * .45)
protein = int(male_cal * .20)
fats = int(male_cal * .35)
print("\nYour DCI should be: ", int(male_cal), "calories a day.")
print(f"""\nThat means getting:
{carbs} cals from carbs,
{fats} cals from fats, and
{protein} cals from protein.""")
elif (sex == "female"):
carbs = int(fem_cal * .45)
protein = int(fem_cal * .20)
fats = int(fem_cal * .35)
print("\nYour DCI should be: ", int(fem_cal), "calories a day.")
print(f"""\nThat means getting:
{carbs} cals from carbs,
{fats} cals from fats, and
{protein} cals from protein.""")
while True:
try:
age = int(input("\nHow old are you in years? "))
break
except ValueError:
print('please put in a number')
This should do the Trick
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