4. Parameters and Arguments, %s versus %d


#1


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

My code works, but I am wondering why we use %d to hold the place of the values we want to print in the string when we have been taught to use %s.

When I change them all to %s, it still works. When I change only one to %s, it still works.

I would think that good practice would be to pick letters that make sense, in this case, maybe b for base, e for exponent, and r for result: "%b to the power of %e is %r." But that doesn't work; I get a syntax error: "ValueError: unsupported format character 'b' (0x62) at index 1" Apparently we can use d and s but not b.

So my real question is how do we pick what letter to use?


def power(base, exponent):  # Add your parameters here!
    result = base**exponent
    print "%d to the power of %d is %d." % (base, exponent, result)

power(37, 4)  # Add your arguments here!


#2

Okay, the error message tells me that %s and %d are called format characters, which made it possible to google for more information. I found that these mean different things. There is a chart here:
https://docs.python.org/3/library/stdtypes.html#string-formatting
that explains that:
s means "String (converts any Python object using str())."
d means "Signed integer decimal."

So if they are all the same type of value, we should use the same letter. And since I don't know what all those types mean yet, I'm not going to worry about it yet.


#3

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