I cannot get the healthindex function to work. Even when I input b or h, nothing happens the while loop does not execute. I tried to make it so the input would make two seperate segments of code happen based on the input, but that is not happening. Thank you!
def inputM():
print("Enter weight in kg")
weightm = float(input())
print("Enter heigh 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 (BMIList, BMINum, bmi):
if healthy == "b":
print (str(bmi))
elif healthy == "h":
index = 0
print ("Your bmi is" + (str(bmi))
while index < len(BMIList):
if bmi < BMINum[index]:
print ("And, you are " + BMIList[index])
return
index = index + 1
print("You are Obese")
return
BMIList = ["severly underweight", "underweight", "healthy", "overweight", "obese"]
BMINum = [12, 18.4, 24.9, 29.9, 200]
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 health index")
healthy= input()
healthindex (BMIList, BMINum, bmi)
You should also pass healthy variable to the healthindex function
healthindex (BMIList, BMINum, bmi, healthy)
Full code
def inputM():
print("Enter weight in kg")
weightm = float(input())
print("Enter heigh 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 (BMIList, BMINum, bmi, healthy):
if healthy == "b":
print (str(bmi))
elif healthy == "h":
index = 0
print ("Your bmi is " + (str(bmi)))
while index < len(BMIList):
if bmi < BMINum[index]:
print ("And, you are " + BMIList[index])
return
index = index + 1
print("You are Obese")
return
BMIList = ["severly underweight", "underweight", "healthy", "overweight", "obese"]
BMINum = [12, 18.4, 24.9, 29.9, 200]
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 health index")
healthy= input()
healthindex (BMIList, BMINum, bmi, healthy)
...
def healthindex (preference, bmi):
if preference == "b":
print (str(bmi))
elif preference == "h":
index = 0
print ("Your bmi is" + (str(bmi)))
while index < len(BMIList):
if bmi < BMINum[index]:
print ("And, you are " + BMIList[index])
return
index = index + 1
print("You are Obese")
return
...
healthindex (healthy, bmi)
... refers to unchanged codes
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()
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)
let me change the question. how would i extract all of users information(score, class number and score) from a desired class. for e.g i want to know all the users info in lets class number 1.
to help, schooldata[x]['class_code'] = the class number the user types schooldata[x]['score'] = the score obtained by that student
schooldata[x]['name'] = name of that user
[x] is the student so the first user would be [0], 2nd user [1] etc...
schooldata = []
for x in range (0,3): #the number of loops the quiz is run which is 3 times
score = 0
quiz = dict()
print ("Enter your name")
quiz['name'] = input()
print ("what class")
quiz['class_code'] = input()
print("1. 9+10=")
answer = input()
answer = int(answer)
if answer == 19:
print("correct")
score = score + 1
else:
print("wrong")
print("2. 16+40=")
answer = input()
answer = int(answer)
if answer == 56:
print("correct")
score = score + 1
else:
print("wrong")
print("3. 5+21=")
answer = input()
answer = int(answer)
if answer == 26:
print("correct")
score = score + 1
else:
print("wrong")
print("4. 5-6=")
answer = input()
answer = int(answer)
if answer == -1:
print("correct")
score = score + 1
else:
print("wrong")
print("5. 21-9=")
answer = input()
answer = int(answer)
if answer == 12:
print("correct")
score = score + 1
else:
print("wrong")
print("6. 12-11=")
answer = input()
answer = int(answer)
if answer == 1:
print("correct")
score = score + 1
else:
print("wrong")
print("7. 5*6=")
answer = input()
answer = int(answer)
if answer == 30:
print("correct")
score = score + 1
else:
print("wrong")
print("8. 1*8=")
answer = input()
answer = int(answer)
if answer == 8:
print("correct")
score = score + 1
else:
print("wrong")
print("9. 4*6=")
answer = input()
answer = int(answer)
if answer == 24:
print("correct")
score = score + 1
else:
print("wrong")
print("10. 9*10=")
answer = input()
answer = int(answer)
if answer == 90:
print("correct")
score = score + 1
else:
print("wrong")
quiz['score'] = score
schooldata.append(quiz)
print ("name - ", schooldata[0]['name'],", user score - ", schooldata[0]['score'],", class number - ", schooldata[0]['class_code'])
print ("name - ", schooldata[1]['name'],", user score - ", schooldata[1]['score'],", class number - ", schooldata[1]['class_code'])
print ("name - ", schooldata[2]['name'],", user score - ", schooldata[2]['score'],", class number - ", schooldata[2]['class_code'])
#high to low
sorted_schooldata = sorted(schooldata, key=lambda k: k['score'])[::-1]
#alphabetical
for i in sorted(schooldata, key=lambda k: k['name']):
print('%s:%s' %(i['name'], i['score']))
Updating answer based on updated question:
classdata = {}
for data in schooldata:
if classdata.get(data['class_code']):
classdata[data['class_code']].append(data)
else:
classdata[data['class_code']] = [data]
print classdata
To print class data (in orderly manner):
for class_data in sorted(classdata):
for person_data in sorted(classdata[class_data], key=lambda x: x['name']):
print person_data['class_code'], person_data['name'], person_data['score']
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")