python - 确保用户在使用 BMI 分析器时只输入整数

标签 python string if-statement idl-programming-language

# 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/

相关文章:

python - Conda 更新除 python 之外的软件包

编写单行长字符串的 Pythonic 方式

javascript - 为什么这个 if 语句在 for 循环内创建一个未定义的值?

c - 获取序列的递归函数无法正常工作

python - 作为服务让 PubNub 订阅者保持事件状态 (Python SDK)

python - 更改多索引数据帧较低级别中的多个值

c++ - 对 std::string 数组进行二进制搜索

java - Java从二进制文件中读取字符串

python - 根据其中一个值从元组列表中删除重复项

swift - 条件语句的预期声明