【问题标题】:Ensuring user inputs only whole numbers when using BMI Analyzer确保用户在使用 BMI Analyzer 时仅输入整数
【发布时间】:2018-11-26 19:18:21
【问题描述】:
# 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 计算中使用该数字。

我的问题是:我如何确保用户只输入实数、没有负数或带小数点的数字,如果输入,显示和错误提示“仅使用整数”

【问题讨论】:

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


    【解决方案1】:

    使用try...except 语句。
    这些语句用于尝试程序员认为可能有错误的一段代码。然后,程序员“捕获”错误(如果有)。
    在您的情况下,输入的数字应该是自然的(不是整数,因为身高为零的 BMI 计算不正确)。

    因此,代码将是:

    print("Welcome to My BMI Calculator.\n")
    persons_name = input("Name of person that we are calculating the BMI for: ")
    try:
        inches = int(input("Enter height in inches: "))
        assert inches > 0
        inches_to_meters = inches / 39.36
        pounds = int(input("Enter weight in pounds: "))
        assert pounds > 0
        pounds_to_kilograms = pounds / 2.2
        BMI = pounds_to_kilograms / (inches_to_meters ** 2)
        print(persons_name, "BMI is:", format(BMI, ".2f" ))
        if BMI <= 18.50:
            print( 'BMI finding is the subject is: Underweight ' )
        elif 18.51 < BMI <  24.90:
            print( 'BMI finding is the subject is: Normal ' )
        elif 24.91 < BMI <  29.90:
            print("BMI finding is the subject is: Overweight")
        elif BMI > 29.90:
            print("BMI finding is the subject is: Obese")
    except ValueError:
        print("Enter only natural numbers!")
    except AssertionError:
        print("Enter positive numbers only!")
    

    【讨论】:

      【解决方案2】:

      一个简单的while循环应该适合你:

      inches=float(input('Height in inches:'))
      while (inches<0)|(inches%1!=0):
          inches=float(input('error, use whole numbers only:'))
      inches = int(inches)
      
      Height in inches:5.2
      
      error, use whole numbers only:-182
      
      error, use whole numbers only:180
      180
      

      【讨论】:

        【解决方案3】:

        去掉float()输入转换试试:

        x=input()
        try: 
           int(x) 
        except: 
           raise ValueError('Cannot accept:', x)
        

        还强烈建议您将代码拆分为函数。

        【讨论】:

          猜你喜欢
          • 2018-06-08
          • 1970-01-01
          • 2014-01-30
          • 1970-01-01
          • 2022-10-22
          • 2020-06-27
          • 2010-10-15
          • 1970-01-01
          相关资源
          最近更新 更多