There are various types of arguments you can give to functions in Python. You can read about functions here- Functions in Python
Multiple Arguments
You can give multiple arguments to a function, by separating them using commas.
For example-
def fruits(a, b):
print("My favourite fruits are", a, "and", b)
fruits("Banana", "Mango")
The output-
My favourite fruits are Banana and Mango
Here, you need to specify the same number of values as the number of arguments, else you will get an error.
For example-
def fruits(a, b):
print("My favourite fruits are", a, "and", b)
fruits("Banana")
The output-
TypeError: fruits() missing 1 required positional argument: 'b'
Arbitrary Arguments
If you don’t know how many arguments you will need, you can add a
*
before the name of the argument while defining the function.
Doing this will submit the values as a tuple to the function. Then, you can use numbering to extract the required value.
For example-
def fruits(*names):
print("My favourite fruit is", names[1])
fruits("Banana", "Apple", "Mango")
The output-
My favourite fruit is Apple
Here, the second value of
fruits()
is taken as the value for
names
, because in Python, numbering begins from 0. So, the first
value is number 0, the second is number 1, and so on.
Keyword Arguments
Arguments can be given in another way, where the value of the argument is
defined along with it using
=
.
For example-
def fruits(fruit1, fruit2, fruit3):
print("My favourite fruit is", fruit3)
fruits(fruit3="Banana", fruit2="Watermelon", fruit1="Grapes")
The output-
My favourite fruit is Banana
Arbitrary Keyword Arguments
These are basically a mix of arbitrary arguments and keyword arguments covered above and can be used when you don’t know the number of arguments you may need.
You can create these by adding
**
before the name of the argument.
For example-
def fruits(**names):
print("My favourite fruit is", names["f2"])
fruits(f1="Banana", f2="Apple", f3="Mango")
The output-
My favourite fruit is Apple
These are the basics that you need to know about arguments in Python.
Follow this blog, bookmark it and keep checking it to get more such content on Python.
Happy Coding,
Aarav Iyer