简体   繁体   English

ValueError:无法将字符串转换为浮点型

[英]ValueError: could not convert string to float

So... I have this primitive calculator that runs fine on my cellphone, but when I try to run it on Windows 10 I get... 所以...我有一个可以在手机上正常运行的原始计算器,但是当我尝试在Windows 10上运行它时,我得到了...

ValueError: could not convert string to float ValueError:无法将字符串转换为浮点型

I don't know what the problem is, I've tried using raw_input but it doesn't work ether. 我不知道问题出在哪里,我尝试使用raw_input但是以太不起作用。 Please keep in mind I'm green and am not aware of most methods for getting around a problem like this 请记住,我是绿色的,并且不了解解决此类问题的大多数方法

num1 = float(input ()) #take a float and store it
chars = input () #take a string          and store it
num2 = float(input ())

your code only convert string that are integers like in below statement 您的代码只能转换为整数的字符串,如以下语句所示

num1 = float(input ()) #take a float and store it ex 13
print num1 # output 13.0

if you provide 13 as a input it will give the output as 13.0 but if you provide SOMEONEE as input it will give ValueError 如果您提供13作为输入,它将给出13.0的输出,但是如果您提供SOMEONEE作为输入,它将给出ValueError

And it is same with the case of raw_input() but the difference is that by default raw_input() takes input as a string and input() takes input as what is provided to the function raw_input()的情况相同,不同之处在于,默认情况下raw_input()将输入作为字符串,而input()将输入作为提供给函数的内容

I think this is happening because in some cases 'input' contains non-numerical characters. 我认为发生这种情况是因为在某些情况下,“输入”包含非数字字符。 Python is smart and when a string only contains numbers, it can be converted from string to float. Python很聪明,当字符串仅包含数字时,可以将其从字符串转换为浮点数。 When the string contains non-numerical characters, it is not possible for Python to convert it to a float. 当字符串包含非数字字符时,Python不可能将其转换为浮点数。

You could fix this a few ways: 您可以通过以下几种方法解决此问题:

  1. Find out why and when there are non-numerical characters in your input and then fix it. 找出输入内容中为何以及何时出现非数字字符的原因,然后加以解决。
  2. Check if input contains numbers only with: isdecimal() 检查输入是否仅包含带有isdecimal()的数字
  3. Use a try/except 使用try / except

isdecimal() example: isdecimal()示例:

my_input = raw_input()
if my_input.isdecimal():
    print("Ok, go ahead its all numbers")

UPDATE: Two-Bit-Alchemist had some great advice in the comments, so I put it in my answer. 更新:两位炼金术士在评论中提出了一些很好的建议,因此我将其放在答案中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM