python3 typecast是否输入了input()值?

2024-09-30 02:33:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个雨量计降水计算器的半径为雨量计。运行脚本时,出现以下错误消息:

Type de raingauge radius [cm]: 5.0
Traceback (most recent call last):
  File "pluviometro.py", line 27, in <module>
    area_bocal = (pi * (raio_bocal * raio_bocal)) # cm.cm
TypeError: can't multiply sequence by non-int of type 'str'

我正在使用 raio_bocal = input("Type de raingauge radius [cm]:") 用于数据输入。当使用Python2时,类型转换是自动的。在

如何使用python3输入一个float值?在


Tags: 脚本消息type错误半径cmde计算器
2条回答

您需要强制转换为float,input在python3中返回一个字符串:

float(input("Type de raingauge radius [cm]:"))

使用while循环和try/except在强制转换输入时可能更安全。在

^{pr2}$

docs中所述

The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that

所以您需要显式地将其类型转换为float

raio_bocal = float(input("Type de raingauge radius [cm]:"))

相关问题 更多 >

    热门问题