Here’s another article in the series on functions in Python. Today we’ll be talking about mandatory parameters. If you haven’t read the previous parts yet, feel free to do so. Here they are:
The parameters that we’ve been using up to now are all mandatory parameters. It means that if we use them in the definition, we then must pass the same number of arguments to the function when we call it. Otherwise we’ll get an error. For example the ordered function we created in the previous part has three mandatory parameters:
def ordered(number1, number2, number3):
return True if (number1 <= number2 <= number3) else False
Let’s see what happens if we pass a different number of parameters to it:
if ordered(4, 2):
print("4 and 2 are ordered.")
We can’t run the program because of the following error:
TypeError: ordered() missing 1 required positional argument: 'number3'
Now let’s pass three arguments, but let’s use strings instead of numbers:
if ordered("a", "b", "c"):
print("a, b and c are ordered.")
If we run this code, we’ll get the following output:
a, b and c are ordered.
Even though we passed three strings, it still works, because we can compare strings. As mentioned before, Python functions are polymorphic, which means we can use them with arguments of different types as long as the same operations are supported by the types. In this case both ints and strings support comparison.
Finally, let’s see what happens if we pass arguments that can’t be compared:
if ordered("a", "b", 6):
print("a, b and 6 are ordered.")
This time we’ll get an error:
TypeError: '<=' not supported between instances of 'str' and 'int'