Understanding the code in Functions 3


#1


https://www.codecademy.com/courses/python-beginner-c7VZg/1/2?curriculum_id=4f89dab3d788890003000096

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.


#2

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


#3

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

#4

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


#5

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