Parameters & defaults, explained simply
A function that always does exactly the same thing is useful, but a function you can customise is much more powerful. Parameters are the names inside the brackets of def. They act like variables that get filled in each time the function is called.
The values you pass when you call the function are called arguments. stamp("star") passes "star" into the shape parameter.
You can give a parameter a default value with an equals sign in the def line. If the caller leaves it out, the default is used; if they supply one, theirs wins.
Example: A stamp maker
def stamp(shape, copies=1):
for i in range(copies):
print("Stamped a", shape)
stamp("star")
stamp("moon", 2)Output
Stamped a star
Stamped a moon
Stamped a moonTry this
- Add a colour parameter with a default of "blue" and include it in the message.
- Call the function with copies=3 written by name.
- Call stamp() with no arguments at all and read the error.
