Python (2.x) multiplication is not happening properly

前端 未结 3 1892
悲&欢浪女
悲&欢浪女 2021-01-23 04:52

Here is the code ...

a=4
b=8.0
if a and a >0:
    a=a*int(b)
    print \"Value:\",a 

The desired o/p should be 32. i am also getting the sam

相关标签:
3条回答
  • 2021-01-23 05:14

    I bet you 100 bob that in your product a is not actually the integer 4, but the string '4'.

    >>> a = '4'
    >>> b=8.0
    >>> if a and a >0:
    ...     a=a*int(b)
    ...     print "Value:",a
    ... 
    Value: 44444444
    

    This will happen, for example, if you are using something like a = raw_input('Please enter a number: ') and then you forget to convert the string a into a number.

    0 讨论(0)
  • 2021-01-23 05:31

    'a' must be a string in your code:

    >>> a = 4
    >>> b = 8
    >>> a * b
    32
    >>> a = "4"
    >>> a * b
    '44444444'
    >>> int(a) * b
    32
    
    0 讨论(0)
  • 2021-01-23 05:31

    That looks like a is a string, and not an integer. Try this:

    a = int(a) * int(b)
    

    Hope that helps

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