10 August 2010

Common python gotcha

  1. Unlike Java, the '+' does not automatically convert numbers or other types to string form. The str() function converts values to a string form so they can be combined with other strings. For example:


      pi = 3.14
      ##text = 'The value of pi is ' + pi      ## NO, does not work
      text = 'The value of pi is '  + str(pi)  ## yes
  2. There is no ++ operator, but +=, -=, etc. work. If you want integer division, it is most correct to use 2 slashes -- e.g. 6 // 5 is 1 (previous to python 3000, a single / does int division with ints anyway, but moving forward // is the preferred way to indicate that you want int division.)

No comments: