0% found this document useful (0 votes)
23 views15 pages

Psc-Unit1-2-Python Functions

Uploaded by

Khushbu Maurya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views15 pages

Psc-Unit1-2-Python Functions

Uploaded by

Khushbu Maurya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Python functions & Types of function arguments in pytho... https://colab.research.google.com/drive/1AAb7PJ-xii5KoE...

Python Functions is a block of statements that return the


speci�c task. The idea is to put some commonly or
repeatedly done tasks together and make a function so
that instead of writing the same code again and again for
different inputs, we can do the function calls to reuse
code contained in it over and over again.
Some Bene�ts of Using Functions

Increase Code Readability


Increase Code Reusability

 Python Function Declaration

The syntax to declare a function is:

Types of Functions in Python

Below are the different types of functions in Python:

1 of 15 7/24/24, 14:54
Python functions & Types of function arguments in pytho... https://colab.research.google.com/drive/1AAb7PJ-xii5KoE...

Built-in library function: These are Standard functions in Python that are available to use.

User-defined function: We can create our own functions based on our requirements.

Here are simple rules to de�ne a function in Python:


1. Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
2. Any input parameters or arguments should be placed within these parentheses. You can
also de�ne parameters inside these parentheses.
3. The �rst statement of a function can be an optional statement - the * documentation
string of the function or docstring.
4. The code block within every function starts with a colon (:) and is indented.
5. The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as return
None.

Syntax:
def functionname( parameters ):

"function_docstring"

function_suite

return [expression]

 Creating a Function in Python

We can de�ne a function in Python, using the def keyword. We can add any type of
functionalities and properties to it as we require. By the following example, we can
understand how to write a function in Python. In this way we can create Python function
de�nition by using def keyword.

# A simple Python function


def fun():
print("Welcome to Indus")

2 of 15 7/24/24, 14:54
Python functions & Types of function arguments in pytho... https://colab.research.google.com/drive/1AAb7PJ-xii5KoE...

 Calling a Function in Python

After creating a function in Python we can call it by using the name of the functions Python
followed by parenthesis containing parameters of that particular function. Below is the
example for calling def function Python.

# Driver code to call a function


fun()
Welcome to Indus

 Python Function with Parameters

If you have experience in C/C++ or Java then you must be thinking about the return type of the
function and data type of arguments. That is possible in Python as well (speci�cally for
Python 3.5 and above).

Python Function Syntax with Parameters

#def function_name(parameter: data_type) -> return_type:

"""Docstring"""
body of the function
return expression

The following example uses arguments and parameters that you will learn later in this article
so you can come back to it again if not understood.

Double-click (or enter) to edit

 Docstring

The �rst string after the function is called the Document string or
Docstring in short. This is used to describe the functionality of
the function. The use of docstring in functions is optional but it is
considered a good practice.
The below syntax can be used to print out the docstring of a function. Syntax:
print(function_name.doc)

Example: Adding Docstring to the function

3 of 15 7/24/24, 14:54
Python functions & Types of function arguments in pytho... https://colab.research.google.com/drive/1AAb7PJ-xii5KoE...

Example: Adding Docstring to the function

def add(num1: int, num2: int) -> int:


"""Add two numbers"""
num3 = num1 + num2

return num3

# Driver code
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results {ans}.")

The addition of 5 and 15 results 20.

 Python Function Arguments

Arguments are the values passed inside the parenthesis


of the function. A function can have any number of
arguments separated by a comma.
In this example, we will create a simple function in Python to check whether the number
passed as an argument to the function is even or odd.

# A simple Python function to check


# whether x is even or odd
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")

# Driver code to call the function


evenOdd(2)
evenOdd(3)

even
odd

 Pass by Value In Python Example

Here, we will pass the integer x to the function which is an


4 of 15 7/24/24, 14:54
Python functions & Types of function arguments in pytho... https://colab.research.google.com/drive/1AAb7PJ-xii5KoE...

Here, we will pass the integer x to the function which is an


immutable data type. We then update the value of the integer
inside the function and print the updated value. The changes are
not seen outside the function as integers are immutable data
types.

def modify_integer(x):
x = x + 10
print("Inside function:", x)

x = 5
print("Before function call:", x)
modify_integer(x)
print("After function call:", x)

Before function call: 5


Inside function: 15
After function call: 5

 Pass by reference vs value

All parameters (arguments) in the Python language are


passed by reference. It means if you change what a
parameter refers to within a function, the change also
re�ects back in the calling function. For example:

def changeme( mylist ):


#"This changes a passed list“
mylist.append([1,2,3,4]);
print ("Values inside the function: ", mylist)
return
mylist = [10,20,30];
changeme( mylist );
print ("Values outside the function: ", mylist )

Values inside the function: [10, 20, 30, [1, 2, 3, 4]]


Values outside the function: [10, 20, 30, [1, 2, 3, 4]]

There is one more example where argument is being


5 of 15 7/24/24, 14:54
Python functions & Types of function arguments in pytho... https://colab.research.google.com/drive/1AAb7PJ-xii5KoE...

There is one more example where argument is being


 passed by reference but inside the function, but the
reference is being over-written.

def changeme( mylist ): #"This changes a passed list"


mylist = [1,2,3,4];
print( "Values inside the function: ", mylist )
return
mylist = [10,20,30];
changeme( mylist );
print ("Values outside the function: ", mylist)

Values inside the function: [1, 2, 3, 4]


Values outside the function: [10, 20, 30]

 Is Python pass by reference or value?

Python uses a mechanism known as “pass by object reference”


or “pass by assignment“. This means that when you pass a
variable to a function, you are passing the reference to the object
(or value) the variable points to. However, this reference itself is
passed by value.

What is the difference between pass by value and pass by


reference?

Pass by Value:
A copy of the actual data (value) is passed to the function. Changes made to the parameter
inside the function do not affect the original data. Used in languages like C, C++ for primitive
types.

Pass by Reference:
A reference (memory address) to the original data is passed to the function. Changes made
to the parameter inside the function affect the original data. Used in languages like C, C++ for
non-primitive types and objects.

6 of 15 7/24/24, 14:54
Python functions & Types of function arguments in pytho... https://colab.research.google.com/drive/1AAb7PJ-xii5KoE...

Why is pass by reference better than pass by value?


1. E�ciency: Pass by reference avoids making copies of large data structures, which can
be more e�cient.

2. Mutability: It allows functions to modify complex objects (like lists, dictionaries) directly,
without needing to return them.

3. Consistency: It maintains consistency in behavior when dealing with mutable objects.

Types of Python Function Arguments


Python supports various types of arguments that can be passed at the time of the function
call. In Python, we have the following function argument types in Python:

Default argument
Keyword arguments (named arguments)
Positional arguments
Arbitrary arguments (variable-length arguments *args and **kwargs)

 Default Arguments

A default argument is a parameter that assumes a default value


if a value is not provided in the function call for that argument.
The following example illustrates Default arguments to write
functions in Python.
Like C++ default arguments, any number of arguments in a function can have a default value.
But once we have a default argument, all the arguments to its right must also have default
values.

# Python program to demonstrate


# default arguments
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)
# Driver code (We call myFun() with only one # argument)
myFun(10)

7 of 15 7/24/24, 14:54
Python functions & Types of function arguments in pytho... https://colab.research.google.com/drive/1AAb7PJ-xii5KoE...

x: 10
y: 50

 Keyword Arguments

The idea is to allow the caller to specify the argument name with
values so that the caller does not need to remember the order of
parameters.

Double-click (or enter) to edit

# Python program to demonstrate Keyword Arguments


def student(firstname, lastname):
print(firstname, lastname)

# Keyword arguments
student(firstname='khushbu', lastname='maurya')
student(lastname='maurya', firstname='khushbu')

khushbu maurya
khushbu maurya

 Positional Arguments

We used the Position argument during the function call so that


the �rst argument (or value) is assigned to name and the second
argument (or value) is assigned to age.

By changing the position, or if you forget the order of the


positions, the values can be used in the wrong places, as shown
in the Case-2 example below, where 27 is assigned to the name
and Suraj is assigned to the age.

def nameAge(name, age):


print("Hi, I am", name)

8 of 15 7/24/24, 14:54
Python functions & Types of function arguments in pytho... https://colab.research.google.com/drive/1AAb7PJ-xii5KoE...

print("My age is ", age)


# You will get correct output because
# argument is given in order
print("Case-1:")
nameAge("Suraj", 27)
# You will get incorrect output because
# argument is not in order
print("\nCase-2:")
nameAge(27, "Suraj")
Case-1:
Hi, I am Suraj
My age is 27

Case-2:
Hi, I am 27
My age is Suraj

 Arbitrary Keyword Arguments

In Python Arbitrary Keyword Arguments, args, and *kwargs can


pass a variable number of arguments to a function using special
symbols. There are two special symbols:

*args in Python (Non-Keyword Arguments)


**kwargs in Python (Keyword Arguments)

# Python program to illustrate


# *args for variable number of arguments
def myFun(*argv):
for arg in argv:
print(arg)
myFun('Hello', 'Welcome', 'to', 'Indus University',"sfgyjgvcj")
Hello
Welcome
to
Indus University
sfgyjgvcj

# Python program to illustrate


# *kwargs for variable number of keyword arguments
def myFun(**kwargs):
for key, value in kwargs.items():
print("%s->%s" %(key, value))
# Driver code
myFun(first='Indus', mid='University', last='Ahmedabad')

9 of 15 7/24/24, 14:54
Python functions & Types of function arguments in pytho... https://colab.research.google.com/drive/1AAb7PJ-xii5KoE...

first->Indus
mid->University
last->Ahmedabad

 Docstring

The �rst string after the function is called the Document string or
Docstring in short. This is used to describe the functionality of
the function. The use of docstring in functions is optional but it is
considered a good practice.
The below syntax can be used to print out the docstring of a function. Syntax:
print(function_name.doc)

Example: Adding Docstring to the function

# A simple Python function to check


# whether x is even or odd

def evenOdd(x):
"""Function to check if the number is even or odd"""

if (x % 2 == 0):
print("even")
else:
print("odd")

# Driver code to call the function


print(evenOdd.__doc__)

Function to check if the number is even or odd

 Python Function within Functions

A function that is de�ned inside another function is known as the


inner function or nested function. Nested functions can access
variables of the enclosing scope. Inner functions are used so that
they can be protected from everything happening outside the
function.
10 of 15 7/24/24, 14:54
Python functions & Types of function arguments in pytho... https://colab.research.google.com/drive/1AAb7PJ-xii5KoE...

function.

# Python program to
# demonstrate accessing of
# variables of nested functions

def f1():
s = 'Indus University'
def f2():
print(s)
f2()
# Driver's code
f1()
Indus University

Anonymous Functions in Python

In Python, an anonymous function means that a function is


without a name. As we already know the def keyword is used to
de�ne the normal functions and the lambda keyword is used to
create anonymous functions.

A lambda function can take any number of arguments,


 but they can return only one value in the form of
expression.
Single one line function ,Anoymous function(no name),no def, no return

# Python code to illustrate the cube of a number


# using lambda function
def cube(x): return x*x*x

cube_v2 = lambda x : x*x*x

print(cube(7))
print(cube_v2(7))

343
343

11 of 15 7/24/24, 14:54
Python functions & Types of function arguments in pytho... https://colab.research.google.com/drive/1AAb7PJ-xii5KoE...

#Find sum of Three numbers

add=lambda a,b,c: print(a+b+c)


add(4, 5, 1)
#Output- 10
10

 Recursive Functions in Python

Recursion in Python refers to when a function calls itself. There


are many instances when you have to build a recursive function
to solve Mathematical and Recursive Problems.

Using a recursive function should be done with caution, as a


recursive function can become like a non-terminating loop. It is
better to check your exit statement while creating a recursive
function.

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)

print(factorial(4))

24

 Return Statement in Python Function

The function return statement is used to exit from a function and


go back to the function caller and return the speci�ed value or
data item to the caller. The syntax for the return statement is:
return [expression_list]

The return statement can consist of a variable, an expression, or


a constant which is returned at the end of the function execution.
12 of 15 7/24/24, 14:54
Python functions & Types of function arguments in pytho... https://colab.research.google.com/drive/1AAb7PJ-xii5KoE...

a constant which is returned at the end of the function execution.


If none of the above is present with the return statement a None
object is returned.
Example: Python Function Return Statement

def square_value(num):
"""This function returns the square
value of the entered number"""
return num**2

print(square_value(2))
print(square_value(-4))

4
16

 Pass by Reference and Pass by Value

One important thing to note is, in Python every variable name is a


reference. When we pass a variable to a function Python, a new
reference to the object is created. Parameter passing in Python is
the same as reference passing in Java.

# Here x is a new reference to same list lst


def myFun(x):
x[0] = 20

# Driver Code (Note that lst is modified


# after function call.
lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
print(lst)

[20, 11, 12, 13, 14, 15]

When we pass a reference and change the received


reference to something else, the connection between

the passed and received parameters is broken. For
13 of 15 7/24/24, 14:54
Python functions & Types of function arguments in pytho... https://colab.research.google.com/drive/1AAb7PJ-xii5KoE...

the passed and received parameters is broken. For


example, consider the below program as follows:

def myFun(x):

# After below line link of x with previous


# object gets broken. A new object is assigned
# to x.
x = [20, 30, 40]

# Driver Code (Note that lst is not modified


# after function call.
lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
print(lst)

[10, 11, 12, 13, 14, 15]

Another example demonstrates that the reference link is



broken if we assign a new value (inside the function).

def myFun(x):

# After below line link of x with previous


# object gets broken. A new object is assigned
# to x.
x = 20

# Driver Code (Note that x is not modified


# after function call.
x = 10
myFun(x)
print(x)

10

def swap(x, y):


temp = x
x = y
y = temp
print(x)#scope of variable inside function
print(y)
# Driver code
x = 2
3

14 of 15 7/24/24, 14:54
Python functions & Types of function arguments in pytho... https://colab.research.google.com/drive/1AAb7PJ-xii5KoE...

y = 3
swap(x, y)

3
2

15 of 15 7/24/24, 14:54

You might also like