Previous topic

Fermi-Dirac Integrals

Next topic

Python Techniques

This Page

Python GotchasΒΆ

What is the output of the following function? Why?

::
>>> def f(x):
...     print("3*x = %s" % 3*x)
>>> f(5)
3*x = 33*x = 33*x = 33*x = 33*x = 3
Answer:
Look at the operator precedence: % has higher precedence that *, so the print statement is parsed as print(("3*x = %s" % 3)*x) which means, print x copies of the string. The fix is recommended in the manual: always use a tuple after %: print("3*x = %s" % (3*x,))