python - 如何解决 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
解决方案
首先,下次一定要解释你遇到了什么问题,像这样:
我无法将输入转换为数字,当我运行它时,我收到此错误:
回溯(最近一次通话最后):
文件“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}'
) 将变量的值直接打印到字符串中。这样做会让你的生活更轻松,并且更具可读性。
推荐阅读
- c# - 无法获取网格视图数据并将其存储到数据库
- java - 以编程方式创建 Maven 多模块
- html - 如何在 Angular 中完全删除图表
- javascript - 如何从 javascript 树中查找并获取最后一个孩子?
- google-cloud-platform - 标签在 GCP Console 的成本表中不可见
- amazon-web-services - 如何通过重新配置 AWS 服务器端来强制通过笔记本电脑 VPN 进行流量?
- datatable - 引导视图中的未定义变量错误
- python - 有没有办法将变量从 python 脚本传递到 bash 脚本?
- c# - Bot Framework 任务模块作为一项技能
- json - 从 React 导入 csv 数据