0% found this document useful (0 votes)
7 views

pymodule3

The document provides an overview of arrays and functions in Python, highlighting the differences between arrays and lists, as well as various methods for manipulating arrays. It also explains the concept of functions, including built-in, module-defined, and user-defined functions, along with their advantages and syntax. Additionally, it covers the flow of execution in function calls and introduces lambda functions as a concise way to define anonymous functions.

Uploaded by

ryanut.jb
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)
7 views

pymodule3

The document provides an overview of arrays and functions in Python, highlighting the differences between arrays and lists, as well as various methods for manipulating arrays. It also explains the concept of functions, including built-in, module-defined, and user-defined functions, along with their advantages and syntax. Additionally, it covers the flow of execution in function calls and introduces lambda functions as a concise way to define anonymous functions.

Uploaded by

ryanut.jb
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/ 36

Python Programming [R4ET2015T+P]

by
Karuna Bhalerao
Assistant Professor, VJTI, Matunga, Mumbai
400019
Contact: [email protected]
Mob: 8378919162
MODULE III
Arrays
"Arrays" in Python are not the arrays in conventional programming languages like C and
Java, but closer to lists. A list can be a collection of either homogeneous or heterogeneous
elements, and may contain ints, strings or other lists.

Individual elements can be accessed through indexes. Python arrays are zero-indexed.
Here is an example:
my_array = array('i', [1,2,3,4,5])
print(my_array[1])
#2
print(my_array[2])
#3
print(my_array[0])
#1
Introduction to Arrays
• An array is a data structure that stores values of same data type. In
Python, this is the main difference between arrays and lists.
• While python lists can contain values corresponding to different data
types, arrays in python can only contain values corresponding to
same data type.
• To use arrays in python language, you need to import the standard
array module. This is because array is not a fundamental data type
like strings, integer etc. Here is how you can import array module in
python :
• from array import *
• Once you have imported the array module, you can declare an
array. Here is how you do it:
• arrayIdentifierName = array(typecode, [Initializers])
Introduction to Arrays
• In the declaration above, arrayIdentifierName is the name of array, typecode lets
python know the type of arrayand Initializers are the values with which array is
initialized.
• Type codes are the codes that are used to define the type of array values or the type
of array. The table in the parameters section shows the possible values you can use
when declaring an array and it's type.
• Here is a real world example of python array declaration :
• my_array = array('i',[1,2,3,4])
• In the example above, typecode used is i. This typecode represents signed integer
whose size is 2 bytes.
• Here is a simple example of an array containing 5 integers
• from array import *
• my_array = array('i', [1,2,3,4,5])
• for i in my_array:
• print(i)
• #1
• #2
• #3
• #4
• #5
• Append any value to the array using append()
Method

• Insert value in an array using insert() method


• Extend python array using extend() method

• Add items from list into array using fromlist() method


• Remove any array element using remove() method

• Remove last array element using pop() method


• Fetch any element through its index using index() method

• Reverse a python array using reverse() method


• Check for number of occurrences of an element using count()
method

• Convert array to string using tostring() method


Multidimensional arrays
• Lists in lists
Functions
Definition OF Function
A program is a set of statements that takes some input,
does specific computations based on given input and
produces desired output. A very Large program with a huge
single list of instructions increases complexity.So Python
allows us to divide a large program into some small
independent units or blocks known as functions.
Decomposing a complex problem into simpler one using
functions improves clarity of the code.
Functions are the most important segments or
subprograms of an application used to perform specific tasks.
A python program can have one or more functions.
The advantages of using functions

• Reduce By using functions, we can


avoid rewriting same
duplication of logic/code again and again,
code. Thus function reduces
program size.

We can call python functions


• Induce any number of times from any
reusability of part of the program.So
function induces reusability in
code. a program.
Types of Functions:
Basically there are three types of functions used in
python program:
• Built in functions (python library functions)
– These are predefined functions and are always
available in python library.
• Functions defined within modules
– These are also predefined functions available in
different modules.
• User defined functions
– These are defined by programmer.
1.Built- in Functions
• These functions are already built in the library of python and can be
accessed by programmer easily.
• These are always available and for using them, we don't have to
import any module (file).
• Python has a small set of built-in functions like abs(), max(), min(),
len(), range(),round(),bool() chr(), float(), int(),long(),str( ),type( ),id(
) etc.
• Example:
• max( x, y, z) returns the largest of its 3 arguments.
• >>>max(80, -70, 100)
• 100
Flow of Execution
Flow of Execution
Flow of Execution
Flow of Execution
Flow of Execution
Flow of Execution
Flow of Execution
Flow of Execution
Flow of Execution
Flow of Execution with Functions
Calling functions inside functions

def main():

print (“I have a message for you.”)

message()

print (“Goodbye!”)

def message():

print (“The password is „foo‟”)

main()
2.Functions defined in modules
When we want to use module based functions in our
program, we need to import the corresponding module of that
particular function.
The functions available in math module are:
ceil(), floor(), fabs(), exp(), log(), pow(), sqrt() cos(), sin()etc.
Example:
ceil(x) returns the smallest integer not less than x
fabs(x) returns the absolute value of x,where x is a numeric value.

Example:
To work with the functions of math module, we must
import math module in our program.
sqrt() returns the square root of a number
>>>import math
>>>math.sqrt(49)
7.0
User defined function

In Python, programmers can also develop their own function(s). They


are known as user defined functions.

Syntax of function
def function-name(parameters) :
#block of statement(s)

Example:
def hello_world(): #called function
print("hello world")

hello_world() #calling function

Output:
hello world
Defining functions in python
def functionName( list of parameters ): Top level statements
"_docstring"
function_block • In python program, generally all
return [expression] python definitions are given at
Top level statements the top followed by statements
which are not part of any
functions These statements are
not indented at all.
def userfunction (arg1, arg2, arg3 ...):
program statement1 • The non indented statements
program statement2 written after all the function
definitions are often called top
program statement3 level statements .
....
return
userfunction(arg1,arg2,arg3)
Function definition with example
• Keyword def marks the start of #python function to calculate the sum o
function header. f two variables
• A function name to uniquely identify
it. Name of the Function follows the #defining the function
same rule of naming the identifier.
def sum(a,b):
• Parameters (arguments) through '‘’takes a and b and return the
which we pass values to a function
are optional. sum'''
• A colon (:) is used to mark the end of return a+b;
function header.
• The string after the function header #taking values from the user
is called the docstring . It is briefly a = int(input("Enter a: "))
used to explain what a function does. b = int(input("Enter b: "))
comments are ignored by python
interpreter but docstrings can be
viewed when the program is running. #printing the sum of a and b
• One or more python statements form print("Sum = ",sum(a,b))
function body.All the statements of
the block should have same Output:
indentation level.
• A return statement is used to return Enter a: 10
value(s) from the function but it is Enter b: 20
always optional. Sum = 30
HOW A FUNCTION WORKS

• Execution always begins from the first statement of the program.


• A python program may contain several funtion definitions.
• If any function definition is found,python executes only function
header for the correctness of it and skips all lines of function
body(block).
• When python sequentially reaches top level statement’s function
call, python transfers control to the function header and then
execution of function body takes place.
• Finally function execution ends with a return statement if any or the
last statement of function body.
FLOW OF EXECUTION IN AFUNCTION CALL

• Flow of execution refers to the order in which


statements are executed.
• A function body is executed in execution frame.
• Whenever a function call statement is executed,
execution frame for the called function is created and
the control is transferred to invoke the called function.
• Within the function’s execution frame,the body of the
function gets executed and after the last statement of
the function the control returns to the statement
with/without any value(s) to the function from where it is
called(calling function).
Function Parameters:
The values being passed through a function call statement are called
arguments or actual parameters.The values received in the function
definition are called parameters or formal parameters.

A function has two types of parameters:


• Formal Parameter(parameters): Formal parameters are written in the function
prototype(function definition). Formal parameters are local variables which are
assigned values from the arguments when the function is called.
• Actual Parameter(arguments): When a function is called, the values that are
passed are called actual parameters. At the time of the call, each actual
parameter is assigned to the corresponding formal parameter in the function
definition.

Note:
1.Function which is called by another Function is called Called Function. The called
function contains the definition of the function and formal parameters are
associated with them.
2. The Function which calls another Function is called Calling Function and actual
paramaters are associated with them.
3.In python, a function must be defined before the function calling otherwise
python interpreter gives an error.
Lambda function
Python lambda function doesn’t Example:
have any return statement.It has only
a single expression which is always
returned by default. The Python
lambda function is anonymous as it is
• add =
a function without a def keyword lambda x, y
and name. To create a Python
lambda function, we have to use the :x+y
lambda keyword. print(add(10
The basic syntax of python lambda is , 20))
Lambda arguments : expression • print("\nResult from
a Function")
The Python lambda function
accepts any number of • def add_func(x, y):
arguments but use only one
expression.
• return x + y
For instance, lambda a, b: a + b. • print(add_func(10,
Here, a and b are the arguments
accepted by the lambda function. a +
b is the expression.
20))

You might also like