【问题标题】:Can't convert string to float in Python无法在 Python 中将字符串转换为浮点数
【发布时间】:2016-05-29 19:37:57
【问题描述】:

我正在尝试编写一个小程序来计算来自用户的数字。还有一些条件可以检查数字是正数还是用户只是按回车键。出于某种原因,我无法将数据变量转换为浮点数。

错误发生在第 5 行,我收到错误“ValueError:无法将字符串转换为浮点数:”我现在尝试了很多组合,并尝试在 StackOverflow 中搜索答案,但没有任何运气。

如何将输入转换为浮点数?提前感谢您的帮助!

sum = 0.0

while True:

    data = float(input('Enter a number or just enter to quit: '))

    if data < 0:
        print("Sorry, no negative numbers!")
        continue
    elif data == "":
        break
    number = data
    sum += data

print("The sum is", sum)

【问题讨论】:

  • 在解释器中,练习用不同的字符串调用float(str)。您需要了解它何时起作用以及何时引发此错误。
  • 由于某种原因,我在这里看不到问题。
  • 好点@Jasper!我现在在帖子中添加了一个问题。

标签: python


【解决方案1】:

您可以这样写,而不是让用户按 Enter 键退出:

sum = 0.0

while True:
    data = float(input('Enter a number or "QUIT" to quit: '))

    if data.upper() != "QUIT":

        if data < 0:
            print("Sorry, no negative numbers!")
            continue
        elif data == "":
            break
        number = data
        sum += data

print("The sum is", sum)

【讨论】:

    【解决方案2】:

    您不能将空字符串转换为浮点数。

    获取用户的输入,检查是否为空,如果不是,然后将其转换为浮点数。

    【讨论】:

    • @Jasper 如果你得到一个 ValueError,你仍然需要检查它是由于空输入还是其他一些虚假值,因为空输入是终止循环的特殊情况。所以我会坚持我的答案。
    • 感谢您的反馈!如何检查它是否为空?
    • 看看@MaxNoe 的回答。
    • 哦,你是对的。检查是否为空,然后try: ... except: 块中转换。
    【解决方案3】:

    您可以通过这种方式在转换为浮动之前检查数据是否为空:

    sum = 0.0
    
    while True:
    
        data = input('Enter a number or just enter to quit: ')
    
        if data != "":
            data = float(data);
            if data < 0:
               print("Sorry, no negative numbers!")
               continue
            number = data
            sum += data 
            print("The sum is", sum)
         else:
            print("impossible because data is empty")
    

    【讨论】:

      【解决方案4】:

      您必须首先检查空字符串,然后将其转换为float

      您可能还想捕捉格式错误的用户输入。

      sum = 0.0
      
      while True:
      
          answer = input('Enter a number or just enter to quit: ')
      
          if not answer:   # break if string was empty
              break
          else:        
              try:
                  number = float(data)
              except ValueError:   # Catch the error if user input is not a number
                  print('Could not read number') 
                  continue
              if number < 0:
                  print('Sorry, no negative numbers!')
                  continue
              sum += data
      
      print('The sum is', sum)
      

      在 python 中,'' 之类的空值与False 之类的比较,在与if not &lt;variable&gt;if &lt;variable&gt; 进行比较时使用它是惯用的。

      这也适用于空列表:

      >>> not []
      True
      

      对于None

      >>> not None
      True
      

      几乎所有其他可以被描述为空或未定义的东西,如None

      【讨论】:

      • 由于 OP 对 Python 来说似乎很新,您可能需要解释一下 if not answer 成语。
      猜你喜欢
      • 2020-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-30
      • 2021-01-11
      • 2018-04-23
      • 2020-11-19
      • 2015-03-25
      相关资源
      最近更新 更多