【问题标题】:I have a weird issue of python when i am trying to use pycharm当我尝试使用 pycharm 时,我遇到了一个奇怪的 python 问题
【发布时间】:2018-07-27 08:38:34
【问题描述】:

我用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:

不确定问题出在哪里。有人遇到过这个问题吗?

【问题讨论】:

  • 我猜他们被配置为使用不同的python版本。你用的是哪一个?
  • pi_float = float(pi_string) LINK
  • 在转换前尝试print(centimetre)
  • @R.García 不是很有帮助,因为发布的代码本身是正确的
  • 我在默认的 python3.6 IDLE 中尝试了这些代码它仍然有效

标签: python string input floating-point


【解决方案1】:

您可以尝试使用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.')

【讨论】:

    【解决方案2】:

    您可能在输入时使用了错误的小数分隔符。也许逗号“,”而不是句号“。”

    您需要替换它或捕获错误(或两者一起)。我建议:

    try:
        centimetre = float(centimetre.replace(',', '.'))
    except ValueError:
        print('Input is not a valid number or in invalid format!')
    

    【讨论】:

    • 我自己试了一下:>>> a = input() >>> a '1,3' >>> float(a) Traceback (最近一次调用最后一次): File "”,第 1 行,在 ValueError: could not convert string to float: '1,3'
    【解决方案3】:

    我尝试了几天来修复它并解决了这个问题
    我在 pycharm 中创建了一个全新的项目,并将代码放在一个新文件中。
    现在可以使用了
    如果您只是将代码复制并粘贴到现有的 pycharm 项目中,它可能不起作用
    不知道为什么,但至少这不是我的代码的错,它现在可以工作了。

    【讨论】:

    • 一个词(可能):编码:-)
    【解决方案4】:

    试试这个:

    centimetre = float(input('Please enter centimetre:'))
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-01
    • 2019-05-15
    • 2020-12-12
    • 1970-01-01
    • 2019-05-21
    • 1970-01-01
    • 2020-08-27
    • 2017-12-07
    相关资源
    最近更新 更多