Arguments in Python Functions

  • Python

In this tutorial, we’ll learn about different types of arguments that can be defined within a python function. Parameter and an Argument is almost similar and the only difference is that an argument is used when the function is called.

Default Arguments

A default parameter value can be assigned to a function which will be used when when a function is called without an argument.

def fav_color(color='Blue'):
  print("My favorite color is " + color)

fav_color()

Output :

My favorite color is Blue

In the above example, we did not provide any argument while calling the function and it printed the default one. If we give the function an argument, it will behave like this.

def fav_color(color='Blue'):
  print("My favorite color is " + color)

fav_color("Black")

Output ;

My favorite color is Black

Arbitrary Arguments, *args

In a few situations, we don’t know how many arguments are going to be passed in a function. To handle this kind of situation, we use asterisk * in front of the argument. Let’s check this with an example.

def fav_items(*args):
  for arg in args:
    print("I like " + arg)

fav_items("Eggs", "Super Bikes", "Techie Hours")

Output :

I like Eggs
I like Super Bikes
I like Techie Hours

Keyword Arguments

We know that we can pass multiple arguments to a function but we always need to make sure the order they are entered as the function will now know which argument if for which statement.

Let’s understand this with an example by printing Name and favorite color of a person.

def bio(name, color):
  print("My name is " + name)
  print("My favorite color is " + color)

bio("Julia", "Blue")

Output :

My name is Julia
My favorite color is Blue

Now, what if we interchange the positions of the arguments?

def bio(name, color):
  print("My name is " + name)
  print("My favorite color is " + color)

bio("Blue", "Julia")

The Output will be the opposite and My name is Blue and My favorite color is Julia will get printed. To avoid this we use keyword arguments.

def bio(name, color):
  print("My name is " + name)
  print("My favorite color is " + color)

bio(color="Blue", name="Julia")

Output :

My name is Julia
My favorite color is Blue

While using keyword arguments, there is one exception that you cannot use a positional argument after a keyword argument. Check the below example.

def bio(name, color):
  print("My name is " + name)
  print("My favorite color is " + color)

bio(color="Blue", "Julia")

Output :

SyntaxError: non-keyword arg after keyword arg

Arbitrary Keyword Arguments, **kwargs

In some situations, we don’t know how many keyword arguments will be passed. To handle this situation, add two asterisk signs ** before the parameter. Let’s understand this using the above example of bio.

def bio(**details):
  for key, value in details.items():
    print("My {} is {}".format(key,value))

bio(Name="Julia", FavoriteColor="Blue")

Output :

My Name is Julia
My FavoriteColor is Blue