Skip to content
Home » Functions in Python – Mandatory Parameters

Functions in Python – Mandatory Parameters

Spread the love

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:

1) Introduction to Functions

2) Functions with Parameters

3) The return Statement

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.

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

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'

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply