Day #21 - Function Arguments in Python

Day #21 - Function Arguments in Python

Β·

6 min read

Introduction

Welcome to my 21st blog post. Today I learned about 'Functions Arguments' and 'return' statements in python. I also learned about four different types of arguments that we can provide in functions. Now let's dive deep into the details of function arguments for a better understanding

So let's get started......

Function Arguments

In the last blog post, we saw how to write functions in python ( Functions in Python ).

Today we will see how we can customize these functions by passing arguments in them. There are 4 types of arguments that we can provide in function viz:

  1. Default Arguments

  2. Keyword Arguments

  3. Required Arguments

  4. Variable length Arguments

Default Arguments

The default value can be provided within a function while creating it. This way the function assumes a default value even if a value is not provided in the function call for that argument.

Example 1 -

def avg(a=9, b=1): #default arguments
  print("The average is ",(a + b) / 2)

avg() #default arguments are already passed in function

Output:

The average is  5.0

Example 2 -

def name(fname, mname = "Jhon", lname = "Whatson"):
    print("Hello,", fname, mname, lname)


name("Amy")

Output:

Hello, Amy Jhon Whatson

Example 3 -

def avg(a=9, b=1):
  print("The average is ",(a + b) / 2)

avg() #default arguments are already passed in function
avg(5)  #when not specified the argument passed is default to the first parameter
avg(b=4) #here for second parameter we need to manually pass the arguments
avg(2,6) #here we pass both arguments a=2, b=6

Output:

The average is  5.0
The average is  3.0
The average is  6.5
The average is  4.0

Keyword Arguments

We can provide arguments with key = value pair, this way the interpreter recognizes the arguments by the parameter name. Hence, the order in which the arguments are passed does not matter.

Example 1 -

def avg(a=9, b=1):
  print("The average is ",(a + b) / 2)

#keyword arguments
avg(b=5, a=6) #here we changed the order of arguments which does not matter, as we gave more details

Output:

The average is  5.5

Example 2 -

def name(fname, mname, lname):
    print("Hello,", fname, mname, lname)


name(mname = "Peter", lname = "Wesker", fname = "Jade")

Output:

Hello, Jade Peter Wesker

Required Arguments

In case we don’t pass the arguments with a key = value syntax, then it is necessary to pass the arguments in the correct positional order and the number of arguments passed should match the actual function definition.

Example 1 -

#required arguments
def avge(a, b=1):                    #default value of a is not given
  print("The average is ",(a + b) / 2)

avge(2)    #here you need to give argument for a, but for b its optional as default argument already given

Output:

The average is  1.5

Example 2 -

def name(fname, mname, lname):
    print("Hello,", fname, mname, lname)


name("Peter", "Quill") #here we give less number of arguments which should show error

Output:

name("Peter", "Quill")\
TypeError: name() missing 1 required positional argument: 'lname'

Example 3 - when a number of arguments passed matches the actual function definition.

def name(fname, mname, lname):
    print("Hello,", fname, mname, lname)


name("Peter", "Ego", "Quill")
Hello, Peter Ego Quill

Variable-length arguments:

Sometimes we may need to pass more arguments than those defined in the actual function. This can be done using variable-length arguments.

There are two ways to achieve this:

  1. Arbitrary Arguments

  2. Keyword Arbitrary Arguments

Arbitrary Arguments:

While creating a function, pass a * before the parameter name while defining the function. The function accesses the arguments by processing them in the form of a tuple.

Example 1 -

#variable length arguments
#Arbitrary arguments
def averg(*numbers):   #here the arguments are taken in tuple form

  print("\n ",type(numbers))
  sum =0
  for i in numbers:
    sum = sum + i 

  print ("The average of variable length arguments is ", sum /len(numbers))

averg(1,2,4,8,10)

Output:

  <class 'tuple'>
The average of variable length arguments is  5.0

Example 2 -

def name(*name):
    print("Hello,", name[0], name[1], name[2])


name("James", "Buchanan", "Barnes")

Output -

Hello, James Buchanan Barnes

Keyword Arbitrary Arguments:

While creating a function, pass a before the parameter name while defining the function. The function accesses the arguments by processing them in the form of a dictionary**.

Example -

#variable length arguments
 #Keyword Arbitrary arguments
def name(**name):        #here the arguments are taken in dictionary key-value form
  print("\n",type(name))
  print(" Hello,", name["fname"], name["mname"], name["lname"])

name(mname = "Buchanan", lname = "Barnes", fname = "James")

Output:

 <class 'dict'>
 Hello, James Buchanan Barnes

Return Statement

The return statement is used to return the value of the expression back to the calling function.

Example -

#Return statements
def averg(*numbers):   #here the arguments are taken in tuple form

  print("\n ",type(numbers))
  sum =0
  for i in numbers:
    sum = sum + i 
  #print ("The average of variable length arguments is ", sum /len(numbers))
  return sum /len(numbers)   #here the function returns the value after computing

c = averg(10,20,40,80,100)  

print(c)  #if function does not return anything then we get 'None' as the value of 'c' here

Output -

  <class 'tuple'>
50.0

NOTE 1 - if the function does not return anything then we get 'None' as the value of 'c' in above case

NOTE 2 - if multiple return statements are there in the function then the first return is considered and the rest are ignored.

Resources Used

You can watch the video of Day#21 by clicking on the below link πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡

Conclusion

Thanks, guys for going through this blog post. Function Arguments provide us with more depth into functions that can help us customize functions. This article is long with some extensive examples from my learnings covering in-depth Function arguments.

Thank you if you read this post and have found this post useful. I hope you have joined me and are enjoying my magical journey of python coding. This is it for Day #21

See you in the next one.....


About Me

Hey Guys, I am Chintan Jain from CodeWithJain. I am a trader and content creator. I am also passionate about tech and hence wanted to explore the field of tech. I always wanted to learn to code so I watched many tutorials but procrastinated practising coding. To get into the habit of coding consistently I am starting to BLOG with HASHNODE on daily basis.

I will document my coding journey from scratch and share my daily learnings in a blog post on HASHNODE. I hope you all will enjoy my content and my coding journey.

So what are you waiting for, smash the FOLLOW and LIKE buttons and follow along my coding journey, a step to create more beautiful digital products and empower people.


Β