Building useful classes - Question



<Below this line, add a link to the EXACT exercise that you are stuck at.>

<In what way does your code behave incorrectly? Include ALL error messages.>
My code doesn’t have any problem and I’ve solved it correctly. My question is about the return statement. When returning/printing this way, we usually use %s. But why did we use %d? What is the difference between those two and are they any others that are different than %s?

<What do you expect to happen instead?>


class Point3D(object):

def __init__(self, x, y, z):
    self.x = x
    self.y = y
    self.z = z
def __repr__(self):
    return "(%d, %d, %d)" % (self.x, self.y, self.z)

my_point = Point3D(1, 2, 3)
print my_point

<do not remove the three backticks above>


%s is for a string. %d then is for a number (more specifically, it accepts a “signed integer decimal” number). The coordinates are numbers. Correct? So you have a choice to make:

  • You can convert their data type from integer to string using str(), which then your code would be:
return "(%s, %s, %s)" % (str(self.x), str(self.y), str(self.z))
  • -or- You can use the formatted placeholder of %d, which accepts a “signed integer decimal” and places it into a string.

There are a lot of string formatters that handle the data type conversions for you. Click here to read the Python documentation.

Does that make sense?


Could you also use %s and %d at the same time?
For example: return “(%s, %d, %s)” % (str(self.x), self.y, str(self.z))
Would this run properly or would it generate an error?


Absolutely. Think about why. What are those placeholders doing?

%s is a string placeholder. It expects you to give it a value with the string data type

%d is a signed integer decimal placeholder. It takes your integer and converts it into a string, inserting that converted integer into the formatted string where you place it.

A better practice is to use the proper string formatters for the data you are given as I indicated here:

Why? It’s more readable. Wouldn’t you agree?


Yes, thank you for helping me understand!


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