Skip to main content

Python Function Arguments

 

Python function arguments: Introduction

The first thing a programmer must be aware of is that parameters and arguments are clearly two different things although people use them synonymously.

Parameters are the variables that are defined or used inside parentheses while defining a function, whereas arguments are the value passed for these parameters while calling a function. Arguments are the values that are passed to the function at run-time so that the function can do the designated task using these values.

#Defining a function first to return the value of parameter
def display(x):  #x is the parameter
  return x
 
#Calling the function and supplying arguments
print ("Hello " + display('David'))  #'David' is the argument

In this example, we have defined a function with parameter ‘x’. Basically, this function will return whatever the value is passed as an argument while calling.There are three types of Python function arguments using which we can call a function.

Output: HelloDavid

Types:


Default Arguments
Keyword Arguments
Variable-length Arguments

Python Default Arguments

Sometimes we may want to use parameters in a function that takes default values in case the user doesn’t want to provide a value for them.

For this, we can use default arguments which assumes a default value if a value is not supplied as an argument while calling the function. In parameters list, we can give default values to one or more parameters.

An assignment operator ‘=’ is used to give a default value to an argument. Here is an example.

def sum(a=4, b=2): #2 is supplied as default argument
  """ This function will print sum of two numbers
      if the arguments are not supplied
      it will add the default value """
  print (a+b)
 
sum(1,2)  #calling with arguments
sum( )    #calling without arguments

Output

3
6

In the program above, default arguments 2 and 4 are supplied to the function. First, the user has provided the arguments 1 and 2, hence the function prints their sum which is 3. In the second call, the user has not provided the arguments. Thus the function takes the default arguments and prints their sum.

Common Programming Errors

Using a non-default argument after default arguments raise a SyntaxError.

In Python functions, a default argument can only be followed by a default argument. Non-default arguments must be placed before default arguments.

 

 

Why does Python throw error while using default argument before non-default argument?

Well, the reason is simple.

In function, the values are assigned to parameters in order, by their position. The value of default argument may be optional as there is the default value if not provided, but the value for a non-default argument is mandatory as there exists no default value for this.

For example, def func(a=1, b) is not allowed because when we will call the function using func(5), the default argument a will be replaced by 5, leaving no value for parameter b. That is why a non-default argument is always placed before default argument.

Python Keyword Arguments

In function, the values passed through arguments are assigned to parameters in order, by their position.

With Keyword arguments, we can use the name of the parameter irrespective of its position while calling the function to supply the values. All the keyword arguments must match one of the arguments accepted by the function.

Here is an example.

def print_name(name1, name2):
  """ This function prints the name """
  print (name1 + " and " + name2 + " are friends")
 
#calling the function
print_name(name2 = 'John',name1 = 'Gary')

Output

Gary and John are friends

Notice in above example, if we had supplied arguments as print_name('John','Gary'), the output would have been John and Gary are friends as the values would have been assigned by arguments position.

But using keyword arguments by specifying the name of the argument itself, we don’t have to worry about their position. This makes using function easier as we don’t need to worry about the order of arguments.

Variable-length Arguments

Sometimes you may need more arguments to process function then you mentioned in the definition. If we don’t know in advance about the arguments needed in function, we can use variable-length arguments also called arbitrary arguments.

For this an asterisk (*) is placed before a parameter in function definition which can hold non-keyworded variable-length arguments and a double asterisk (**) is placed before a parameter in function which can hold keyworded variable-length arguments.

If we use one asterisk (*) like *var,  then all the positional arguments from that point till the end are collected as a tuple called ‘var’ and if we use two asterisks (**) before a variable like **var,  then all the positional arguments from that point till the end are collected as a dictionary called ‘var’.

Here is an example.

def display(*name, **address):
  for items in name:
    print (items)
 
  for items in address.items():
    print (items)
 
#Calling the function
display('john','Mary','Nina',John='LA',Mary='NY',Nina='DC')

Output

John
Mary
Nina
('John', 'LA')
('Mary', 'NY')
('Nina', 'DC')

As you can see in the example above, *name takes all the non-keyworded arguments JohnMary, and Nina wrapped into a tuple, whereas **address takes all the keyworded arguments John='LA'Mary ='NY', and Nina='DC' wrapped into a dictionary.

In this particular example, the function took three arbitrary variables using one variable with either asterisk(*) or double asterisk(**), but using variable length arguments we can take any number of arbitrary arguments.

Comments

Popular posts from this blog

Is-A and Has-A relationships in python

  In object-oriented programming, the concept of IS-A is a totally based on Inheritance, which can be of two types Class Inheritance or Interface Inheritance. It is just like saying "A is a B type of thing". For example, Apple is a Fruit, Car is a Vehicle etc. Inheritance is uni-directional. For example, House is a Building. But Building is not a House. #Is-A relationship --> By Inheritance class  A:    def   __init__ ( self ):      self .b= 10    def   mym1 ( self ):      print ( 'Parent method' ) class  B(A):    def   mym2 ( self ):      print ( 'Child method' ) d = B() d.mym1() #output: Parent method d.mym2() #output: Child method HAS-A Relationship:  Composition(HAS-A) simply mean the use of instance variables that are references to other objects. For example Maruti has Engine, or House has Bathroom. Let’s understand...

Magic Methods in Python

  What Are Dunder Methods ? In Python, special methods are a set of predefined methods you can use to enrich your classes.  They are easy to recognize because they start and end with double underscores, for example  __init__  or  __str__ . Dunder methods let you emulate the behavior of built-in types.  For example, to get the length of a string you can call  len('string') . But an empty class definition doesn’t support this behavior out of the box: These “dunders” or “special methods” in Python are also sometimes called “magic methods.” class NoLenSupport : pass >>> obj = NoLenSupport () >>> len ( obj ) TypeError : "object of type 'NoLenSupport' has no len()" To fix this, you can add a  __len__  dunder method to your class: class LenSupport : def __len__ ( self ): return 42 >>> obj = LenSupport () >>> len ( obj ) 42 Object Initialization:  __init__ "__init __ ...

Inheritance and Types in Python

  Inheritance   Creating a new class from existing class is known as inheritance . The class from which features are inherited is known as base class and the class into which features are derived into is called derived class . Syntax: class  derived- class (base  class ):       < class -suite>      Inheritance promotes reusability of code by reusing already existing classes.  Inheritance is used to implement  is-a  relationship between classes.   Following hierarchy is an example representing inheritance between classes:   Single inheritance   When a derived class inherits only from syntax, the base class is called single inheritance. If it has one base class and one derived class it is called single inheritance.   Diagram     Syntax class  A:  #parent class         #some code       class  b(A):...