Python Function Arguments (Keyword, Default Argument)
In Python, Arguments are used to define and call a function. There are four types of Function Arguments exist in Python:
1. Required Arguments
2. Keyword Arguments
3. Default Arguments
4. Variable-length Arguments
Required Arguments:
In Required Arguments, the arguments are passed to a function in the correct positional order. The number of arguments in the function call should exactly match the number of arguments specified in the function definition.
Example:
def display(str): print(str) str="Hello" display(str)
Output:
Hello
Keyword Arguments:
When we call a function with some values, the values are assigned to the arguments based on their position. Python also allows the functions to be called Keyword Arguments in which the order of the arguments can be changed. the values aren’t assigned to arguments according to their position but it is based on their name or keyword.
Example:
def display(str, int_x, float_y): print("The string is:", str) print("The integer value is:", int_x) print("The string is:", float_y) display(float_y= 50.55, str="Welcome to Webeduclick", int_x=120)
Output:
The string is: Welcome to Webeduclick
The integer value is: 120
The string is: 50.55
Default Arguments:
Python allows users to specify function arguments that can have default values. It means that a function can be called with fewer arguments than it is defined to have. Default Arguments assume a default value if a value isn’t provided in the function call for that argument.
Example:
def display(name, course="B.Tech"): print("Name: "+nae) print("Course:", course) display(name="Ram")
Output:
Name: Ram
Course: B.Tech
Variable-length Arguments:
In some situations, it is not known in advance how many arguments will be passed to a function. In such cases, Python allows us to make function calls with an arbitrary number of arguments.
Example:
def func(name, *favourite_sub): print(name, "likes to study!") for subject in favourite_sub: print(subject) func("Ram", "Mathematics", "Physics") func("Geeta", "History", "Geography")
Output:
Ram likes to study!
Mathematics
Physics
Geeta likes to study!
History
Geography