Python Default Parameter Values (With Examples)

python-default-parameter-values-with-examples

While defining a function, you can set default parameter values.

This can be particularly useful when you have multiple parameters of a single function.

You can easily set the default value for each parameter in python.

And when you call the function if you miss any parameter or you don’t have any data about a specific parameter. This will come in handy.

Your code will run properly, without creating any errors.

It ensures that your code will run all the time even if you do not have the value for all the required parameters.

What are Default Parameter Values in Python?

Let’s have a look at the example below.

def area_of_rectangle(length=1, width=1):
    return length * width

You know the area of the rectangle is simply its length multiplied by its width.

In the code above, the length and width are predefined. Now, let’s run it by passing some values as arguments.

def area_of_rectangle(length=1, width=2):
    return length * width
    
result = area_of_rectangle(2,3)
print(result)

Output

6

But it just working as a normal function. Then what is the purpose of redefining the parameter values?

Hold on, let me make it clear.

If it was a normal function you can not pass a single argument to a function that requires 2 arguments to work properly.

But in this function, you can pass a single argument even if two arguments are required.

Here, the concept of default parameter values comes in play

Let’s try the same function with a single argument and check if it works properly.

def area_of_rectangle(length=1, width=2):
    return length * width
    
result = area_of_rectangle(3)
print(result)

Output

6

You can see, the output is 6. But you might be questioning how this program can run.

Well, the value you passed as the argument was passed in as parameter one from the left which is length, in this case.

Now the value of length is 3 and the function will take the default value of the width, which is 2, and return the result after multiplying.

Now everything should make sense to you.

If you passed both the values as an argument the function will work exactly as a normal function ignoring the default parameter values.

But if you omit any argument the default argument value will be used.


Discover more from Python Mania

Subscribe to get the latest posts sent to your email.

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

Related Articles:

Recent Articles:

0
Would love your thoughts, please comment.x
()
x

Discover more from Python Mania

Subscribe now to keep reading and get access to the full archive.

Continue reading