How to create functions with optional arguments in Python?

Today, We want to share with you python optional arguments.In this post we will show you python function arguments, hear for python default arguments we will give you demo and example for implement.In this post, we will learn about python check if variable exists with an example.

Default arguments in Python

Now, Functions can have required as well as optional arguments. A required argument must be passed for the function to work, while an default argument or parameter is not required for the function to work.

USE A DEFAULT VALUE TO MAKE AN ARGUMENT OPTIONAL

Set an argument to a default data value to make it default. If the user data inputs a value for the argument(parameters), it will override the default main value.

Example 1:

def f(required_arg, default_arg1 = "1"):
//Create function with default argument `default_arg1`

print(required_arg, default_arg1)

f("a")

//Calling `f` using default value for `default_arg1`

//RESULTS
a 1
f("a", "b")
//Call `f` using `"b"` for `default_arg1`

//RESULTS
a b

Warning:

Default values need to always be immutable. Using mutable default some data values can cause unexpected behavior.

USE THE *args PARAMETER TO MAKE OPTIONAL ARGUMENTS

Added the *args parameter at the end of a function simple declaration to allow the user to pass in an arbitrary number of arguments as a tuple.

Example 2:

def f(a, b, *args):
//Make a function with `*args`

	arguments = (a, b) + args
	print(arguments)

f(1, 2)
//Calling `f` without default arguments

//RESULTS
(1, 2)
f(1, 2, 3, 4)
//Call `f` with default arguments `3` and `4`

//RESULTS
(1, 2, 3, 4)

I hope you get an idea about keyword argument in python.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment