首页 > 解决方案 > 当我尝试使用 pycharm 时,我遇到了一个奇怪的 python 问题

问题描述

我用python写了一个长度转换器,代码如下:

active = True
while active:
    option = input('please choose:\na:centimetre to inch \nb:inch to centimetre:')
    if option == "a":
        centimetre = input('Please enter centimetre:')
        centimetre= float (centimetre)
        inch = centimetre / 2.54
        print(str(centimetre) + ' centimetre equals' + str(inch) + ' inches')

    elif option == "b": 
        inch = input('Please enter inch:')
        inch = float ( inch )
        centimetre = inch * 2.54
        print(str(inch) + ' inch equals ' + str(centimetre) + ' centimetre')

    else:
        print("sorry you entered wrong option。please enter 'a'or'b': ")
        continue  

    status = input('continue? yes/no :')
    if status == 'no':
        active = False

这些代码在notepad++和 http://www.pythontutor.com/上运行就可以了

但是当我尝试使用pycharm时,出现错误:

line 6, in <module>
centimetre= float (centimetre)
ValueError: could not convert string to float:

不知道问题出在哪里。有没有人遇到过这个问题?

标签: pythonstringinputfloating-point

解决方案


您可以尝试检查输入是否能够转换为浮点数,使用try:.
而且,如果 Python 无法将逗号识别为小数点,并且可能将句点识别为千位分隔符是一个问题,那么您可以检查是否交换了逗号和句点的数字(使用该.replace()方法)。

这方面的一个例子是:

x = '2.3'
y = '3,4'


def isnumber(num):
    try:
        float(num)
        return True
    except ValueError:
        try:
            float(num.replace(',', 'A').replace('.', 'B').replace('A', '.').replace('B', ','))
            return True
        except ValueError:
            return False


if isnumber(x):
    print(f'The number {x} is valid.')
else:
    print(f'The number {x} is not valid.')

print()

if isnumber(y):
    print(f'The number {y} is valid.')
else:
    print(f'The number {y} is not valid.')


推荐阅读