【问题标题】:ValueError: could not convert string to float: 'erght' [duplicate]ValueError:无法将字符串转换为浮点数:'erght' [重复]
【发布时间】:2021-03-21 07:41:45
【问题描述】:
n = input("enter a number:")
if (float(n))> 0:
    print('Positive') 
elif (float(n))< 0:
    print('Negative')
elif n== '0': 
    print('Zero')
else:
    print('not a number') 

除了我输入“erght”之类的内容外,一切都按预期工作。

【问题讨论】:

标签: python


【解决方案1】:

如果你输入一个字符串,那么float(n) 会抛出错误。您应该使用 try-except 块。

n = input("enter a number:")
try:
    n = float(n)
    if n>0:
        print('Positive') 
    elif n<0:
        print('Negative')
    else: 
        print('Zero')
except:
    print('not a number') 

【讨论】:

  • 不过,为了避免意外发现不相关的错误,应该是except ValueError:
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-23
  • 2018-06-13
  • 2013-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多