ValueError:无法将字符串转换为简单cod中的float

2024-09-24 22:31:57 发布

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

       # -*- coding: cp1250 -*-
print ('euklides alpha 1.0')
a = raw_input('podaj liczbę A  : ')
b = raw_input('podaj liczbę B  : ')

a = float('a')
b = float('b')

if 'a'=='b':
    print 'a'
elif 'a' > 'b':
    while 'a' > 'b':
        print('a'-'b')
        if 'a'=='b': break
        if 'a' > 'b': continue
elif 'b' > 'a':
    while 'b' > 'a':
        print('b'-'a')
        if 'b'=='a': break
        if 'b' > 'a': continue

这是我几个小时前写的代码。现在我得到了一个ValueError: could not convert string to float: a,我不知道为什么。你能给我解释一下吗?我是初学者。在


Tags: alphainputrawiffloatprintbreakelif
2条回答

您将所有变量括在单引号中,因此比较字符串"a"与字符串"b",而不是将变量a中包含的浮点数与变量{}中的相同

同样值得指出的是:

这是您的原始代码,用于向用户请求两个浮点数

a = raw_input('podaj liczbę A  : ')
b = raw_input('podaj liczbę B  : ')
a = float(a)
b = float(b)

如果您使用的是Python 2.x,则可以使用

我在下面的评论中被abarnert更正了。只是为了教化:

I wouldn't suggest using input instead of raw_input and float. The latter guarantees that you get floats; the former could get, say, the result of calling __import__('os').system('rm -rf /'), which is probably something you don't want

^{pr2}$

如果不是,则可能需要包含try/catch块,该块将强制变量为您需要的类型

a_verifying = True
while a_verifying:
  a = input('podaj liczbę A  : ')
  try:
    a = float(a)
    a_verifying = False
  except ValueError as e:
    a = input('podaj liczbę A  : ')

b_verifying = True
while b_verifying:
  b = input('podaj liczbę B  : ')
  try:
    b = float(b)
    b_verifying = False
  except ValueError as e:
    b = input('podaj liczbę B  : ')

浮点函数可以接受字符串,但必须包含可能有符号的十进制数或浮点数。您希望使变量a成为浮点,而不是字符'a'。在

您不需要在变量名周围加上'。当你在它们周围加上引号'b'你就是在把它们变成一个字符串。在

另一个注意事项是,一旦你接触到那些while语句,就没有什么能让你走出困境。在

a = float(a)


if a == b: # you need to get rid of all the ' unless you are talking about chars 



   # -*- coding: cp1250 -*-
print ('euklides alpha 1.0')
a = raw_input('podaj liczbę A  : ')
b = raw_input('podaj liczbę B  : ')

a = float('a')
b = float('b')

if a==b:
    print a
elif a > b:
    while a > b: # nothing will get you out of the while loop
        print(a-b)
        if a == b:
            break
        if a > b: # no need for this if, the while loop will do that check for you
            continue
elif b > a:
    while b > a: # nothing will get you out of the while loop
        print(b-a)
        if b==a:
            break
        if b > a: # no need for this if, the while loop will do that check for you
            continue

相关问题 更多 >