# This program calculates a person's BMI after
# user inputs their height and weight, it then converts
# the data from inches to meters and pounds to kilograms.
# Based on findings the program displays persons BMI
# Display welcome message.
print( "Welcome to My BMI Calculator \n " )
# Ask the user to input their name.
persons_name = input( 'Name of person that we are calculating the BMI for: ' )
# Ask for the user's height in inches.
inches = float(input( 'Supply Height in Inches: ' ))
# Ask for the user's weight in pounds.
pounds = int(input( 'Supply Weight in Pounds: ' ))
# Convert from inches to meters
inches_to_meters = float(inches / 39.36)
# Convert from pounds to kilograms
pounds_to_kilograms = float(pounds / 2.2)
# Calculate the person's BMI
BMI = float(pounds_to_kilograms / ( inches_to_meters * inches_to_meters ))
# Display the BMI
print( persons_name, 'BMI is:' , format(BMI, '.2f' ))
# Display person's BMI findings based on the given data
if BMI <= 18.50:
print( 'BMI finding is the subject is: Underweight ' )
elif BMI > 18.51 < 24.90:
print( 'BMI finding is the subject is: Normal ' )
elif BMI > 24.91 < 29.90:
print( 'BMI finding is the subject is: Overweight ' )
elif BMI > 29.90:
print( 'BMI finding is the subject is: Obese ' )
如果我在粘贴此代码后格式错误,我提前道歉。如果错了,请告诉我,所以我在这个网站上学习了如何正确格式化它。据我了解,我每行缩进 4 个空格。
这是一个 BMI 分析程序,它以英寸为单位计算人的高度并将其转换为米,以磅为单位计算人的体重并将其转换为千克。
经过测试,它似乎可以工作,但前提是您输入整数。因此,如果您为体重输入 0 或为高度输入 0,则不会出现错误,而是会在 BMI 计算中使用该数字。
我的问题是:我如何确保用户只输入实数,没有负数或带小数点的数字,如果输入,显示并错误提示“仅使用整数”
最佳答案
摆脱输入的float()
转换并尝试:
x=input()
try:
int(x)
except:
raise ValueError('Cannot accept:', x)
还强烈建议将您的代码拆分为函数。
关于python - 确保用户在使用 BMI 分析器时只输入整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50901077/