Python Default Function Parameters

closeup photo of computer keyboard

You can add default function parameters in Python by giving a default value for a parameter in the function definition.

For example:

def greet(name="friend"):
    print("Hello,", name)

Now the default value for name is friend. So if you call this function without a parameter:

greet()

You get the default greeting:

Hello friend

But if you call it with a name argument:

greet("Jon")

You get:

Hello Jon

To take home, you can simplify function calls by providing a default parameter when necessary.

Multiple Default Parameters in Python

You can have functions with multiple default parameters.

def function(param1=value1, param2=value2, param3=value3, ...):

For instance, let’s create a function that asks first name and last name. If these are not given, some default values are used:

def greet(firstname="Mr.", lastname="Who"):
    print("Hello,", firstname, lastname)

Example calls:

greet()
greet("Jack")
greet(lastname="Jones")
greet("Matt", "Gibson")

Outputs:

Hello, Mr. Who
Hello, Jack Who
Hello, Mr. Jones
Hello, Matt Gibson

Mix Up Default Parameters and Regular Parameters

You can also have a function with both default parameters and regular parameters.

For example:

def greet(greeting_word, firstname="Mr.", lastname="Who"):
    print(greeting_word, firstname, lastname)
    
    
greet("Hi")
greet("Hi", "Jack")
greet("Hello", lastname="Jones")
greet("Howdy", "Matt", "Gibson")

Output:

Hi Mr. Who
Hi Jack Who
Hello Mr. Jones
Howdy Matt Gibson

Conclusion

You can provide default values for function parameters in Python. This can simplify your function calls and code.

Here is an example of a function with a default parameter value:

def greet(name="friend"):
    print("Hello,", name)

Thanks for reading. I hope you enjoy it.

Happy coding!

Further Reading

50 Python Interview Questions with Answers

50+ Buzzwords of Web Development

Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on pinterest
Pinterest

Leave a Comment

Your email address will not be published. Required fields are marked *