Search code examples
pythonpython-3.xstring-formatting

Why is it a TypeError to use an arithmetic expression in %-style print formatting?


I tried to input a float number and output a simple result using two methods:

t = float(input())
print('{:.2f}'.format(1.0 - 0.95 ** t))
print('%.2f' % 1.0 - 0.95 ** t)

The first method worked but a TypeError occurred in the second one:

unsupported operand type(s) for -: 'str' and 'float'.

What's wrong with that?


Solution

  • On this line: print('%.2f' % 1.0 - 0.95 ** t)

    Python is trying to do '%.2f' % 1.0 first, then subtracting 0.95 ** t from the result. That's a problem because the first term is a string and the second one is a float.

    Use parentheses to control the order of operations. That line should be:

    print('%.2f' % (1.0 - 0.95 ** t))