0% found this document useful (0 votes)
5 views101 pages

Python PGMG Notes

The document provides an overview of functions in Python, including their definition, types (user-defined and built-in), and how to create and call them. It also covers function arguments, recursion, anonymous functions (lambda), and introduces the NumPy module for numerical operations. Key concepts include the use of return statements, variable scopes, and various mathematical functions available in NumPy.

Uploaded by

fp0690584
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)
5 views101 pages

Python PGMG Notes

The document provides an overview of functions in Python, including their definition, types (user-defined and built-in), and how to create and call them. It also covers function arguments, recursion, anonymous functions (lambda), and introduces the NumPy module for numerical operations. Key concepts include the use of return statements, variable scopes, and various mathematical functions available in NumPy.

Uploaded by

fp0690584
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/ 101

WEEK9 FUNCTION

FUNCTIONS
What is a function?
function is a group of related statements that performs a
specific task
9.1 Need of Function
• Using functions, we can avoid rewriting the same logic/code
again and again in a program.
• We can call Python functions multiple times in a program and
anywhere in a program.
• We can track a large Python program easily when it is divided
into multiple functions.
• Reusability is the main achievement of Python functions.
• However, Function calling is always overhead in a Python
program.

9.2 Types of Function

There are mainly two types of functions.

User-define functions - The user-defined functions are those define by


the user to perform the specific task.

Example: add (), fact (), GCD ()

Built-in functions - The built-in functions are those functions that are
pre-defined in Python.

Example: id (), print (), type (), input (), eval ()

MANJUNATHA B S LECTURER/CSE DEPT, KSP


WEEK9 FUNCTION

9.3 Define function/Creating a Function


Python provides the def keyword to define the function.

Syntax:

def my_function(parameters):

function_block

return expression

• The def keyword, along with the function name is used to define
the function.
• The identifier rule must follow the function name.
• A function accepts the parameter (argument), and they can be
optional.
• The function block is started with the colon (:), and block
statements must be at the same indentation.
• The return statement is used to return the value. A function can
have only one return

Example: def fun():

print(“welcome to ksp”);

MANJUNATHA B S LECTURER/CSE DEPT, KSP


WEEK9 FUNCTION

9.4 Function Calling


• after the function is created, we can call it from another function.
• A function must be defined before the function call; otherwise,
the Python interpreter gives an error
• To call the function, use the function name followed by the
parentheses.

Example:

def hello_world():

print("hello world")

hello_world()

OUTPUT:

Return Statement:
• The return statement is used at the end of the function and returns
the result of the function.
• It terminates the function execution and transfers the result where
the function is called.
• The return statement cannot be used outside of the function.

Syntax
return [expression_list]

MANJUNATHA B S LECTURER/CSE DEPT, KSP


WEEK9 FUNCTION

Example1:

Example2: Creating function without return statement

9.5 Function Arguments


• The arguments are types of information which can be passed into
the function.
• The arguments are specified in the parentheses.
• We can pass any number of arguments, but they must be separate
them with a comma.

MANJUNATHA B S LECTURER/CSE DEPT, KSP


WEEK9 FUNCTION

Example:

. Call by reference in Python


• call by reference means passing the actual value as an argument
in the function.
• All the functions are called by reference, i.e., all the changes made
to the reference inside the function revert back to the original
value referred by the reference.

MANJUNATHA B S LECTURER/CSE DEPT, KSP


WEEK9 FUNCTION

Example:

• Passing Mutable Object (String)

9.6 Types of arguments


There may be several types of arguments which can be passed at the
time of function call.
➢ Required arguments
➢ Keyword arguments
➢ Default arguments
➢ Variable-length arguments
Required arguments
• Required arguments are the arguments passed to a function in
correct positional order.
• Here, the number of arguments in the function call should match
exactly with the function definition.

MANJUNATHA B S LECTURER/CSE DEPT, KSP


WEEK9 FUNCTION

Example:

Keyword Arguments
• Python allows us to call the function with the keyword arguments.
• This kind of function call will enable us to pass the arguments in
the random order.
• The name of the arguments is treated as the keywords and
matched in the function calling and definition.
• If the same match is found, the values of the arguments are copied
in the function definition.
Example:

MANJUNATHA B S LECTURER/CSE DEPT, KSP


WEEK9 FUNCTION

Default Arguments
• Python allows us to initialize the arguments at the function
definition.
• If the value of any of the arguments is not provided at the time of
function call.
• then that argument can be initialized with the value given in the
definition even if the argument is not specified at the function
call.
Example:

MANJUNATHA B S LECTURER/CSE DEPT, KSP


WEEK9 FUNCTION

• Variable-length Arguments (*args)


• In large projects, sometimes we may not know the number of
arguments to be passed in advance.
• In such cases, Python provides us the flexibility to offer the
comma-separated values which are internally treated as tuples at
the function call.
• By using the variable-length arguments, we can pass any number
of arguments.
• However, at the function definition, we define the variable-length
argument using the *args (star) as *<variable - name >.

Example:

9.7 Return and yield

MANJUNATHA B S LECTURER/CSE DEPT, KSP


WEEK9 FUNCTION

• The return statement is generally used for the execution


ending and returns the value back to the caller.
• The return statement can return all types of values and it
returns nothing when there is no expression passed to return
statement
Example:

Python Yield statement


• The generators are defined by using the yield statement in Python.
• Generally, it converts a normal Python function into a generator.

What is Generator?

MANJUNATHA B S LECTURER/CSE DEPT, KSP


WEEK9 FUNCTION

• Python generators are used as a method for generating the


iterators. Generators have automatically handled the task.
• A generator can be defined as the special function that returns an
object of the generator to the caller.

Example:

MANJUNATHA B S LECTURER/CSE DEPT, KSP


WEEK9 FUNCTION

Yield Statement Return Statement

Yield returns the generator object. Returns the results to the caller.

It can run multiple times. It runs only a single time.

Code can be executed in the next function call Code will not be executed after the return
after the yield statement. statement.

This statement can resume from where it is left off The function call in this statement only runs the
or paused. function from the beginning.

The yield statement hauls the function and returns The return statement takes exit from the execution
back the value to the function caller. and returns the value back to the caller.

9.8 None Keyword


• None is used to define a null value.
• It is not the same as an empty string, False, or a zero. It is a data
type of the class NoneType object.

Example:

x = None

print(x)

9.9 Scope of Variables


• The scopes of the variables depend upon the location where the
variable is being declared.
• The variable declared in one part of the program may not be
accessible to the other parts.

In python, the variables are defined with the two types of scopes.
• Global variables
• Local variables

MANJUNATHA B S LECTURER/CSE DEPT, KSP


WEEK9 FUNCTION

• The variable defined outside any function is known to have a


global scope,
• whereas the variable defined inside a function is known to have a
local scope.

Example:

9.10 Python Recursion


• Recursion is the process of defining something in terms of itself.
• function can call other functions. It is even possible for the
function to call itself.

MANJUNATHA B S LECTURER/CSE DEPT, KSP


WEEK9 FUNCTION

• These types of constructs are termed as recursive functions.

Example:

Working of recursive function

MANJUNATHA B S LECTURER/CSE DEPT, KSP


WEEK9 FUNCTION

Advantages of Recursion
• Recursive functions make the code look clean and elegant.
• A complex task can be broken down into simpler sub-problems
using recursion.
• Sequence generation is easier with recursion than using some
nested iteration.
Disadvantages of Recursion
• Sometimes the logic behind recursion is hard to follow through.
• Recursive calls are expensive (inefficient) as they take up a lot of
memory and time.
• Recursive functions are hard to debug.

9.11 Python Anonymous/Lambda Function


• an anonymous function is a function that is defined without a
name.

MANJUNATHA B S LECTURER/CSE DEPT, KSP


WEEK9 FUNCTION

• While normal functions are defined using the def keyword in


Python, anonymous functions are defined using the lambda
keyword.
• Hence, anonymous functions are also called lambda functions

Syntax of Lambda Function in python


lambda arguments: expression
example:
# Program to show the use of lambda functions
double = lambda x: x * 2
print(double(5))

• In the above program, lambda x: x * 2 is the lambda function.


• Here x is the argument and x * 2 is the expression that gets
evaluated and returned.
• This function has no name. It returns a function object which
is assigned to the identifier double.
• We can now call it as a normal function.

MANJUNATHA B S LECTURER/CSE DEPT, KSP


WEEK9 FUNCTION

Sufficient examples:

Write a python programs Python Program to Find HCF or GCD

Write a Python program to square and cube every number in a


given list of integers using Lambda.

MANJUNATHA B S LECTURER/CSE DEPT, KSP


WEEK9 FUNCTION

Write a python program of sum of two numbers in python using


function

Write a python program to check whether the given number is


even or odd

MANJUNATHA B S LECTURER/CSE DEPT, KSP


WEEK 11
11.1 Brief about NumPy module
NumPy is a Python package. It stands for 'Numerical Python'. It is a
library consisting of multidimensional array objects and a collection of
routines for processing of array.
NumPy – Environment
A lightweight alternative is to install NumPy using popular Python
package installer, pip.
$pip install numpy
11.2 NumPy Arithmetic Function
NumPy contains a large number of various mathematical operations.
NumPy provides standard trigonometric functions, functions for
arithmetic operations, handling complex numbers, etc.
Trigonometric Functions
NumPy has standard trigonometric functions which return
trigonometric ratios for a given angle in radians.
numpy.sin(x[, out]) = ufunc ‘sin’) : This mathematical function helps
user to calculate trignmetric sine for all x(being the array elements).
numpy.cos(x[, out]) = ufunc ‘cos’) : This mathematical function helps
user to calculate trignmetric cosine for all x(being the array elements).
Example:
arcsin, arcos, and arctan functions return the trigonometric inverse of
sin, cos, and tan of the given angle. The result of these functions can be
verified by numpy.degrees() function by converting radians to degrees.
Example:
OUTPUT:

11.3 Hyperbolic Functions


numpy.sinh(x[, out]) = ufunc ‘sin’) : This mathematical function helps
user to calculate hyperbolic sine for all x(being the array elements).
numpy.cosh(x[, out]) = ufunc ‘cos’) : This mathematical function
helps user to calculate hyperbolic cosine for all x(being the array
elements).
Example:
11.4 Functions for Rounding
numpy.around()
This is a function that returns the value rounded to the desired
precision. The function takes the following parameters.
Syntax:
numpy.around(a,decimals)
OUTPUT:

numpy.floor()
This function returns the largest integer not greater than the input
parameter. The floor of the scalar x is the largest integer i, such that i
<= x. Note that in Python, flooring always is rounded away from 0.
numpy.ceil()
The ceil() function returns the ceiling of an input value, i.e. the ceil of
the scalar x is the smallest integer i, such that i >= x.

11.4 Exponents and logarithms Functions


numpy.exp(array, out = None, where = True, casting =
‘same_kind’, order = ‘K’, dtype = None) : This mathematical
function helps user to calculate exponential of all the elements in the
input array.
numpy.log(x[, out] = ufunc ‘log1p’) : This mathematical function
helps user to calculate Natural logarithm of x where x belongs to all the
input array elements.
11.5 Arithmetic Functions
The add () function sums the content of two arrays, and return
the results in a new array.
Example:

The subtract () function subtracts the values from one array


with the values from another array, and return the results in a
new array.

The multiply () function multiplies the values from one array


with the values from another array, and return the results in a
new array.

The divide() function divides the values from one array with
the values from another array, and return the results in a new
array.
The power() function rises the values from the first array to the
power of the values of the second array, and return the results
in a new array.

Both the mod() and the remainder() functions return the


remainder of the values in the first array corresponding to the
values in the second array, and return the results in a new array.

The divmod() function return both the quotient and the the
mod. The return value is two arrays, the first array contains the
quotient and second array contains the mod.
Both the absolute () and the abs() functions functions do the
same absolute operation element-wise but we should use
absolute() to avoid confusion with python's inbuilt math.abs()

11.4 Numpy Array Creation


Arrays are used to store multiple values in one single variable.
Python does not have built-in support for Arrays, but Python
lists can be used instead.
Example:
Creating an array using list
arr=[1, 2, 3, 4, 5]
for i in arr:
print(i)

Array creation using array functions:


array(data type, value list) function is used to create an array
with data type and value list specified in its arguments
example:
import array
arr = array.array('i', [1, 2, 3])
for i in range (0,3):
print (arr[i], end=" ")

Create a NumPy Array:


• The array object in NumPy is called ndarray.
• We can create a NumPy ndarray object by using the
array() function.

Example:
Create a 2-D array
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
numpy.empty(shape, dtype = float, order = ‘C’) : Return a
new array of given shape and type, with random values.
numpy.zeros:Returns a new array of specified size, filled with
zeros.
Syntax:
numpy.zeros(shape, dtype = float, order = 'C')

You might also like