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 John, Mary, 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

Exception Handling in Python

  Introduction   An error is an abnormal condition that results in unexpected behavior of a program. Common kinds of errors are syntax errors and logical errors. Syntax errors arise due to poor understanding of the language. Logical errors arise due to poor understanding of the problem and its solution.   Anomalies that occur at runtime are known as exceptions. Exceptions are of two types: synchronous exceptions and asynchronous exceptions. Synchronous exceptions are caused due to mistakes in the logic of the program and can be controlled. Asynchronous exceptions are caused due to hardware failure or operating system level failures and cannot be controlled.   Examples of synchronous exceptions are: divide by zero, array index out of bounds, etc.) . Examples of asynchronous exceptions are: out of memory error, memory overflow, memory underflow, disk failure, etc. Overview of errors and exceptions in Python is as follows:     Handling Exceptions   Flowch...

JENKINS BASICS

  Jenkins  – an open source automation server which enables developers around the world to reliably build, test, and deploy their software. Dashboard: " Dashboard " is the default view shown when you open Jenkins and shows an overview of all  projects configured on a  Jenkins  instance. Creating a New Project: Step 2:  In the next screen, enter the Item name, Choose the ‘Freestyle project option’ Step 3  − The following screen will come up in which you can specify the details of the job. Note  − If you repository if hosted on Github, you can also enter the url of that repository here. In addition to this, you would need to click on the Add button for the credentials to add a user name and password to the github repository so that the code can be picked up from the remote repository. Step 4 − Now go to the Build section and click on Add build step → Execute Windows batch command Before Executing and building a file. Let me describe the task which w...

NumPY In python

 NumPy Stands for numerical python How do I install NumPy? To install Python NumPy, go to your command prompt and type “pip install numpy”.  Once the installation is completed, go to your IDE (For example: PyCharm) and simply import it by typing:  “import numpy as np” Here, I have different elements that are stored in their respective memory locations. It is said to be two dimensional because it has rows as well as columns. In the above image, we have 3 columns and 4 rows available. How do I start NumPy? Single-dimensional Numpy Array: 1 2 3 import numpy as np a = np.array([ 1 , 2 , 3 ]) print (a) Output – [1 2 3] Multi-dimensional Array: 1 2 a = np.array([( 1 , 2 , 3 ),( 4 , 5 , 6 )]) print (a) O/P – [[ 1 2 3] [4 5 6]] Python NumPy Array v/s List Why NumPy is used in Python? We use python NumPy array instead of a list because of the below three reasons: Less Memory Fast Convenient The very first reason to choose python NumPy array is that it occupies less memory as co...