Python TypeError when dividing a raw input variable by a number

前端 未结 3 682
北恋
北恋 2021-01-20 12:12

I want to convert an entered lb weight to kg and I get the following error...

TypeError: unsupported operand type(s) for /: \'unicode\' and \'float\'<

相关标签:
3条回答
  • 2021-01-20 12:48

    That's because with raw_input, the input is raw, meaning a string:

    lbweight = float(raw_input("Current Weight (lb): ") )
    
    kgweight = lbweight/2.20462
    
    0 讨论(0)
  • 2021-01-20 12:52

    raw_input returns a string, you should convert the input to float using float():

    float(raw_input("Current Weight (lb): "))
    
    0 讨论(0)
  • 2021-01-20 12:52

    Pay attention to the error message TypeError: unsupported operand type(s) for /: 'str' and 'float'

    >>> kgweight = lbweight/2.20462
    
    Traceback (most recent call last):
      File "<pyshell#17>", line 1, in <module>
        kgweight = lbweight/2.20462
    TypeError: unsupported operand type(s) for /: 'str' and 'float'
    >>> 
    

    So if 2.20462 is a float then which is a string here? What does the documentation say about raw_input?

    If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.

    0 讨论(0)
提交回复
热议问题