Function Arguments in Python
There are various types of arguments in Python functions. You can read about functions in my post, 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.
Notice: You can subscribe to my posts so that you receive quality content by me directly in your inbox here-https://medium.com/@aaraviyer10/subscribe
You can read about tuples here-
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.
Clap this story multiple times if you liked it and follow me to get more such content.
Happy coding,
Aarav Iyer