How to Pass in a Default Value into a Function in Python


In this article, we show how to pass in a default value into a function in Python.

So when you create a function, you can specify a default value for any parameter of the function.

This is done at time of the function creation or definition.

Below is a function called student that takes in a single argument, name.

We specify the default value for name be 'David'.

If the function is called without the name argument being declared, then the function will print the default value.

If the function is called with the name argument declared, then the function will print whatever value was specified.

So we create a function called student().

This function takes in an argument called name.

If we just specified name, it would take the name value without any default value.

However, we want to specify a default value. Therefore, we set name equal to a default value of 'David'

Now we can call the function even without specifying an argument, because the name argument has a default value. If we didn't create a default value and just specified name, then calling the function without a name argument specified would cause an error, since the name argument would have no value.

So you can see above, when we call the student() function without any name argument specified, 'David' is printed, since 'David' is the default value.

If we specify a value for the name argument of the function, then the value we specified is printed.

You can specify the name argument by just putting the value in the function call or by specifying name='value'

Both work the same way, with the latter just being more explicit.

And this can be done with multiple arguments.

In the code below, we declare default values for 2 parameters.

So now we have default values for name and age arguments.

If we call the students() function without any arguments, the default arguments will be the value of the arguments.

If we specify the name argument, this makes the name argument, 'Tom'

If we speciy the age argument, this makes the age argument, 19

If we specify both, this changes both.

You can also have default values for some arguments and none for others. Just make sure that if you do this, the non-default argument is first in the function declaration and the argument with a default value is last, or else an error will be thrown.

And this is how default values can be passed into a function in Python.

Related Resources

How to Randomly Select From or Shuffle a List in Python

HTML Comment Box is loading comments...