【问题标题】:Does python3 typecast entered input() value?python3 类型转换是否输入了 input() 值?
【发布时间】:2015-03-28 14:53:23
【问题描述】:

我正在编写一个基于雨量计半径的雨量计降水计算器。当我运行我的脚本时,我收到以下错误消息:

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 值?

【问题讨论】:

    标签: python python-3.x input


    【解决方案1】:

    docs中所述

    然后该函数从输入中读取一行,将其转换为字符串(去除尾随的换行符),然后返回

    所以你需要明确地将其类型转换为float

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

    【讨论】:

      【解决方案2】:

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

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

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

      while True:
         inp = input("Type de raingauge radius [cm]:")
         try:
             raio_bocal  = float(inp)
             break
         except ValueError:
             print("Invalid input")
      

      【讨论】:

        猜你喜欢
        • 2010-12-25
        • 2018-01-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-01
        • 2017-03-27
        • 1970-01-01
        相关资源
        最近更新 更多