Argument in Python
Last updated Aug 10, 2021Argument
Arguments in python are specified after the function name, inside the parenthesis. You can add several arguments you wish to but you need to separate them with a comma. Here the information is passed into functions in the form of arguments. Arguments are also known by the name of pass by reference.
Let's take an example of Arguments:-
def func1(fname): print(fname + " sharma") func1("sumit") func1("abhinav") |
sumit sharma |
abhinav sharma |
So as you can see we had assigned a value (sharma) and it will be passed to all the arguments which come under fname. So we can get as many outputs as many arguments are passed in the function.
Types of Arguments
There are 4 types of Arguments in Python Programming Language:-
-
Required arguments
-
Keyword arguments
-
Default arguments
-
Variable-length arguments
Required Argument
The arguments which are passed to a function in correct positional order are known as a required arguments. But in this case, we get a syntax error like this as shown in the example given below:-
def func2(str): print(str) return; func2() |
func2() |
So you can see we got an error in the above code.
Keyword Argument
These functions are related to the function calls. Here, the function caller identifies the given argument by its parameter name. In this type of argument we get the value we stored in the argument and is used as a keyword. Let's take an example of a Keyword Argument:-
def func2(str): print(str) return; func2(str="Hello coder") |
Hello coder |
As you can clearly see that we got our output which we passed in the argument.
Default Argument
The argument which assumes a default value if a value is not given or provided in the function call for that given argument then is known as the Default Argument. Let's understand an example of the Default Argument:-
def func3(name, age = 20 ): print("Name: ", name) print("Age ", age) return func3(age=50, name="sonu") func3(name="sonu") |
Age 20 |
Here in the above code, we got the default age when the function is not passed.
Variable-Length Argument
These arguments and are not named in the function definition, unlike required and default arguments. These variables act as args and are denoted by an asterisk(*) and it is placed before the variable name that holds the values of all non-keyword variable arguments. Let's take an example of args or Variable-length argument:-
def func4(arg1, *value ): print("Output is: ") print(arg1) for var in value: print(var) return; func4(10) func4(20, 30) |
Output is: |
10 |
Output is: |
20 |
30 |
So we got the output even after calling the args value.
Hope that you got this concept of argument easily.
Article Contributed By :
|
|
|
|
72 Views |