1

I wrote a length converter with python, here are the codes:

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

It's ok when these codes run with notepad++ and http://www.pythontutor.com/

but when I try to use pycharm, it got error:

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

not sure where is the problems. Has anyone met this issue?

Peter Majko
  • 1,241
  • 11
  • 22

4 Answers4

1

You could try checking if the input is able to be converted into a float, using try:.
And, also, if it's an issue with Python not recognizing commas as a decimal point, and maybe periods as a thousands separator, then you could check for if the number with commas and periods swapped (using the .replace() method).

An example of this is:

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.')

RookieCoder
  • 171
  • 1
  • 6
0

You are probably using wrong decimal separator on input. Perhaps comma "," instead of full stop "."

You need to replace that or catch the error (or both together). I suggest:

try:
    centimetre = float(centimetre.replace(',', '.'))
except ValueError:
    print('Input is not a valid number or in invalid format!')
Peter Majko
  • 1,241
  • 11
  • 22
  • I tried it out by myself: >>> a = input() >>> a '1,3' >>> float(a) Traceback (most recent call last): File "", line 1, in ValueError: could not convert string to float: '1,3' – Peter Majko Jul 27 '18 at 08:56
0

i tried days to fix it and have solved this issue
i created a brand new project in pycharm and put the code in a new file.
it works now
if you just copy and paste the code to existed pycharm project, it might not work
not sure why, but at least it's not my codes' fault and it works now.

-1

Try this:

centimetre = float(input('Please enter centimetre:'))
Hayat
  • 1,539
  • 4
  • 18
  • 32