首页 > 解决方案 > 如何解决 ValueError:int() 以 10 为基数的无效文字:'1.81'?

问题描述

# Body Mass Index Calculator

def BMI_calculator( ):
    name = input('Enter your name: ')
    weight_kg = int(input('Enter your weight in kg: '))
    height_m = int(input('Enter your height in meters: '))
    print('The BMI for ' + name + ' is: ')
    BMI = int(weight_kg) / height_m ** 2
    return BMI

print(BMI_calculator())

我的错误是:

Traceback (most recent call last): 
  File "F:/Programming/Python 3 Tutorials/Tuturial/Automate the boring stuff with python/Others BMI_calculator.py", line 13, in <module>
    print(BMI_calculator())
  File "F:/Programming/Python 3 Tutorials/Tuturial/Automate the boring stuff with python/Others/BMI_calculator.py", line 7, in BMI_calculator
    height_m = int(input('Enter your height in meters: '))
ValueError: invalid literal for int() with base 10: '1.67'
Process finished with exit code 1

标签: pythonpython-3.x

解决方案


首先,下次一定要解释你遇到了什么问题,像这样:

我无法将输入转换为数字,当我运行它时,我收到此错误:

回溯(最近一次通话最后):

文件“C:/Users/Nathan/.PyCharmCE2019.2/config/scratches/scratch_35.py”,第 13 行,在

print(BMI_calculator())

文件“C:/Users/Nathan/.PyCharmCE2019.2/config/scratches/scratch_35.py”,第 8 行,在 BMI_calculator

height_m = int(input('Enter your height in meters: '))

ValueError: int() 以 10 为底的无效文字:'1.81'

问题是您的输入(以米为单位)将类似于1.81,您无法将其转换为整数(因为.),因此请将其转换为浮点数,如下所示:

height_m = float(input('Enter your height in meters: '))

另一方面 ,您的 BMI 计算器要求输入我的名字,这有点奇怪,因为您不需要我的名字来计算我的 BMI。如果我要重写你的代码,我会这样做:

# Body Mass Index Calculator

def BMI_calculator(weight_kg, height_m):
    BMI = int(weight_kg / height_m ** 2)
    return BMI

# Only run this code if your run this file
# This allows for easy importing of BMI_calculator in other files
if __name__ == '__main__':
    # Get the inputs to your function
    name = input('Enter your name: ')
    weight_kg = float(input('Enter your weight in kg: '))
    height_m = float(input('Enter your height in meters: '))

     # Calculate BMI
    bmi = BMI_calculator(weight_kg=weight_kg, 
                         height_m=height_m)

    # Print the results
    print(f'The BMI for {name} is: {bmi}')

f-string ( f'lalaal {variable}') 将变量的值直接打印到字符串中。这样做会让你的生活更轻松,并且更具可读性。


推荐阅读