Understanding the code in Functions 3



In the 'square' function defined in the exercise, I noticed that on line 4 they wrote:

print "%d squared is %d." % (n, squared)

If you run the code, '%d' it becomes apparent that '%d' is a placeholder for the values in the brackets. I was just wondering how '%d' differs from '%s' as that is what Codeacademy taught to use as a placeholder.


%d is a placeholder for integers, but %s is a placeholder for strings. :slight_smile:


The placeholders specify how to format the values before they take the place of the placeholders. d formats the value as an integer, s uses default string conversion. For an integer, those will have the same outcome.

print '%d' % True  # 1


Thanks for your help @bandit @ionatan! Just out of curiosity, could %d and %s be used interchangeably?


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.