3. Call and Response - % Operator and its multiple uses


#1

Hi.

I'm a little confused as to why the modulo operator can be used to call upon a variable that hasn't even been defined yet.

See below:

def square(n):
"""Returns the square of a number."""
squared = n**2
print "%d squared is %d." % (n, squared)
return squared

square(10)

Why does this work and how does it know what it's calling?
print "%d squared is %d." % (n, squared)


#2

I asked someone with a little expertise and they provided me an answer. Basically it calls upon a pre written formatting modifier to do a specific job, in this case '%d' calls upon an 'signed integer decimal' which to my knowledge lets your program know that it's about to process numbers and then repeat them in a certain location.

I am very new, so I can't explain this properly. For more information, check out the python libraries.

https://docs.python.org/2/library/stdtypes.html#string-formatting


#3

If it has not been defined then it can't be interacted with. Python isn't supernatural. Something else is happening.

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

is equivalent to:

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

All of that is defined, what are you referring to, the d's? Those are in a string, they are just text.

operators are just convenient aliases to methods. Those methods then do whatever they want. Let's make % print meow.

class Derp(object):
    def __mod__(self, other):
        print 'meow'

Derp() % 4

output:

meow

__mod__ for string thus looks for format specifiers and replaces them with the values that you supplied as arguments, doing so in different ways based on what the format specifier was. For example, %d will make it convert the value to int and then the int to str with a base10 (decimal) representation


#4

Appreciate the explanation Ionatan, thanks. I was confused about the modulo because it had previously been introduced in the lessons as a mathematical operator with a specific function and there was no explanation offered during the lesson about the way it was being implemented in this case.

I think I was just being too thorough for my own good.