SlideShare a Scribd company logo
Data Analytics Using Python
Python
• Python is a programming language that combines the features of C
and Java.
• When the programmers want to go for object orientation, python
offers class and objects like java.
• Python was developed by Guido Van Rossum in the year 1991 at the
center of Mathematics and computer Science managed by the Dutch
Government.
• Van Rossum picked the name python for the new language from the
TV show , “Monty Python’s Flying Circus”.
• The logo of Python shows two intertwined snakes.
Features of Python
• Simple: python is a programming language when we read a python
program , we feel like reading English sentences. It means more
clarity and less stress on understanding the syntax of the language.
• Easy to Learn: Python uses very few keywords. Its programs use very
simple structure so developing programs in python become easy.
• Open Source: There is no need to pay for python software. Python
can be freely downloaded from www.python.org.
• High Level Language: High Level languages use English words to
develop programs. These are easy to lern and use.
• Platform Independent: When a python program is compiled using a
python compiler, it generates byte code. Python’s byte code
represents a fixed set of instructions that run on all operating systems
and hardware. Using a python virtual machine, anybody can run
these byte code instructions on any computer system.
Features of Python
• Huge Library: Python has a big library which can be used on any
operating system. Programmers can develop programs very easily
using the modules available in the python library.
• Scripting Language: A scripting language is a programming language
that does not use a compiler for executing source code . Rather, it
uses an interpreter to translate the source code into machine code
while running.
• Database Connectivity: Python provides interfaces to connect its
programs to all major databases like Oracle, Sybase or MySql.
• Scalable: Python programs are scalable since they can run on any a
platform and use the features of the new platform effectively.
• Interpreter: A software which converts high-level language
instructions line-by-line into machine-level language is called an
interpreter.
Parts of Python programming Language
• Identifiers
• Keywords
• Statements and Expressions
• Variables
• Operators
• Precedence and associativity
• Data types.
• Indentation
• Comments
Parts of Python programming Language
Identifier: Identifier is a user-defined name given to a variable, function,
class, module or object. The identifiers are formed with a combination of
alphabets (A-Z or a-z), digits and underscore. All identifiers are case sensitive.
Here are naming conventions for python identifiers.
• Class names start with an uppercase letter. All other identifiers start with a
lowercase letter.
• Starting an identifier with a single leading underscore indicates that the
identifier is private.
• Starting an identifier with a two leading underscores indicates a strongly
private identifier.
• If the identifier also ends with two trailing underscore, the identifier is
language defined special name.
• Example: sum, total, s1, gross_salary
Parts of Python programming Language
Variable: A variable is a name used to store a value. The variable may change its value
during the execution of a program.
In Python, a variable need not be declared with a specific type before its usage. The
type of it will be decided by the value assigned to it.
Example:
a = 10
b = “hello”
c = 5.5
Rules to follow when naming variables
• Variable name can contain letters , numbers and underscore.
• Variable name cannot contain spaces and other special characters .
• Variable name should not start with a digit.
• Variable names are case sensitive i.e. ‘Total’ different from ‘total’.
• Keywords cannot be used as a variable name.
Example: valid variable names : total, a1,net_salary
invalid variable names: 1a, total salary
Parts of Python programming Language
Keywords: Keyword is a special word which is having a predefined
meaning. The meaning of the keyword cannot changed by a user.
Keywords are building blocks of the programming language.
Example: and, as, assert, break, continue, while and so on
Statements and Expressions:
A statement is a unit of code the python interpreter can execute . There
are mainly four types of statements in python.
i) Assignment statement ii) print statement iii) conditional statement
iv) Looping statements
Assignment statement: we assign a value to a variable using the
assignment statement by using assignment operator(=)
Example: a = 10
c = a + b
a, b, c = 10, 20, 30
Parts of Python programming Language
• print statement: print is a function which takes string variables as a
argument to display it on the screen.
Example: a = 10
print(a)
Optional arguments with print statement :
Sep: Python will insert a space between each of the arguments of the
print function. There is an optional argument called sep. For Example
sep = “ :” would separate the argument by a colon and sep = “ ## “
would separate the arguments by two hash symbols.
For example: print(“a” , ”b”, “c”, “d”, sep =“ ;”)
output: a;b;c;d
Parts of Python programming Language
Optional arguments with print statement :
end: The print function will automatically advance to the next line. For
example: print(“a”)
print(“b”)
print(“c”, end = “ “)
print(“d”)
output:
a
b
c d
Parts of Python programming Language
Expression: An expression is a combination of operands and operators
is called an expression. The expression in python produces some result
or value after being interpreted by the python interpreter.
for example: a = 10
a = a + 10
print(a)
output is 20
Operators, precedence and associativity
Operator is a symbol that perform either arithmetic or logical operation.
Arithmetic operators:
Operator meaning example
+ addition c = a + b
- subtraction c = a - b
* multiplication c = a * b
/ division c = 5 / 2 will give 2.5
// floor division c = 5 // 2 will give 2
% modulo division c = 5 % 2 will give 1
** exponent e = a ** b means a to the
power of b
Assignment operator
These operators are useful to store the right side value into a left side
variable.
For Example: a = 10
c = a + b
a += b (a = a + b)
Unary minus operator :
The unary minus operator is denoted by the symbol (-). When this operator
is used before a variable, its value is negated.
For example:
n = 10
print(-n)
The output is -10
Relational Operators
Relational operators compare two quantities. The following are the
relational operators. The following are the relational operators.
<, >, == , <= , >= , !=
The relational expression will return a value True or False depending on
the condition.
Example: print(5 > 3) returns True
print(5 < 3) returns False
Logical operators
Logical operators are useful to construct compound condition. A
compound is a combination of more than one simple condition. Each of
the simple condition is evaluated to true or false and then the decision
is taken to know whether the total condition is true or false.
Logical operators are ‘and’ , ‘or’ and ‘not’
For Example: print(5 > 2 and 8 > 3) returns True
print(5 > 8 or 3 > 9) returns False
print( not( 5 > 8)) returns True
Precedence and Associativity (order of operation)
When an expression contains more than one operator, the evaluation
of operators depends on the precedence of operators.
The python operators follow the precedence rule(Which can be
remembered as PEMDAS)
Parenthesis have the highest precedence in any expression. The
operations within parenthesis will be evaluated first.
Exponentiation: Has the 2nd precedence ,but ,it is right associative. if
there are two exponentiation operations continuously, it will be
evaluated from right to left.
For Example : print( 2 ** 3 ** 2)
2^3^2= 2^9 = 512
Precedence and Associativity (order of operation)
Multiplication and division are next priority : Out of these operations ,
whichever comes first in the expression is evaluated.
print( 5 * 2 / 4) = 5 *2 = 10 10/4 = 2.5
print( 8 / 2 * 3) = 8 / 2 = 4 4 * 3 = 12
Additions and subtractions are least priority: Out of these operations ,
whichever appears first in the expression is evaluated i.e. they are
evaluated from left to right.
print(5 + 3 – 2) = 5 + 3 = 8 – 2 = 6
print(8 -2 + 3) = 8 – 2 = 6 + 3 = 9
Precedence and Associativity (order of operation)
Ex example: x = 1 + 2 ** 3 / 4 * ( 5 – 2)
x = 1 + 2 ** 3 / 4 * 3
x = 1 + 8 / 4 * 3
x = 1 + 2 * 3
x = 1 + 6
x = 7
Data types
Data types specify the type of data stored in a variable like numbers
and characters. Basic data types are
. Numbers . Boolean . Strings. List, Tuple, Dictionary, None
Numbers: Integers ,floating point numbers and complex numbers fall
under python number category. They are defined as int, float and
complex class in python. Integers can be of any length. It is only limited
by the memory available. A floating number contains a decimal point
and have accuracy of 15 decimal places.
Complex numbers are written in the form x + y i. Where x is the real
part and y is the imaginary part.
Boolean: Python Boolean type is one of the built-in datatypes provided
by python, Which represents one of the two values i.e. True or False
Data Types
Strings
A string consists of a sequence of one or more characters, which can
include letters ,numbers and other type of characters. A string can also
contain spaces. You can use single quotes or double quotes to represent
strings and it is also called a string literal. Multline strings can be
denoted using triple quotes.
For Example: s1 = ‘welcome to python ‘
s2 = “welcome to python”
s3 = ‘’’ welcome
to
python ‘’’
Data Types
List: A list is formed by placing all the items inside square brackets[],
separated by commas it can have any number of items and they may or may
not be different types (integers, float, string,etc)
for example lst = [ 1,2,3,4.5,”python”]
Tuple : A tuple is defined as ordered collection of python objects. The only
difference between tuple and list is that tuples are immutable i.e. tuples
cannot be modified after it is created. We can represent tuples using
parenthesis ().
for example t = (1,2,3,4.5,”python”)
Dictionary: Dictionary is an unordered collection of data values. Dictionary
consists of key value pair. In python, a dictionary can be created by placing a
sequence of elements within curly braces({ }), separated by comma.
Dictionary holds pairs of values, one being its key and other corresponding
pair element its key: value. Values in a dictionary can be any data type and
can be duplicated, where as keys cannot be repeated and must be
immutable.
For example = { “usn”: 123, “name”: “xyz”, “marks”: 50}
Data Types
None: None is another special datatype in python. None is frequently
used to represent the absence of a value.
for example: money = none
Indentation
Code block1 begins
Code block2 begins
Code block3 begins
Code block2 continues
Code block1 continues
Usually, we expect indentation from any program code, but in python it is a
requirement and not be matter of style. This makes code look clearer and
easier to understand and read.
Any statements written under another statement with the same indentation
is interpreted to belong to the same code block. If there is a next statement
with less indentation to the left, then it just means the end of the previous
code block.
In other words, if a code block has to be deeply nested statements need to
be indented further to the right. In the above diagram , code block2 and
code block3 are nested under block1. Usually four white spaces or tab space
used for indentation. In correct indentation will result in indentation error.
Comments
As programs get bigger and more complicated, they get more difficult to
read. It is often difficult to look at a piece of code and figure out what it is
doing or why.
For this reason, it is a good idea to add notes to your programs to explain in
natural language what the program is doing. These notes are called
comments, and in python they start with the “#” symbol. Comments are
non-executable statements.
There are two types of comments:
1. Single line comment
2. Multiline comment
1. Single line comment: These comments start with a hash symbol (#) and
are useful to maintain that entire line till the end should be treated as
comment.
for example: # program to add two numbers
Comments
2. Multiline comments: When we want mark several lines as comment, then
writing # symbol in the beginning of every line will be tedious job.
Instead of starting every line with # symbol, we can write the “ “ “(triple
double quotes) or ‘ ‘ ‘(triple single quotes) in the beginning and ending of
the block as:
“ “ “ welcome to python
Hello world
data analytics
“ “ “
or
‘ ‘ ‘ welcome to python
Hello world
data analytic
‘ ‘ ‘
Reading input and output
To accept an input from keyboard, python provides the input function. This
function takes a value from the keyboard and return it as a string.
For Example:
str = input() # this will wait until we enter a string
print(str)
It is a better idea to display a message to the user so that the user
understands what to enter. This can be done by writing a message inside
input() function as
For Example:
str = input(“enter your name”)
print(str)
Reading input and output
We can use the int() function before the input()function to accept an
integer from the keyboard as
For Example:
x = int(input(“enter x”))
print(x)
Similarly to accept a float value from the keyboard, we can use float()
function along with the input() function
For Example:
x = float (input(“enter x”))
print(x)
Reading input and output
# A Python program to accept 3 integers in the same line separated by # space and display
their sum
For Example:
a, b, c = [ int(x) for x in input(“enter 3 no's”).split()]
print(“sum = “ , (a + b + c))
# A Python program to accept 3 integers in the same line separated by
# comma and display their sum
For Example:
a, b, c = [ int(x) for x in input(“enter 3 no's”).split( “,”)]
print(“sum = “ , (a + b + c))
# Evaluating an expression entered from keyboard
For Example:
x = eval(input(“enter an expression”))
print(x)
input: 10 + 5 – 4
output : 11
Printing Output
Format operator: The format operator , % allows us to construct
strings, replacing parts of the strings with the data stored in variable.
For Example, the format sequence ”%d” means that the operand should
be formatted as an integer.
a = 10
“%d” %a
“ 10”
A format sequence can appear anywhere in the string. So you can
embed a value in a sentence.
For Example: a = 10
“ The value of a is %d” % a
output: “the value of a is 10”
Printing Output
If there is more than one format sequence in the string, the second
argument has to be a tuple. Each format sequence is matched with an
element of the tuple, in order.
The following example uses “%d” to format an integer, %g to format a
floating point number, and “%s” to format a string.
“in %d years I spotted %g %s” %(3, 0.1 , “camels”)
output: “in 3 years I spotted 0.1 camels
Format function: is one of the string formatting methods in python3,
Which allows multiple substitutions and value formatting. This method
lets us concatenate elements within a string through positional
formatting.
Two types of parameters:
• Positional argument
• Keyword argument
Printing Output
Positional argument: It can be integers, floating point numbers, strings,
characters and even variables.
Keyword argument : They are essentially variable storing some value, which
is passed as parameter. Positional arguments are placed in order.
For Example: print(“ {0} college {1} department” . format(“Atria”, mca”))
Output: Atria college mca department
Positional arguments are not specified, by default it starts positioning from
zero
For Example: print(“ {} college {} department” . format(“Atria”, mca”))
Output: Atria college mca department
.
Printing Output
Printing Output
Printing Output
Keyword arguments are called by their keyword name.
For Example:
print(“MCA department has {0} sections in {college}”. format(“2”,
college = “Atria”))
Output: MCA department has 2 sections in Atria
f- strings : Formatted strings or f-strings were introduced in python
3.6. A f-string is a string literal that is prefixed with ‘f’ . These strings
may contain replacement fields, which are expressions enclosed within
curly braces { }.
For Example: a = 10
print(f “the value of a is { a})
output : the value of a is 10
Type conversion functions
Python provides built-in functions that convert values from one type to another.
int():
ex1: int(“32”) # string to integer
32
ex2: int(“hello”)
value error
ex3: int(3.56) # float to integer
3
ex4: int(-2.34) # float to integer
-2
float() :
ex1: float(32) # convert integer to float
32.0
ex2: float(“3.124”) convert string to float
3.124
str() : ex1: str(32)
“ 32”
ex2: str(3.124)
“3.124”
The type() function
type() function is used to know the datatype of the value. The
expression in parenthesis either a value or a variable.
Ex1: type(10)
output: <class int>
Ex2: type(10.5)
output: <class float>
Ex3: type(“hello”)
output: <class str>
Ex4: a = 10
type(a)
output: <class int>
The is operator
The ‘is’ operator is useful to compare whether two objects are same or
not. It will internally compare the identity number of the objects. If the
identity numbers of the objects are same, it will return True;
Otherwise, it returns False.
For Example: a = 25 id(a) 1670954952
b = 25 id(b) 1670954952
a is b
output: True
When two variables are referring to same object, they are called as
identical objects.
When two variables are referring to different objects, but contain a
same, they are known as equivalent objects.
The is operator
For Example: s1 = input(“enter s1”) # if input hai
s2 = input(“enter s2”) # if input hai
s1 is s2 # output false
s1 == s2 # output true
Control flow statement
if statement: This statement is used to execute one or more statement
depending one or more statement depending on whether a condition
is True or not. The general form is:
if condition:
statements
First, the condition is tested. If the condition is True, then the statements given
after colon(:) are executed. If the condition is False, then the statements mentioned
after colon are not executed.
# program to find the biggest of two numbers
a = int(input(“enter a”))
b = int(input(“enter b”))
big = a
if b > big:
big = b
The if – else statement
The if – else statement executes a group of statements when a
condition is true; Otherwise, it will execute another group of
statements .
The general form of if – else statement is as follows:
if condition:
statements1
else:
statements2
If the condition is True, then it will execute statements1 and if the
condition is False, then it will execute statement2.
The if – else statement
# To check whether the given number is even or not
n = int(input(“enter n”))
if n % 2 == 0:
print(“even no”)
else:
print(“odd no”)
The if – elif – else statement
Sometimes, the programmer has to test multiple conditions and execute
statements depending on those conditions if – elif – else statement is useful
in such situations.
The general form of if – elif – else statement is as follows
if condition1:
statement1
elif condition 2:
statement2
elif condition 3:
statement3
-
-
else:
statement4
The if – elif – else statement
Here, the conditions are tested from top to bottom as soon the true
condition is found, then the associated statements are executed. After
the execution, the control will be transferred below if—elif –else
statement.
Example : # to check whether the given number is positive, negative or
# equal to zero
n = int (input(“enter n “))
if n > 0:
print(“positive number”)
elif n < 0:
print(“negative number”)
else:
print(“equal to zero”)
Nested if statement
In if statement , another if statement exists then it is called nested if
statement.
# program to check whether the given number is positive and even or
# odd
n = int(input(“enter n”))
if n > 0:
if n % 2 == 0:
print(“positive and even number”)
else:
print(“ number is positive and odd”)
else:
print(“the number is not positive”)
Looping statements
Repeatedly executing a block of statements is called a loop.
While loop: The while loop is useful to execute a group of statements
several times depending on the condition is true or false. The general
form is as follows:
while condition:
statements
Python interpreter first checks the condition. If the condition is true,
then it will execute the statements written after colon(:) . After
executing the statements, it will go back and check the condition again.
If the condition is again found to be true, then it will execute the
statements. In this way, as long as condition is true, python interpreter
executes statements again and again. Once the condition is found to
be false, then it will come out of the loop.
While loop
# program to display numbers from 1 to 10
x = 1
while x <= 10:
print(x)
x = x + 1
The for loop
The for loop is useful to iterate over the elements of a sequence. It
means, the for loop can be used to execute a group of statements
repeatedly depending upon the number of elements in the sequence.
The for loop work with sequence like string, list and tuple. The syntax
of the for loop is given below:
For var in sequence:
statements
The first element of the sequence is assigned to the variable written
after for and then statements are executed. Next, the second element
of the sequence is assigned to the variable and then the statements are
executed second time. In this way, for each element of the sequence ,
the statements are executed once. So, the for loop is executed as many
times as there are number of elements in the sequence.
The for loop
# a python program to display the characters of a string using for loop
str = “hello”
for ch in str:
print(ch, end = “ “)
Output: h e l l o
Syntax of for loop with range() function:
for variable in range(start, end, steps):
statements to be repeated
The start and end indicates starting and ending values in the sequence,
where end is excluded in the sequence that is sequence is up to
end – 1. The default value of start is 0. The argument steps indicates
the increment / decrement in the values of the sequence with the
default value as 1. Hence the argument steps is optional.
The for loop
# program to print the message multiple times
for i in range (3):
print(“hello”)
Output: hello
hello
hello
# program to print numbers in sequence
for i in range(5):
print(i, end = “ “)
output: 0 1 2 3 4
#program to display numbers from 5 to 1
for i in range(5,0,-1):
print(i, end = “ “)
Output: 5 4 3 2 1
for loop
# program to display odd numbers from 1 to 10 using range function
for i in range(1,10,2):
print(i, end = “ “)
output: 1 3 5 7 9
Nested loops
It is possible to write one loop inside another loop is called nested
loops.
For Example: for i in range(2):
for j in range(3):
print(“ I =“, I “t”, “j = “,j)
Output: i = 0 j =0 i = 1 j = 0
i = 0 j = 1 i = 1 j = 1
I = 0 j = 2 I = 1 j = 2
The break statement
The break statement is used to terminate a loop when an unusual
condition occurs in the body of the loop.
For Example:
for i in range(10):
if i == 4:
break
print(i, end = “ “)
output: 0 1 2 3
The continue statement
The continue statement is used in a loop to go back to the beginning of the
loop. It means, when continue is executed, the next repetition will start
when continue is executed, the subsequent statements in the loop are not
executed.
# program to print odd numbers
for i in range(1,10):
if i % 2 == 0:
continue
else:
print(I, end = “ “)
Output: 1 3 5 7 9
Functions
• A sequence of instructions intended to perform a specific
independent task is known as a function.
• You can pass data to be processed, as parameters to the function.
Some functions can return data as a result.
Function types
• Built-in types
• User defined functions
Built-in Function
• Python provides a number of built-in functions that we can use
without needing to provide the function definition
• Built-in functions are ready to use functions
Functions
Commonly used modules:
Math functions: python has a math module that provides
most of the frequently used mathematical functions. Before
we use the those functions, we need to import the module as
below.
ex: import math
Some of the functions in math module are:
Function Description
ceil(x) Raises x value to the next higher
integer. If x is an integer, then
same value is returned.
Ex: ceil(4.3) gives 5
Math functions
Function Description
floor(x) Decreases x value to the
previous value. If x is an
integer, then the same value
is returned. Ex: floor(4.5) gives 4
degree(x) converts angle value x radians
into degree
radians(x) converts x value from degrees
into radians
Math functions
Functions Description
sin(x) gives sine value of x. Here x
value is given in radians
cos(x) gives cos value of x. Here x
value is given in radians
fabs(x) gives the absolute value for
positive quantity of x
Ex: fabs(-4.5) gives 4.5
fatorial(x) Returns factorial of x.
Math functions
Functions Descriptions
fmod(x, y) Returns remainder of division
of x and y. fmod() is used to
calculate the modulus of float values
ex: fmod(14.5,3) gives 2.5
modf(x) returns float and integral parts of x
ex: modf(2.56) (0.56,2.0)
sqrt(x) returns positive square root of x
sqrt(16) = 4
Math functions
Function Description
pow(x, y) Raises x value to the power of y
ex: pow(2,3) = 8
gcd( x, y) gives the greatest common
divisor of x and y.
gcd(14,10) = 2
trun(x) The real value of x is truncated
to integer value. Trun(12.3)
gives 12.
Math.pi the mathematical constant
Random numbers
• Most of the programs that we write take predefined input values and
produces expected output values such programs are said to be
deterministic.
• Making a program truly non deterministic turns out to be not so easy, but
there ways to make it at least seem non-deterministic. One of them is to
use algorithms that generate pseudo-random numbers.
• The function random returns a random float between 0.0 to 0.1 and for
integers( 1 and 100 )
• Python has a nodule called random, in which functions related to random
numbers are available.
To generate random numbers. Consider an example to generate random
numbers
import random
for i in range(5):
x = random.random()
print(x)
Random numbers
• The function randint() takes the parameters low and high, and returns
an integer between low and high, and returns an integer between low
and high (including both)
import random
random.randint(5,10)
The output may be between 5 and 10. for ex: 6, or, 7 or 9
To choose an element from a sequence from a sequence at random
you can use choice
import random
t = [ 1, 2, 3, 4]
random.choice(t)
Output: it can choose any element from the list
Some of Built-in Functions
max() ex: max(“hello world”)
output: w display the character having maximum ASCII code
min() ex: min(‘hello world’)
output: ‘ ‘ display the character having minimum ASCII code
len() ex: len(“ hello”)
output: 5 display the length of the string
User-defined functions
The general syntax of a user-defined function:
def fname(arg list):
statement1
statement2
--------------
---------------
statement n
return value
def: is a keyword indicating it as a function definition
fname: is any valid name given to the function
arg list: is list of arguments taken by a function. These are treated as inputs
to the function from the position of function call. They may be zero or more
arguments to a function.
statements : are the list of instructions to perform required task
return: is a keyword used to return the output value. This statement is
optional.
User-defined functions
• The first line in the function def fname(arg list): is known as function
header function definition. The remaining lines constitute function
body.
• The function header is terminated by a colon and body must be
indented.
• To come out of the function, indentation must terminated.
# program to add two numbers using function
def add(a, b):
c = a + b
return c
s = add(10,20) # function call
print(s)
Void Functions
A function that performs some task, but do not return any value to the
calling function is known as void function.
Example:
def add():
a = 10
b = 20
c = a + b
print(c)
add() #function call
Fruitful functions: The function which returns some result to the calling
function after performing a task is known as fruitful function. All built-in
functions are called fruitful function.
Scope and lifetime of variables
• All variables in program may not be accessible at all locations in that
program. This depends on where you have declared a variable.
• The scope of a variable determines the portion of the program where
you can access a particular variable. There are two basic scope of
variables in python:
global variables
local variables
Global versus local variables:
• Variables that are defined inside a function body have a local scope,
and those defined outside have global scope.
• This means that local variables can be accessed only inside the
function in which they are declared. Where as global variables can be
accessed throughout the program body by all function.
Scope and lifetime of variables
# program to demonstrate global and local variables
total = 10
def add(a, b):
total = a + b # here total is local variable
print(total)
add(10,20)
print(total) # here total is global variable
output: 30
10
Default arguments
• For some functions, you may want to make some parameters optional
and use default values. In case the user does not want provide values
for them. This is done with the help of default argument values.
• Default argument values can be specified for parameters by
appending to the parameter name in the function definition. The
assignment operator(=) followed by the default value
• Note that the default argument value should be a constant
• Only the parameters which are at the end of the parameterlist can be
default values.
For example: def add(a, b = 5): is valid
def add(a = 5,b): is invalid
Default arguments
# program to demonstrate default arguments
def add(a, b = 5):
c = a + b
print(c)
add(10,20)
add(30)
If we specify the argument values, then it will not take default value. If do
not have a corresponding value for a argument then it will take a default
value.
Output for first function is 30
Output for first function is 35
Keyword Arguments
If you have some functions with many parameters and you want to
specify only some of them, then you can give values for each
parameters by naming from them, this is called keyword arguments.
We use the name instead of the position to specify the arguments to
the function.
There are two advantages:
1. Using the function is easier since we do not need to worry about the
order of the arguments
2. We can give values to only those parameters to which we want to
provided that the parameter have default argument values.
Keyword Arguments
# program to demonstrate keyword arguments
def func(a, b = 5 , c = 10):
print(“a is “,a, “and b is”, b, ”and c is”,c)
func(3,7)
func(25,c = 24)
func(b = 20, a =100)
Output:
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 20 and c is 10
*args and ** kwargs
• Sometimes you might want to define a function that can take any
number of parameters, i.e. variable number of arguments, this can be
achieved by using the stars.
• *args and ** kwagrs are mostly used as parameters in function
definition. *args and ** args allows you to pass a variable number of
arguments to the calling function. Here variable number of
arguments means that the user does not know in advance about how
many arguments will be passed to the called function.
• *args as parameters in function definition allows you to pass a non-
key worded, variable length tuple argument list to the called
function.
• **kwargs as parameter in function definition allows you to pass key
worded. Variable length dictionary argument list to the called
functions.
• *args come after all the positional parameters and **kwargs must
come right at the end.
*args and ** kwargs
# program to demonstrate *args and ** kwargs
def func(a = 5, *numbers,**names):
print(“a = “, a)
for i in numbers:
print(i)
for fp,sp in names.items():
print(fp,sp)
func(10,20,30,40,xxx = 40, yyy = 50 zzz = 60)
output : a = 10
20
30
40
zzz 60
yyy 50
xxx 40
Command line arguments
The ‘sys’ module provides a global named ‘argv’ that is list of extra text
that the user can supply when launching an application from the
command prompt.
# Python program to display command line arguments
import sys
n = len(sys.argv)
print(“no of command line args =‘, n)
print(“the arguments are”, args)
print(“the args one by one”)
for x in args:
print(x)
To run a program like this
C:> python cmd.py 10,20,hello
output : no of command line args = 3
The arguments are [‘10’,’20’,’hello’]
Command line arguments
#python program to add numbers using command line arguments
import sys
args = sys.argv
sum = 0
for x in args:
sum = sum + int(x)
print(sum)
To run this program
c:> python sum.py 10 20 30
output 60
Module-2
String: A string is a sequence of characters, Which include letters,
numbers, punctuation marks and spaces.
Creating and storing strings
A string can be created enclosing text in single or double quotes.
s = “hello”
s1 = ‘python’
To nullify the effect of escape characters, we can create the string as
‘raw’ string by adding ‘r’ before the string as
s = r “welcome to t core python n learning”
print(s)
Output: welcome to t core python n learning
Strings
Length of a string: Length of a string represents the number of characters in
a string. To know the length of a string, we can use the len() function.
s = “hello”
l = len(s)
print(l)
output: 5
Basic string operations:
1. Repeating the strings: The repetition operator is denoted by * symbol
and is useful o repeat the string for several times.
For ex: str * n repeats the string for n times.
s = “hai”
print(s * 3)
output: hai hai hai
Strings
2. Concatenation of strings: We can use ‘+’ on strings to attach a string
at the end of another string.
s1 = “hello”
s2 = “world”
s3 = s1 + s2
print(s3)
Output: Hello world
3. In operator: The in operator returns true if string or character found
in the main string. It returns false if the string or character is not found
in the main string.
Strings
# python program to check whether a substring exists in main string or
# not
str = input(“enter a main string”)
sub = input(“enter a sub string”)
if sub in str:
print(“sub string present in main string”)
else:
print(“sub string is not present in main string”)
Strings
4. Comparing strings: We can use the relational operators like >, ==, <, == or
!= operators to compare two strings. They return Boolean value i.e. either
True or False depending on the strings being compared.
s1 = “box”
s2 = “boy”
if s1 == s2:
print(“same”)
else:
print(“not same”)
This code returns ‘not same’ as the strings are not same. While comparing
the strings, python interpreter compares them by taking them in English
dictionary order. The string which comes first in the dictionary order will
have low value than the string which comes next. It means ‘A’ is less than ‘B’
which is less than ‘C’ and so on.
Strings
# python program to compare two strings
s1 = input(“enter a string1”)
s2 = input(“enter a string 2”)
if s1 == s2:
print(“strings are equal”)
elif s1 < s2:
print(“strings are not equal”)
else:
print(“s1 is greater than s2”)
Strings
# Accessing characters in string by index number (Traversing in a st
ring”)
str = “hello”
index = 0
while index < len(str):
print(str[index], end = “ “)
index = index + 1 # output h e l l o
# Another way to traversal a string
str = “hello”
for ch in str:
print(ch, end = “ “) # output h e l l o
Strings
Accessing characters in string by index number:
• We can get at any single character using an index specified in square
brackets.
• The index value can be an integer and starts at zero.
For example: str = “python”
Character
index
str = “python”
print(str[0]) # output p
print(str[3]) #output h
P Y T H 0 N
0 1 2 3 4 5
Strings
Python supports negative indexing starting from the end of the string
as shown below.
Character
index
str = “python”
print(str[-3]) #output h
print(str[-1]) #output n
p y t h o n
-6 -5 -4 -3 -2 -1
Strings
String Slicing:
• A segment or a portion of a string is called as slice.
• Only required number of characters can be extracted from string
using (:) symbol.
The basic syntax of slicing a string:
String_name[start : end : step]
Where,
start: the position from where it starts.
end: the position where it stops(end – 1)
step: also known as stride, is used to indicate number of steps to
incremented after extracting first character. The default value of stride
is 1.
Strings
String slicing continued:
• If start is mentioned, it means that slice should start from the
beginning of the string.
• If the end is not mentioned, it indicates the slice should be till end of
the string.
• If both are not mentioned, it indicates the slice, should be from the
beginning till the end of the string.
For example: S = “abcdefghij”
Character
Index
Reverse index
a b c d e f g h i j
0 1 2 3 4 5 6 7 8 9
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Strings
String slicing continued:
Slicing Result Description
S[2:5] cde Characters at
indices 2,3,4
S[:5] abcde First five characters
S[5:] fghij Characters at index
5 to the end
S[-2:] ij Last two characters
S[:] abcdefghij Entire string
S[1:7:2] bdf Characters from
index 1 to 6 by step
2
S[::-1] jihgfedcba A negative step
reverses the string
String methods
capitalize() : Make the first character have upper case and the rest
lower case.
Example:
str = “hello”
print(str.capitalize())
Output: Hello
find: This method return the location of the first string occurrence of
the sub string from the main string. The find method return -1, if the
substring is not found in the main string. The general form is:
mainstring.find(substring, beg, end)
For example: str = “hello”
str1 = “hello world”
print(str.find(“l”)) #output 2
print(str.find(“x”)) # returns -1
print(str1.find(“o”,6,9) # returns 6
String methods
strip(): Return copy of the string with leading and trailing white spaces.
For Example: str = “ hello world “
print(str.strip())
output: hello world
strip(chars): If chars is given, remove characters specified at both the
ends.
For example: str = “ ### hello ###”
print(str.strip(“#”))
output: hello
rstrip(): is to remove white spaces at right side.
For Example: str = “hello “
print(str.rstrip())
output: hello
String methods
lstrip() : it is used to remove the white spaces at left side,
For Example: str = “ hello”
print(str.lstrip()) # output: hello
casefold(): It is an advanced version of lower() method. It converts the upper
case letters to lower case letters including some special characters which are
not specified in the ASCII table.
For Example: str1 = “india”
str2 = “INDIA”
print(str1.casefold() == str2.casefold())
output: returns a value true
startswith(): method returns true if the string starts with the specified value,
Otherwise, false.
General form is :
string.startswith(value, start, end)
Value: Required. The value to check if string starts with.
Start: Optional. An integer specifying at which position to start the search.
End: Optional. An integer specifying at which position to end the search
String methods
For Example: str = “logical”
print(str.startswith(“l”)) #returns true
print(str.startswith(“g”)) # returns false
print(str.startswith(“l”,2,5) # returns false
join() : It is used to join elements of the sequence separated by a string separator. This
function joins elements of a sequence and makes it a string.
For Example: str1 = “-”
str2 = “abc”
print(str1.join(str2))
output: a-b-c
split(): The split method is used to brake a string into pieces. These are returned as a list.
For example: str = “one, two, three, four”
str1 = str.split(“,”)
print(str1)
output: [ “one”, two”, ”three”, ”four”]
String methods
lower(): The lower method converts the capital letters into lowercase
letters.
For Example: str = “HELLO”
print(str.lower()) # output hello
upper(): The upper method is used to convert all the characters of a string
into uppercase.
swapcase(): This method is used to converts letters into lower case letters
and vice versa.
str = “python is future”
print(str.swapcase())
output: PYTHON IS FUTURE
title : The title method converts the string such that each word in the string
starts with a capital letter and remaining will be lowercase letters.
For Example: str = “python is future”
print(str.title())
output: Python Is Future
String methods
count(): This method is used to count the number of substrings occurs in a
main string.
str = “hello”
print(str.count(“l”))
output : 2
replace(): This method is useful to replace a substring in a string with
another sub string. The general form is:
stringname.replace(old, new)
for Example: str = “this is a beautiful college”
str1 = “college”
str2= “flower”
str3 = str.replace(str1,str2)
print(str3)
output: this is a beautiful flower
String methods
isalpha(): Returns true if the string has at least one character and all
characters are alphabets(A to Z and a to z). Otherwise, it returns false.
For example: str =“hello”
print(str.isalpha())
output: True
Note: Strings are immutable, an immutable object is object whose
content cannot be changed. In python numbers, strings and tuple are
immutable. Lists, sets, dictionaries are mutable objects.
Sorting strings
We can sort a group of strings into alphabetical order using sort()
method and sorted() function. When sort() method is used, it will sort
the original array i.e. str. So the original order of strings will be lost and
will have only one sorted array. To retain the original array even after
sorting, we can use sorted() function.
str1 = sorted(str)
Here, str is the original array whose elements are to be sorted. After
sorting the array, the sorted array will be referenced by str1. So, the
sorted strings appear in str1. The original array ‘str’ is undistributed.
Sorting strings
# python program to sort strings in alphabetical order
str = [] # empty string
n = int(input(“enter how many strings”))
print(“enter strings”)
for i in range(n):
str.append(input())
str1 = sorted(str)
print(“sorted list”)
for i in str1:
print(i)
Lists
A list is similar to an array that consists of a group of elements or items. The values
inside the lists can be of any type like integers, float, strings and so on. The
elements of the lists are enclosed within square brackets.
Creating a list with numbers:
lst = [10,20,30,40]
Creating a list with strings:
s = [“xxx”, “yyy”, “zzz”]
Creating a list with different types:
lst = [10,20,30,40.5,”xxx”]
Nested lists can be created as follows:
l1 =[10,20,30]
l2 = [40.5, “xxx”]
l3 = [ l1,l2]
Lists
Creating a list using range function:
1. l1 = range(4)
print(l1)
Output: [0,1,2,3]
2. l1 = range(5,10)
print(l1)
output: [5,6,7,8,9]
3. l1 = range(5,10,2)
print(l1)
output: [5, 7, 9]
Lists
Concatenation of lists:
l1 = [10,20,30]
l1 = l1 + [40,50]
print(l1)
Output: [10,20,30,40,50]
Accessing the elements with in the inner list can be done by double
indexing.
For example: l = [ [10,20],[xxx, yyy]]
print(l[1][0])
output: xxx
List slicing
We can make a new list from a portion of an existing list using a
technique known as slicing. A list slice is an expression of the form:
list_name[begin: end: step]
• If the begin value is missing, it default to 0(zero)
• If the end value is missing, it default to the length of the list
• The default step value is 1.
list
index
Reverse index
10 20 30 40 50 60 70 80 90 10
0 1 2 3 4 5 6 7 8 9
-10 -9 -8 -7 -6 -5 -4 -3- -2 -1
List slicing
For example:
lst = [10,20,30,40,50,60,70,80,90,100]
print(lst) # output [10,20,30,40,50,60,70,80,90,100]
print(lst[0:3]) # [output 10,20,30]
print(lst[4:8]) # output [50,60,70,80]
print(lst[-5:-3]) # output [60,70]
print(lst[:3]) # output [10,20,30]
print(lst[4:]) # output [50,60,70,80,90,100]
print(lst[:]) # output [10,20,30,40,50,60,70,80,90,100]
print(lst[-100:3]) #output [10,20,30]
print(lst[4:100]) # output [50,60,70,80,90,100]
print(lst[2:-2:2]) #output [30,50,70]
print(lst[::2]) # output [10,30,50,70,90]
List slicing
A begin value less than zero treated as zero.
Ex: lst[-100:3]
A end value greater than the length of the list is treated as the length of
the list.
Ex. Lst[4:100] # here 100 is treated as len(lst)
Cloning of lists:
x = [10,20,30,40]
y = x[:]
print(x) # output [10,20,30,40]
print(y) # output [10,20,30,40]
Lists
Built-in functions used on lists :
There are several built-in functions that operate on lists. Here some useful
functions.
len – returns the number of items in the list
sum – returns the sum of items in the list
min – returns the minimum in the list
max – returns the maximum element in the list
#program to demonstrate built-in functions
lst = [30, 10, 50,40,20]
print(“length =“, len(lst)) # output 5
print(“sum = “, sum(lst)) # output 150
print(“min =“, min(lst)) # output 10
print(“max =‘, max(lst)) #output 50
Methods to process lists
Method Example Description
Index() lst.index(x) Returns the first occurrence of x in
the list
append() lst.append(x) Appends x at the end of the list
insert() lst.insert(i, x) Inserts x to the list in the position
specified by i
copy() lst.copy() Copies all the list elements into a
new list and returns 1
extend() lst.extend(list1) Appends list1 to list
count() lst.count(x) Returns the number of occurrences
of x in the list
remove() lst.remove(x) Removes x from the list
pop() lst.pop() Removes the ending element from
the list
Sort() lst.sort() Sorts the elements of the list into
ascending order
reverse() lst.reverse() Reverses the sequence of elements
from the list
clear() lst.clear() Deletes all elements from the list
Lists
# a python program to demonstrate list methods
lst = [10, 20, 30, 40, 50]
lst.append(60)
print(“after appending 60 :”,lst)
lst.insert(2,15)
print(“list after inserting 15 at 2nd position: ”,lst)
lst1 = lst.copy()
print(“newly created list1 : “, lst1)
lst.extend(lst1)
print(“list after appending list1 :”, lst)
c = lst.count(50)
print(“number of times 50 found in the list:”,c)
lst.remove(50)
print(“list after removing 50”,lst)
lst.pop()
print(“list after removing ending element:”, lst)
Lists
# a python program to demonstrate list methods
lst.sort()
print(“list after sorting :”,lst)
lst.reverse()
print(“list after reversing:”, lst)
lst.clear()
print(“list after clearing all elements:”,lst)
For Example: lst.sort() :- This will sort list in ascending order. If we want to
sort the elements of list into descending order, then we can mention reverse
= “True”
in the sort function.
lst.sort(reverse = True)
Lists
# python program to find the biggest element in the list
lst = []
print(“how many elements”)
n = int(input(“enter how many elements”))
print(“enter elements”)
for i in range(n):
lst.append(int(input())
print(“contents of list:”, lst)
big = lst[0]
for i in range(1,n):
if lst[i] > big:
big = lst[i]
print(“biggest element = “, big)
Lists
# Finding common elements in the list
lst1 = [10,30,40,50,60]
lst2 = [20,30,50,70]
s1 = set(lst1) #converts list into set
s2 = set(lst2) #converts list into set
s3 = s1.intersection(s2)
common = list(s3) # converting set to list
print(common)
Sets
A set in python programming is an unordered collection data type that
is iterable, mutable and has no duplicate elements. We use curly
braces({}) to enclose the elements of the set.
For example: s = {10,20,30,40}
Set operation:
s1 = {0,2,4,6,8}
s2 = { 1,2,3,4,5}
print(“union of s1 and s2 :”, s1 | s2)
print(“intersection of s1 and s2 :”, s1 & s2)
print(“difference of s1 and s2 :”, s1 - s2)
print(“symmetric difference of s1 and s2 :”, s1 ^ s2)
Sets
Operations on Sets:
Operation Python syntax Meaning
Union A | b Elements in A or
B or both
Intersection A & B Elements
common to both
A and B
Set difference A – B Elements in A
but not B
Symmetric
difference
A ^ B Elements in A or
B but not both
Tuple
A tuple is a python sequence which stores a group of elements or items. Tuples are
similar to lists but the main difference is tuples immutable where as lists are
mutable. Since tuples are immutable, once we create a tuple we cannot modify
elements. Tuples are generally used to store data which should not be modified
and retrieve that data on demand.
Tuples are enclosed with the parenthesis:
t = (10,20,30,40)
t1 = (10,20,30.5,”xxx”)
Accessing the tuple elements (slicing):
t = (10,20,30,40,50)
print(t[0]) # output 10
print(t[:]) # output (10,20,30,40,50)
print(t[1:4]) # output is (20,30,40)
print(t[::2]) # output is (10,30,50)
Tuple
Functions available to process tuples:
Function/method Example Description
len() len(t) Returns the number of
elements in the tuple
min() min(t) Returns the smallest
element in the tuple
max() max(t) Returns the biggest
element in the tuple
Count() t.count(x) Returns how many times
the element x is found in
tuple
index() t.index() Returns the first
occurrence of the element
x in tuple. Raises value
error if x is not found in
the tuple.
Sorted() sorted(t) Sorts the elements of the
Dictionaries
A dictionary represents a group of elements arranged in the form of
key-value pairs. In the dictionary, the first element is considered as key
and the immediate next element is taken as its value. The key and value
are separated by a colon(:). All the key key-value pairs in a dictionary
are inserted in curly braces ({}).
For Example: dict = {“id” : 123, “name”: “xxx”, “salary”:9000)
key value key value key value
# A python program to create a dictionary with employee details and
# retrieve the values upon giving the key.
dict = {“id” : 123, “name”: “xxx”, “salary”:9000)
print(“id number =‘, dict[“id”])
print(“name = “, dict[“name”])
print(“salary = “, dict[“salary”])
Dictionaries
Operations on Dictionaries:
1. If we want know how many key-value pairs are there in a dictionary, we
can use the len() function.
dict = {“id” : 123, “name”: “xxx”, “salary”:9000}
n = len(dict)
print(“number of key-value pairs =“, n) #output 3
2. We can modify the existing value of a key by assigning a new value, as
shown in the following statement.
dict[“salary”] = 9500
3. We can also insert a new key-value pair into an existing dictionary. This is
done by mentioning the key and assigning a value to it, as shown in the
following statements.
dict[“dept”] = “sports”
Dictionaries
This pair is stored in the dictionary. If we print the dictionary created in
the previous statement appears as shown below.
print(dict)
Output: {“id”:123, “dept”: “sports”, “name”: “xxx”, “salary”: 9500}
Observe that “dept”: “sports” is added to the dictionary. Also, observe
that this pair is not added at the end of the existing pairs. It may be
added at any place in the dictionary.
Suppose, we want to delete a key-value pair from the dictionary, we
can use ‘del’ statement.
del dict[“id”]
This will delete the key “id” and its corresponding value from
dictionary. Now, the dictionary look like this:
{“dept”:”sports, ”name”: “xxx”, “salary” : 9500}
Dictionary methods
Method Example Description
clear() d.clear() Removes all key-value pairs
from dictionary
copy() d1 = d.copy() Copies all the elements from ‘d’
into a new dictionary ‘d1’
get() d.get( k[,v]) Returns the value associated
with key ‘k’
items() d.Items() Returns an object that contains
key-value pairs of ‘d’
keys() d.keys() Returns a sequence of keys
from the dictionary d.
values() d.values() Returns a sequence of values
from the dictionary
update() d.update(x) Adds all elements from
dictionary ‘x’ to ‘d’
Dictionary
# a python program to create a dictionary from keyboard and display
the elements
dict = {} # empty dictionary
n = int(input(“how many key-value pairs”))
for i in range:
print(“enter key”, end = “ “)
k = input() # key is string
print(“enter its value:”, end = “ “)
v = int(input())
dict.update({k:v})
print(dict)
Files
A file is a collection of related information stored on a disk
permanently.
Opening a file: To perform a operation on file, we must open a file.
The general form of opening a file is.
File handler = open(“filename”, ”open mode”)
Here, ‘file name’ represents a name on which the data is stored . The
file ‘open mode’ represents the purpose of opening file.
The file opening modes:
File open mode Description
w To write data into a file. if any data is already present in
the file, it would be deleted and present data will be
stored.
r To read data from the file. The file pointer is positioned at
the beginning of the file
The file opening modes
File open mode Description
a To append data to the file, Appending means adding at the end
of the existing file. The file pointer is placed at the end of the
file. If file does not exists, it will create a new file for writing
data.
w+ To write and read data of a file. The previous data in the file
will be deleted.
r+ To read and write into a file. The previous data in the file will
not be deleted. The file pointer is placed at the beginning of
the file.
a+ To append and read data of a file. The file pointer will be at
end of the file if the file exists, If file does not exists, it creates
a new file for reading and writing.
x To open a file in exclusive creation mode. The file creation fails
if the file already exists.
Files
For example: f = open(“abc.txt”, “w”)
Here, ‘f’ represents the file handler or file object. It refers to the file
with the name “abc.txt” that is opened in “w” mode. This means, we
can write data into the file but we cannot read data from this file. If the
file already exists, then its contents are deleted and the present data is
stored into the file.
Closing a file: A file which is opened should be closed using the close()
method. Once a file is opened but not closed, then the data of the file
may be corrupted or deleted in some cases. Also, if the file is not
closed, the memory utilized by the file not freed, leading to problems
like insufficient memory. This happens when we are working with
several files simultaneously. Hence it is mandatory to close the file
f.close()
Files
# python program to create a file (write a data) and read data from the
# file
f = open(“abc.txt”, ”w”)
str = input(“enter a text”)
f.write(str)
f.close()
f = open(“abc.txt”, ”r”)
str1 = f.read()
print(str1)
f.close()
Files
# a python program to store a group of strings into a text file and
# retrieve it.
f = open(“xyz.txt”, ”w”)
print(“enter text ( @ at end) : “)
while str != “@”:
str = input()
if str != “@”:
f.write(str + “n”)
f.close()
f = open(“xyz.txt”, ”r”)
print(“file contents”)
str1 = f.read()
print(str1)
f.close()
Files
# python program to count number of lines, words and characters in a # text
f = open(“abc.txt”, “w”)
print(“enter a text @ at end:”)
while str != “@”
str = input()
if str != “@”:
f.write(str + n)
f.close()
f = open(“abc.txt”, “r”)
cl = cw = cc = 0
for line in f:
words = line.split()
cl = cl + 1
cw = cw + len(words)
cc = cc + len(line)
print(“number of lines = “, cl)
print(“number of words = “,cw)
Class
The mechanism that allows us to combine data and operations on those data
into a single unit is called class. The general form of class is:
A class is created with the keyword class and then writing the class name.
The attributes are nothing but variables that contains data.
__init__(self) is a special method or constructor to initialize the variables.
Method1() and Method2() - - etc are methods that are intended to process
the variables.
class classname:
attributes
def __init__(self):
def method1():
def method2():
class
# python program to demonstrate class
class Student:
def __init__(self):
self.usn = “ “
self.name = “ “
self.marks = 0
def getdata(self):
self.usn = input(“enter usn”)
self.name = input(“enter name”)
self.marks = int(input(“enter marks”))
def putdata(self):
print(“usn =“, self.usn)
print(“name =“,self.name)
print(“marks = “,self.marks)
s = Student() # creating an object
s.getdata()
s.putdata()
Class
Observe that the keyword class is used to declare a class. After this, we
should write the class name. So student is our class name. Generally, a
class name should start with a capital letter. Hence ‘s’ is capital in
student. In the class, we write attributes and methods. To create an
object, the following syntax is used:
objectname = classname()
So, to create an instance for object to the student class, we can write
s = Student()
The self variable
‘self’ is a default variable that contains the memory address of the instance
(object) of the current class. So, we can use ‘self’ to refer to all the instance
variable and instance methods.
When an instance(object) to the class is created, the instance name contains
the memory location of the instance(object). This memory location is
internally passed to ‘self’. For example, we create an instance to student
class as
s = Student()
Here s contains the address of the instance (object). This memory address is
internally and by default passed to the ‘self’ variable. Since ‘self’ is known as
the address of the instance(object). We use self in two ways.
The ‘self’ variable is used as first parameter in the constructor as
def __init__(self):
In this case, self can be used to refer to the instance variables inside the
construct0r
class
‘self’ can be used as first parameter in the instance method as,
def getdata(self):
Here, getdata() is instance method as it acts on the instance variables.
Constructor: A constructor is a special method that is used to initialize the
instance variables of a class. In the constructor, we create the instance
variables and initialize them with some starting values. The first parameter of
the constructor will be ‘self; variable that contains the memory address of
the instance. For example
def __init__(self):
self.a = 0
self.b = 0
Here, the constructor has only one parameter, i.e. ‘self’. Using the ‘self.a’ and
‘self.b’, we can access the instance variables of the class. A constructor is
called when we creating the object of a class.
Constrctors
# python program to demonstrate a constructor
class Cons:
def __ init__(self):
self.a = 10
self.b = 20
def printdata(self):
print(self.a)
print(self.b)
x = Cons()
x.printdata()
Parameterized Constructor
class Parcons:
def __init__(self, m = 0, n = 0):
self.a = m
self.b = n
def putdata(self):
print(self.a)
print(self.b)
x = Parcons() # constructor called without parameter
y = Parcons(10,20) # constructor called with arguments
x.putdata()
y.putdata()
Polymorphism
‘Poly’ means ‘many’, morphism means forms. It is an ability to take more
than one form. The polymorphism is achieved in python by using method
overloading.
Method Overloading ; If a method is written such that it can perform more
than one task, it is called method overloading.
# python program to demonstrate method overloading
class Moverload:
def add(self, m, n):
self.c = m + n
print(self.c)
m = Moverload()
m.add(10,20) # output 30
m.add(“hello”, “world”) # output helloworld (concatenate two strings)
Constructor overloading
# python program to overload a constructor
class Coverload:
def __init__(self, *args):
for i in args:
print(I, end = “ “)
x = Coverload(10,20,30) # output 10 20 30
y = Coverload(“hello”, “world”) # output hello world
Inheritance
The mechanism of deriving a new class from the old class is called
inheritance. The old class is called base class and new class is called
derived class. There are different types of inheritance.
1. Single level inheritance
2. Multi-level inheritance
3. Hierarchical inheritance
4. Multiple inheritance
1. Single Inheritance : A mechanism of deriving a single class from the
base class is called single level inheritance.
Single Level Inheritance
# Program to demonstrate single level inheritance
class A:
def __init__(self):
self.a = 0
self.b = 0
self.c = 0
def getdata(self):
self.a = int(input(“enter a”))
self.b = int(input(“enter b”))
def putdata(self):
print(self.a)
print(self.b)
class B(A): # derived class
def sum(self):
self.c = self.a + self.b
print(self.c)
x = B()
Multi-level Inheritance
# Program to demonstrate multi level inheritance
class A:
def __init__(self):
self.a = 0
self.b = 0
self.c = 0
def getdata(self):
self.a = int(input(“enter a”))
self.a = int(input(“enter b”))
def putdata(self):
print(self.a)
print(self.b)
Multi-Level Inheritance Continued
class B(A): # derived class
def sum(self):
self.c = self.a + self.b
print(self.c)
class C(B): # derived class
def prod(self):
self.d = self.a * self.b
print(self.d)
x = C()
x.getdata()
x.putdata()
x.sum()
• x.prod()
Hierarchical Inheritance
# python program to implement Hierarchical inheritance
class A:
def __init__(self):
self.a = 0
self.b = 0
def getdata(self):
self.a = int(input(“enter a”))
self.b = int(input(“enter b”))
def putdata(self):
print(self.a)
print(self.b)
Hierarchical Inheritance continued
class B(A): # derived class
def sum(self):
self.c = self.a + self.b
print(self.c)
class C(A): # derived class
def prod(self):
self.d = self.a * self.b
print(self.d)
x = B()
x.getdata()
x.putdata()
x.sum()
y = C()
y.getdata()
y.putdata()
Multiple Inheritance
# python program to implement Multiple inheritance
class A:
def __init__(self):
self.a = 0
def getdata(self):
self.a = int(input(“enter a”))
class B:
def __init__(self):
self.b = 0
def inputdata(self):
self.b = int(input(“enter b”))
Multiple Inheritance continued
class C(A,B):
def sum(self):
self.s = self.a + self.b
print(self.s)
x = C()
x.getdata()
x.inputdata()
x.sum()
Method Overriding
When there is a method in the super class, Writing the same method in
the sub class so that it replaces the super class method is called
method overriding.
# Python program to demonstrate method overriding
class A:
def disp(self):
print(“welcome to java world”)
class B(A):
def disp(self):
print(“welcome to Python world”)
x = B()
x.disp() # output is welcome to python world
Constructors in super class
class A:
def __init__(self):
print(“super class constructor executed”)
class B(A):
def __init__(self):
print(“sub class constructor called”)
x = B()
output: sub class constructor executed.
If you have constructor written in the super class and subclass, then it
will execute sub class constructor. If you do not have a sub class
constructor, then it will execute the super class constructor.
Module 3
Regular Expression: A regular expression is a string that contains special
symbols and characters to find and extract the information needed by us
from the given data. A regular expression helps us to search information,
match, find and split information as per our requirements.
Sequence characters in regular expressions
Character Its Description
d Represents any digit ( 0 to 9)
D Represents any non digit
s Represents white space
S Represents non white space
w Represents any alphanumeric (A to Z, a to z, 0 to 9)
W Represents non-alphanumeric
b Represents a space around words
Regular Expressions
Regular expression are used to perform the following important
operations. Python provides ‘re’ module that stands for regular
expression. This module contains the following methods.
• Matching strings
• Searching for strings
• Finding all strings
• Splitting string into pieces
• Replacing strings
match method() : The match method searches the beginning of the
string and if matching string is found, it returns an object that contains
the resultant string. Otherwise it returns the none. We can access the
string from the returned object using group() method.
Regular Expressions
# A python program to create a regular expression using match() method to search
for strings starting with m and having total 3 characters.
import re
str = “man, sun, mop, run”
result = re.match(r “mww”, str)
print(result.group())
output: man
. # A python program to create a regular expression using match() method to
search for strings starting with m and having total 3 characters.
import re
str = “sun, man, mop, run”
result = re.match(r “mww”, str)
print(result)
output: none
Regular Expressions
findall() : Method searches the string from beginning till the end and
returns all occurrences of the matching string in the form of list
object. If the matching strings are not found , then it returns empty list
# A python program to create a regular expression using match()
method to search for strings starting with m and having total 3
characters.
import re
str = “man, sun, mop, run”
result = re.findall(r “mww”, str)
print(result)
Output: [“man”, “mop”]
Regular Expressions
search(): The search method searches the string from beginning till the
end returns the first occurrence of the matching string. Otherwise, it
returns none. We can use group() method to retrieve the string from
the object returned by this method.
# A python program to create a regular expression using match()
method to search for strings starting with m and having total 3
characters.
import re
str = “ sun, man, mop, run”
result = re.findall(r “mww”, str)
print(result)
Output: man
Regular Expressions
split(): The split() method splits the string according to the regular
expression and resultant pieces returned as a list. If there are no string
pieces, then it returns an empty list.
# A python program to create a regular expression to split string into
pieces where one or more white spaces.
import re
str = “welcome to python”
result = re.split(“ s+”, str)
print(str)
Output: [“welcome”, “to”, “python”]
Regular Expressions
sub(): This method substitutes or replaces in the place existing strings.
After substitution, the main string is returned by this method.
import re
str = “welcome to java”
res = re.sub(r “welcome”, “python”,str)
print(res)
Module 4
Arrays and Numpy in Python : An array is an object that stores group of
elements of same datatype
Advantages of Arrays:
• Arrays are similar to lists. The main difference is that always can store
only one type of elements. Where as the lists can store different types
of elements.
• The size of the array is not fixed in python. Hence, we need not
specify how many elements we are going to store into array in the
beginning.
• Arrays can grow or shrink in memory dynamically(during run time)
• Methods that are useful to process the elements of any array are
available in array module.
Arrays
Creating an array : The type should be specified by using a type code at the time
creating the array object as:
arrayname = array(typecode, [elements])
The typecode ‘i’ represents I integer type where we can store integer numbers. If
the type code is ‘f’ then it represents float type array where we can store numbers
with decimal point.
The important type codes are given below:
Typecode Ctype Minimum size in bytes
‘b’ Signed integer 1
‘B’ Unsigned integer 1
‘i’ Signed integer 2
‘I’ Unsigned integer 2
‘l’ Signed integer 4
‘L’ Unsigned integer 4
‘f’ Double precision 4
Arrays
Type code Ctype Minimum size in bytes
‘d’ Double precision floating point 8
‘u’ Unicode character 2
Arrays
# creating an array using python
import array as ar
a = ar.array(“i”, [-1,2,3,4])
print(“elements of array”)
for i in a:
print(i)
Output:
-1
2
3
4
Arrays
# Creating array with characters
import array as ar
a = ar.array(‘u’,[‘a’, ‘b’, ‘c’, ‘d’])
print(“the array elements are”)
for ch in a:
print(ch) # output a b c d
# Creating floating type array
import array as ar
a = ar.array(‘f ’,[1.5,2.5,3.5.4.5])
print(“the array elements are”)
for i in a:
print(i) # output 1.5 2.5 3.5 4.5
Arrays
# A python program to retrieve the elements of an array using index
import array as ar
a = ar.array(‘I’, [10,20,30,40])
n = len(a)
for I in range(n):
print(a[i], end= “”) # output 10 20 30 40
Array Slicing
A slice presents a piece of the array. When we perform slicing
operation on any array, we can retrieve a piece of the array that
contains a group of elements. The general format of slice is:
arrayname[start : stop : step]
import array as ar
a = ar.array(‘i’, [10,20,30,40,50])
print(a[1:4]) # output [20,30,40]
print(a[0:]) # output print all the elements of an array
print(a[:4] # output [10,20,30,40]
print(a[-4:]) # prints the last four elements [20,30,40,50]
print(a[-4: -1] # prints [20,30,40]
print(a[0:4:2]) # prints [10,30]
Processing the arrays
The arrays class of arrays module in python offers methods to process
the arrays easily. The programmers can easily perform certain
operations by using these methods.
Method Description
a.append(x) Adds an element ‘x’ at the end of the
existing ‘a’
a.count(x) Returns the number of occurrences
of x in the array ‘a’
a.extend(x) Appends x at the end of the array a .
‘x’ Can be another array
a.fromfile(f, n) Reads n items from the file object
a.fromlist(lst) Appends items from the list to the
end of the array.
a.fromstring(s) Appends items from the string ‘s’ to
the end of the array ‘a’
Processing the arrays
Method Description
a.Insert(i, x) Inserts ‘x’ in the position ‘I’
a.pop() Removes the last item from the array ‘a’.
a.remove(x) Removes the first occurrence of x in the
array ‘a’
a.reverse() Reverses the order of elements in the
array ‘a’
a.tolist() Converts the array ‘a’ into list
Program to demonstrate array methods
import array as ar
a = ar.array(‘i’, [10, 20, 30, 40, 50])
a.append(60)
print(a) # output [10,20,30,40,50,60]
a.insert(2,70)
print(a) # output [10,20,70,30,40,50,60]
a.remove(20)
print(a) # output [10,70,30,40,50,60]
a.pop()
print(a) # output [10,70,30,40,50]
print(a.index(30)) # returns 2
lst = a.tolist()
print(lst) # output [10,70,30,40,50]
Program to read and print an array using keyboard
import array as ar
a = ar.array(‘i’, []) # creates an empty array to store integers
n = int(input(“enter how many elements”))
for i in range(n):
print(“enter an element”)
a.append(int(input())
print(“the contents of array”)
for i in a:
print(i)
Numpy
Numpy is a package that contains several classes, functions, variable
etc, to deal with scientific calculations in python. Numpy is useful to
create and also process single and multi-dimensional arrays. In
addition, numpy contains a large library of mathematical functions like
linear algebra functions and Fourier transformations.
Creating array using numpy :
import numpy as np
a = np.array([10,20,30,40],int)
print(a)
Creating arrays in numpy can be done in several ways. Some of the
important ways are
Numpy
Creating arrays in numpy can be done in several ways. Some of the
important ways are:
1. Using array() function
2. Using linspace() function
3. Using logspace() function
4. Using arange() function
5. Using zeros() and ones() function
Creating array using array()
We can call array function of numpy module to create an array. When
create an array, we can specify the datatype of the elements either ‘int’
or ‘float’. We can create an integer array type array as
arr = array([10,20,30,40],int)
Numpy
To create an array with float type elements, we should specify ‘float’.
Import numpy as np
arr = np.array([10.5,20.5,30.5.40.5], float)
In the array, if python interpreter finds one element belonging to ’float type’,
then it will also convert into float type by a decimal point after the element
as
Import numpy as np
arr = np.array([10,20,30.5,40])
If we display this array using print() function, we can see the array as
[ 10., 20., 30.5, 40.]
To create an array with character type elements, we need not specify the
datatype. We can simply write
import numpy as np
arr = np.array([‘a’, ’b’ ,’c’, ‘d’])
Numpy
# creating a array using numpy
import numpy as np
a = np.array([10,20,30,40],int)
print(a)
Creating arrays using linspace: The linspace() function is used to create
an array with evenly spaced points between a starting and ending
point. The general form of the linspace() function as:
linspace(start, stop, n)
‘start’ represents the starting element and stop represents the ending
element. ‘n’ is an integer that represents the number of parts the
elements should be divided. If ‘n’ is omitted, then it is taken as 50.
Numpy
# a python program to creating an array with 5 equal parts using
linspace.
import numpy as np
a = np.linspace(2,10,5)
print(“a = “,a)
Output: a = [2,4,6,8,10]
Creating arrays using logspace: The linspace() function produces evenly
spaced points. Similarly, logspace() function produces evenly spaced
points on a logarithmically spaced scale. The general form is:
logspace(start, stop, n)
The logspace() function starts at value which is ‘start’ to the power of
10 and ends at a value which is stop to the power of 10. If n is not
specified, then its value is taken as 50. For example: if we write
Numpy
a = logspace(1,4,5)
The function represents values 1 to the power of 10 to 4 to the power of 10.
These values are divided into 5 equal points and those points are stored into the
array ‘a’.
import numpy as np
a = np.logspace(1,4,5)
print(a)
Output: [10.0, 56.2,316.2, 1778.3,10000.0]
Creating arrays using arange() function
The arange() function in numpy as same as range() function in python. The arange
function is used in the following format.
arange(start, stop, stepsize)
This creates an array with a group of elements from start to stop – 1 in steps of
step size. If the step size is omitted, then it is taken as zero.
Ex : arange(10) will produce an array with elements 0 to 9.
arange(5,10) will produce an array with elements from 5 to 9
arange(1,10,3) will produce 1, 4, 7
arange(5,1,-1) will produce 5,4,3,2
Numpy
# Creating array with arange function
import numpy as np
a = np.arange(2,11,2)
print(“a =“, a)
Output: a = [2,4,6,8,10]
Creating arrays using zeros() and ones() function:
We can use zeros() functions to create an array with all zeros. The one
function is useful to create an array with all 1’s. They are written in the
following format.
zeros(n, datatype)
ones(n, datatype)
Where ‘n’ represents the number of elements. We can eliminate the
‘datatype’ argument. If we do not specify the datatype then the default
datatype used by numpy as ‘float’.
Numpy
For example: zeros(4)
This will create an array with four elements all zeros as [0.,0.,0.,0.]
If we want this array in integer format, we can use ‘int’ as datatype, as
zeros(4,int) this will create an array as : [0,0,0,0]
If we use ones() function, it will create an array with elements 1.
For ex: ones(5,float)
will create an array with 5 integer elements are [1.,1., 1.,1.,1.]
Creating arrays using zeros() and ones()
import numpy as np
a = np.zeros(5,int)
print(a)
b = np.ones(5) # default datatype is float
print(b)
Numpy
We apply mathematical functions like sin(), cos(), sqrt(), exp() and so on the
elements of the array. The list of functions that can be used on numpy
arrays.
Function meaning
sin(arr) Calculate the sine value of each
element in the array arr.
cos(arr) Calculates the cosine value of each
element in the array arr.
log(arr) Calculates natural logarithmic value of
each element in the array arr.
abs(arr) Calculates absolute value of each
element in the array arr.
sqrt(arr) Calculates square root value of each
element in the array arr.
Numpy
Function Meaning
exp(arr) Calculates exponentiation value of each element
in the array arr.
sum(arr) Returns the sum of all elements in the array arr.
prod(arr) Returns the product of all the elements in the
array arr.
min() Returns smallest element in the array arr.
max(arr) Returns the biggest element in the array arr.
mean(arr) Returns the mean value( average ) of elements in
the array arr.
median(arr) Returns median value of all elements in the array
arr.
unique(arr) Gives array that contains unique elements of the
array arr.
sort(arr) Gives an array with sorted elements of the array
arr in ascending order
Numpy
# python program to demonstrate mathematical function on arrays.
import numpy as np
arr = np. array([10,20,30,5,40],int)
print(“original array = “, arr)
print(“after adding 5 = “, arr + 5)
print(“sin value = “, sin(arr))
print(“cos value =“, cos(arr))
print(“biggest value =“, max(arr))
print(“minimum value = “, min(arr))
print(“sum of all elements = “, sum(arr))
print(average of all elements = “,avg(arr))
Numpy
Comparing Arrays : We can use the relational operators >,<,==,
>=,<=,>=, and != to compare the arrays of same size.
import numpy as np
a = np.array([1,2,3,0],int)
b = np.array([0,2,3,1],int)
c = a== b
print(“result of a==b”, c)
c = a > b
print(“result of a >b”, c)
c = a <= b
print(“result of a<=b”, c)
Result of a==b [False True True False]
Result of a>b [True False False False]
Numpy
any() Function : The any function can be used to determine if any one element of
the array is True.
all() Function: The all() function can be used to determine whether the all
elements in the array are true.
The any() and all() functions returns either True or False.
# python program to demonstrate all() any() functions.
import numpy as np
a = np.array([1,2,3,0],int)
b = np.array([0,2,3,1],int)
c = np.array([0,2,3,1],int)
d = a > b
print(“check if any one of the element is true”, any(d))
d = b == c
print(“check if all elements are true”, all(d))
Output: True
True
Slicing in Numpy arrays
import numpy as np
a = np.arrange(1,6) # creates an array an array with 1 to 5
print(a) # prints 1 2 3 4 5
b = a[1:6:2]
print(b) # prints [1,3,5]
b = a[-2,2:1]
print(b) # prints[4,3,2]
b = a[: -2 : ]
print(b) # prints [1,2,3]
Attributes of numpy array (variables)
Numpy array class is called ndarray. This class contains the following attributes.
The ‘ndim’ attribute : The ‘ndim’ attribute represents the number of dimensions of
the array. The number of dimensions is also referred to as rank. For a single
dimensional array rank is 1 and for two dimensional array brank is 2.
# program to demonstrate ndim attribute
import numpy as np
a = np.array([1,2,3,4],int)
print(a.ndim) # returns 1
b = np.array([[1,2,3],[4,5,6]],int)
print(b.ndim) # returns 2
The ‘shape’ atttribute: The ‘shape’ attribute gives the shape of an array. The shape
is tuple listing the number of elements along each dimension. For a 1 dimensional
array, shape elements in the row. For a two dimensional array, it specifies the
number of rows and columns in each row. We can also change the shape using
‘shape’ attribute.
Attributes of numpy array (variables)
# program to demonstrate shape attribute
a = np.array([1,2,3,4],int)
print(a.shape) # prints (4,)
b = np.array([[1,2,3],[4,5,6]],int)
print(b.shape) # prints (2,3)
b.shape = (3,2)
print(b) # [[1 2]
[3 4]
[5 6]]
Attributes of numpy array (variables)
The size attribute: The ‘size’ attribute gives the total number of elements in the
array.
# Python program to demonstrate size attribute.
import numpy as np
a = np.array([1,2,3,4,5],int) # prints 5
print(a.size)
b = np.array([[1,2,3], [4,5,6]],int)
print(b.size) # prints 6
The ‘itemsize’ attribute : The ‘item size’ attribute gives the memory size of the
array element in bytes
import numpy as np
a = np.array([1,2,3,4],int)
print(a.size) # prints 4 (long integer)
b = np.array([1.5,2.5,3.5,4.5],float) # prints 8 (double precision)
Attributes of numpy array (variables)
The dtype attribute: The ‘dtype’ attribute gives the datatype of the
elements in the array.
import numpy as np
a = np.array([1,2,3,4],int)
print(a.dtype) # prints int32
b = np.array([1.5,2.5,3.5.4.5],float)
print(b.type) # pints float64
The nbytes attribute: The ‘nbyte’ attribute gives the total number of
bytes occupied by an array. The total number of bytes = size of array *
itemsize of each element in the array.
Attributes of numpy array (variables)
# Python program to demonstrate nbytes attribute
import numpy as np
a = np.array([1,2,3,4],int)
print(a.nbytes) # prints 16 each element occupies 4 bytes
b = np.array([[1,2,3],[4,5,6]],int)
print(b.nbytes) # prints 24 bytes
c = np.array([1.5,2.5.3.5,4.5],int)
print(c.nbytes) # prints 32 bytes
Numpy
The reshape() method : The reshape() method is useful to change the shape
of an array. The new array should have the same number of elements as in
the original array.
# Pyhton program to demonstrate reshape() method
import numpy as np
a = np.arange(6)
print(a) # creates an array [0,1,2,3,4,5]
b = np.reshape(2,3)
print(b) # change the shape as 2 rows and 3 columns
output: [[0 1 2],
[3,4,5]]
Numpy
The flatten method: The flatten method is useful to return a copy of
the array collapsed into one dimension.
# Python program to demonstrate flatten method
a = np.array([[1,2,3],[4,5,6],int)
print(a) # [[ 1 2 3]
[ 4 5 6]]
b = a.flatten()
print(b) # prints [1 2 3 4 5 6]
Working with multidimensional arrays with numpy
The 2d array, 3D arrays , etc . Are called multidimensional arrays. A 2D
array contains more than 1 row and 1 column. A 2D array is also
considered as matrix. For Ex: A 2D array with m rows and n columns is
called m * n matrix.
We can create multidimensional arrays in the following ways.
1. Using array Function.
2. Using ones() and zeros() function
3. Using eye() function
4. Using reshape() function
The array() Function: Numpy’s array function can be used to create
multidimensional array. Usually, we pass lists of elements to this
function.
Working with multidimensional arrays with numpy
# python program to create a multidimensional array.
import numpy as np
a = np.array([[1,2,3], [4,5,6]])
print(a)
Output:[[1 2 3]
[4 5 6]]
The ones() and zeros() functions : The ones() function is useful to
create a 2D array with several rows and columns where all the
elements will be taken as 1. The format of this function is:
ones ((r, c),datatype)
Here ;r; represents number of rows and ‘c’ represents the number of
columns. Datatype represents the datatype of the elements in the
array.
Working with multidimensional arrays with numpy
# python program to demonstrate ones() function to create array
import numpy as np
a = np.one((2,2),float)
print(a)
Output: [[ 1. 1.]
[1. 1.]]
Just like the ones() function, we can also use the zeros() function to create a 2d
array with elements filled with zeros.
# python program demonstrate zeros() to create array
import numpy as np
a = np.zeros((2,2),int)
print(a)
Output: [[0 0]
[0 0]]
Working with multidimensional arrays with numpy
The eye() function : The eye() function creates a 2d array and fills the elements in
the diagonal with 1’s. The general format of using this function is:
eye(n, dtype = datatype)
This will create an array with ‘n’ rows and ‘n’ columns. The default datatype float.
# Python program to demonstrate eye function
import numpy as np
a = np.eye(2)
print(a) # out put [[1. 0.]
[0. 1.]]
b = np.eye(2, dtype = int)
print(b) # output [[ 1 0]
0 1]]
Working with multidimensional arrays with numpy
The reshape() function: This function is useful to convert 1D array into
multidimensional array. The general form is:
reshape(arrayname,(n, r, c))
Here, array represents the name the array whose elements to be converted .
‘n’ indicates the number the number of arrays in the resultant array. ‘r’, ‘c’
indicates the number of rows and columns respectively.
# program to demonstrate reshape() function
import numpy as np
a = np.array([1,2,3,4,5,6])
b = np.reshape(a,(2,3))
print(b) # output [[1 2 3]
[4 5 6]]
Matrices in numpy
In, mathematics, a matrix represents a rectangular array of elements
arranged in rows and columns. When a matrix has more than 1 row
and more than 1 column, it is called m * n matrix. Where m represents
the rows and n represents the columns.
# create a matrix
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
b = np.matrix(a)
print(b) # output [[1 2 3]
[4 5 6]]
Getting Diagonal elements of a matrix
To retrieve the diagonal elements of a matrix, we can use diagonal() function: The
general for is:
a = diagonal(matrix)
The diagonal() function returns a 1D array that contains diagonal elements of the
original matrix.
import numpy as np
a = np.matrix(‘1 2 3; 4 5 6; 7 8 9’)
print(a) # output [[ 1 2 3]
[4 5 6]
[7 8 9]]
d = np.diagonal(a)
print(d) # output [ 1 5 9]
Finding maximum and minimum elements
To know the maximum element, we use max() method and to the
minimum element, we can use min() method. These methods should
be using matrix name.
# program to demonstrate max(0 and min() method
import numpy as np
a = np.array([[3,1,2],[8,4,6]])
b = np.matrix(a)
big = b.max()
small = b.min()
print(big)
print(small)
Finding sum and average of elements
To find the sum of all elements in the matrix, we can use sum() method
and to find average, we can use mean method. These methods should
be called using the matrix name.
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
b = np.matrix(a)
s = b.sum()
m = b.mean()
print(s) # output 21
print(m) # output 3.5
Product of elements
It is possible to know the product of elements in a matrix. For this purpose, numpy
provides prod() method. For example: prod(0) returns a matrix that contains the
products of elements in each column of the original matrix. prod(1) returns a
matrix that contains products of elements of each row. These methods should be
called using matrix name.
# Python program to demonstrate product()
a = np.array([[1,2],[3,4]]) # [1 2
3 4]
b = np.matrix(a)
c = b.prod(0)
print(c) # [3 8]
r = b.prod(1)
print(r) # [[2]
[12]]
Sorting the matrix
Numpy provides sort function that sorts the matrix elements into ascending order. The
general syntax is:
sort(matrixname, axis)
If we use axis = 1, it sorts the elements in each into ascending order. If we use axis = 0, then
it sorts the elements in column into ascending order. The default value of axis is 1.
# program to demonstrate sort method
import numpy as np
a = np.array([[3,5,4],[1,8,6]]) # 3 5 4
1 8 6
b = np.matrix(a)
r = np.sort(b,1)
print(r) # output [[ 3 5 4]
[1 6 8]]
c = np.sort(b,0) # output [ [1 5 4]
[3 8 6]]
Transpose a matrix
Rewriting matrix rows and into columns and vice versa is called ‘transpose’. Thus
the rows in the original matrix will become rows in the original matrix will become
rows in the transpose matrix. To find the transpose, we can transpose() and getT()
methods in numpy. These methods should be called using matrix name.
# Python program to demonstrate transpose method
import numpy as np
m = np.matrix(‘1,2; 3,4; 5,6’)
print(m) # output [[ 1 2]
[3 4]
[5 6]
t = m.transpose()
t1 = m.getT() # output [[ 1 3 5]
print(t1) [ 2 4 6]]
Matrix addition and Multiplication
# python program demonstrate arithmetic operations
import numpy as np
a = np.matrix([[1,2].[3,4]]) a = [ 1 2
3 4]
b = np.matrix([[1,2].[3,4]]) b = [1 2
3 4]
c = a + b
print(c) # output [ [2 4]
[6 8]]
d = a – b #output [[0 0]
[0 0]]
print(d)
e = a * b # output [[7 10]
[15 12]]
print(e)
Ad

More Related Content

Similar to python notes for MASTER OF COMPUTER APPLIICATION_ppt.pptx (20)

python ppt | Python Course In Ghaziabad | Scode Network Institute
python ppt | Python Course In Ghaziabad | Scode Network Institutepython ppt | Python Course In Ghaziabad | Scode Network Institute
python ppt | Python Course In Ghaziabad | Scode Network Institute
Scode Network Institute
 
Unit -1 CAP.pptx
Unit -1 CAP.pptxUnit -1 CAP.pptx
Unit -1 CAP.pptx
malekaanjum1
 
Introduction on basic python and it's application
Introduction on basic python and it's applicationIntroduction on basic python and it's application
Introduction on basic python and it's application
sriram2110
 
Python Basics by Akanksha Bali
Python Basics by Akanksha BaliPython Basics by Akanksha Bali
Python Basics by Akanksha Bali
Akanksha Bali
 
Intro-to-Python-Part-1-first-part-edition.pdf
Intro-to-Python-Part-1-first-part-edition.pdfIntro-to-Python-Part-1-first-part-edition.pdf
Intro-to-Python-Part-1-first-part-edition.pdf
ssuser543728
 
Python_Unit_1.pdf
Python_Unit_1.pdfPython_Unit_1.pdf
Python_Unit_1.pdf
alaparthi
 
Ch-3.pdf
Ch-3.pdfCh-3.pdf
Ch-3.pdf
R.K.College of engg & Tech
 
Welcome to python workshop
Welcome to python workshopWelcome to python workshop
Welcome to python workshop
Mukul Kirti Verma
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Ranjith kumar
 
Python by Rj
Python by RjPython by Rj
Python by Rj
Shree M.L.Kakadiya MCA mahila college, Amreli
 
BASICS OF PYTHON usefull for the student who would like to learn on their own
BASICS OF PYTHON usefull for the student who would like to learn on their ownBASICS OF PYTHON usefull for the student who would like to learn on their own
BASICS OF PYTHON usefull for the student who would like to learn on their own
Nandini485510
 
Chapter 1-Introduction and syntax of python programming.pptx
Chapter 1-Introduction and syntax of python programming.pptxChapter 1-Introduction and syntax of python programming.pptx
Chapter 1-Introduction and syntax of python programming.pptx
atharvdeshpande20
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
RojaPriya
 
Python Introduction
Python IntroductionPython Introduction
Python Introduction
vikram mahendra
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
kavinilavuG
 
Learn about Python power point presentation
Learn about Python power point presentationLearn about Python power point presentation
Learn about Python power point presentation
omsumukh85
 
Python
PythonPython
Python
Aashish Jain
 
Python fundamentals
Python fundamentalsPython fundamentals
Python fundamentals
natnaelmamuye
 
Python for katana
Python for katanaPython for katana
Python for katana
kedar nath
 
python ppt | Python Course In Ghaziabad | Scode Network Institute
python ppt | Python Course In Ghaziabad | Scode Network Institutepython ppt | Python Course In Ghaziabad | Scode Network Institute
python ppt | Python Course In Ghaziabad | Scode Network Institute
Scode Network Institute
 
Introduction on basic python and it's application
Introduction on basic python and it's applicationIntroduction on basic python and it's application
Introduction on basic python and it's application
sriram2110
 
Python Basics by Akanksha Bali
Python Basics by Akanksha BaliPython Basics by Akanksha Bali
Python Basics by Akanksha Bali
Akanksha Bali
 
Intro-to-Python-Part-1-first-part-edition.pdf
Intro-to-Python-Part-1-first-part-edition.pdfIntro-to-Python-Part-1-first-part-edition.pdf
Intro-to-Python-Part-1-first-part-edition.pdf
ssuser543728
 
Python_Unit_1.pdf
Python_Unit_1.pdfPython_Unit_1.pdf
Python_Unit_1.pdf
alaparthi
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Ranjith kumar
 
BASICS OF PYTHON usefull for the student who would like to learn on their own
BASICS OF PYTHON usefull for the student who would like to learn on their ownBASICS OF PYTHON usefull for the student who would like to learn on their own
BASICS OF PYTHON usefull for the student who would like to learn on their own
Nandini485510
 
Chapter 1-Introduction and syntax of python programming.pptx
Chapter 1-Introduction and syntax of python programming.pptxChapter 1-Introduction and syntax of python programming.pptx
Chapter 1-Introduction and syntax of python programming.pptx
atharvdeshpande20
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
RojaPriya
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
kavinilavuG
 
Learn about Python power point presentation
Learn about Python power point presentationLearn about Python power point presentation
Learn about Python power point presentation
omsumukh85
 
Python for katana
Python for katanaPython for katana
Python for katana
kedar nath
 

Recently uploaded (20)

Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Journal of Soft Computing in Civil Engineering
 
π0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalizationπ0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalization
NABLAS株式会社
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Journal of Soft Computing in Civil Engineering
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)
samueljackson3773
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
π0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalizationπ0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalization
NABLAS株式会社
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)
samueljackson3773
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
Ad

python notes for MASTER OF COMPUTER APPLIICATION_ppt.pptx

  • 1. Data Analytics Using Python Python • Python is a programming language that combines the features of C and Java. • When the programmers want to go for object orientation, python offers class and objects like java. • Python was developed by Guido Van Rossum in the year 1991 at the center of Mathematics and computer Science managed by the Dutch Government. • Van Rossum picked the name python for the new language from the TV show , “Monty Python’s Flying Circus”. • The logo of Python shows two intertwined snakes.
  • 2. Features of Python • Simple: python is a programming language when we read a python program , we feel like reading English sentences. It means more clarity and less stress on understanding the syntax of the language. • Easy to Learn: Python uses very few keywords. Its programs use very simple structure so developing programs in python become easy. • Open Source: There is no need to pay for python software. Python can be freely downloaded from www.python.org. • High Level Language: High Level languages use English words to develop programs. These are easy to lern and use. • Platform Independent: When a python program is compiled using a python compiler, it generates byte code. Python’s byte code represents a fixed set of instructions that run on all operating systems and hardware. Using a python virtual machine, anybody can run these byte code instructions on any computer system.
  • 3. Features of Python • Huge Library: Python has a big library which can be used on any operating system. Programmers can develop programs very easily using the modules available in the python library. • Scripting Language: A scripting language is a programming language that does not use a compiler for executing source code . Rather, it uses an interpreter to translate the source code into machine code while running. • Database Connectivity: Python provides interfaces to connect its programs to all major databases like Oracle, Sybase or MySql. • Scalable: Python programs are scalable since they can run on any a platform and use the features of the new platform effectively. • Interpreter: A software which converts high-level language instructions line-by-line into machine-level language is called an interpreter.
  • 4. Parts of Python programming Language • Identifiers • Keywords • Statements and Expressions • Variables • Operators • Precedence and associativity • Data types. • Indentation • Comments
  • 5. Parts of Python programming Language Identifier: Identifier is a user-defined name given to a variable, function, class, module or object. The identifiers are formed with a combination of alphabets (A-Z or a-z), digits and underscore. All identifiers are case sensitive. Here are naming conventions for python identifiers. • Class names start with an uppercase letter. All other identifiers start with a lowercase letter. • Starting an identifier with a single leading underscore indicates that the identifier is private. • Starting an identifier with a two leading underscores indicates a strongly private identifier. • If the identifier also ends with two trailing underscore, the identifier is language defined special name. • Example: sum, total, s1, gross_salary
  • 6. Parts of Python programming Language Variable: A variable is a name used to store a value. The variable may change its value during the execution of a program. In Python, a variable need not be declared with a specific type before its usage. The type of it will be decided by the value assigned to it. Example: a = 10 b = “hello” c = 5.5 Rules to follow when naming variables • Variable name can contain letters , numbers and underscore. • Variable name cannot contain spaces and other special characters . • Variable name should not start with a digit. • Variable names are case sensitive i.e. ‘Total’ different from ‘total’. • Keywords cannot be used as a variable name. Example: valid variable names : total, a1,net_salary invalid variable names: 1a, total salary
  • 7. Parts of Python programming Language Keywords: Keyword is a special word which is having a predefined meaning. The meaning of the keyword cannot changed by a user. Keywords are building blocks of the programming language. Example: and, as, assert, break, continue, while and so on Statements and Expressions: A statement is a unit of code the python interpreter can execute . There are mainly four types of statements in python. i) Assignment statement ii) print statement iii) conditional statement iv) Looping statements Assignment statement: we assign a value to a variable using the assignment statement by using assignment operator(=) Example: a = 10 c = a + b a, b, c = 10, 20, 30
  • 8. Parts of Python programming Language • print statement: print is a function which takes string variables as a argument to display it on the screen. Example: a = 10 print(a) Optional arguments with print statement : Sep: Python will insert a space between each of the arguments of the print function. There is an optional argument called sep. For Example sep = “ :” would separate the argument by a colon and sep = “ ## “ would separate the arguments by two hash symbols. For example: print(“a” , ”b”, “c”, “d”, sep =“ ;”) output: a;b;c;d
  • 9. Parts of Python programming Language Optional arguments with print statement : end: The print function will automatically advance to the next line. For example: print(“a”) print(“b”) print(“c”, end = “ “) print(“d”) output: a b c d
  • 10. Parts of Python programming Language Expression: An expression is a combination of operands and operators is called an expression. The expression in python produces some result or value after being interpreted by the python interpreter. for example: a = 10 a = a + 10 print(a) output is 20
  • 11. Operators, precedence and associativity Operator is a symbol that perform either arithmetic or logical operation. Arithmetic operators: Operator meaning example + addition c = a + b - subtraction c = a - b * multiplication c = a * b / division c = 5 / 2 will give 2.5 // floor division c = 5 // 2 will give 2 % modulo division c = 5 % 2 will give 1 ** exponent e = a ** b means a to the power of b
  • 12. Assignment operator These operators are useful to store the right side value into a left side variable. For Example: a = 10 c = a + b a += b (a = a + b) Unary minus operator : The unary minus operator is denoted by the symbol (-). When this operator is used before a variable, its value is negated. For example: n = 10 print(-n) The output is -10
  • 13. Relational Operators Relational operators compare two quantities. The following are the relational operators. The following are the relational operators. <, >, == , <= , >= , != The relational expression will return a value True or False depending on the condition. Example: print(5 > 3) returns True print(5 < 3) returns False
  • 14. Logical operators Logical operators are useful to construct compound condition. A compound is a combination of more than one simple condition. Each of the simple condition is evaluated to true or false and then the decision is taken to know whether the total condition is true or false. Logical operators are ‘and’ , ‘or’ and ‘not’ For Example: print(5 > 2 and 8 > 3) returns True print(5 > 8 or 3 > 9) returns False print( not( 5 > 8)) returns True
  • 15. Precedence and Associativity (order of operation) When an expression contains more than one operator, the evaluation of operators depends on the precedence of operators. The python operators follow the precedence rule(Which can be remembered as PEMDAS) Parenthesis have the highest precedence in any expression. The operations within parenthesis will be evaluated first. Exponentiation: Has the 2nd precedence ,but ,it is right associative. if there are two exponentiation operations continuously, it will be evaluated from right to left. For Example : print( 2 ** 3 ** 2) 2^3^2= 2^9 = 512
  • 16. Precedence and Associativity (order of operation) Multiplication and division are next priority : Out of these operations , whichever comes first in the expression is evaluated. print( 5 * 2 / 4) = 5 *2 = 10 10/4 = 2.5 print( 8 / 2 * 3) = 8 / 2 = 4 4 * 3 = 12 Additions and subtractions are least priority: Out of these operations , whichever appears first in the expression is evaluated i.e. they are evaluated from left to right. print(5 + 3 – 2) = 5 + 3 = 8 – 2 = 6 print(8 -2 + 3) = 8 – 2 = 6 + 3 = 9
  • 17. Precedence and Associativity (order of operation) Ex example: x = 1 + 2 ** 3 / 4 * ( 5 – 2) x = 1 + 2 ** 3 / 4 * 3 x = 1 + 8 / 4 * 3 x = 1 + 2 * 3 x = 1 + 6 x = 7
  • 18. Data types Data types specify the type of data stored in a variable like numbers and characters. Basic data types are . Numbers . Boolean . Strings. List, Tuple, Dictionary, None Numbers: Integers ,floating point numbers and complex numbers fall under python number category. They are defined as int, float and complex class in python. Integers can be of any length. It is only limited by the memory available. A floating number contains a decimal point and have accuracy of 15 decimal places. Complex numbers are written in the form x + y i. Where x is the real part and y is the imaginary part. Boolean: Python Boolean type is one of the built-in datatypes provided by python, Which represents one of the two values i.e. True or False
  • 19. Data Types Strings A string consists of a sequence of one or more characters, which can include letters ,numbers and other type of characters. A string can also contain spaces. You can use single quotes or double quotes to represent strings and it is also called a string literal. Multline strings can be denoted using triple quotes. For Example: s1 = ‘welcome to python ‘ s2 = “welcome to python” s3 = ‘’’ welcome to python ‘’’
  • 20. Data Types List: A list is formed by placing all the items inside square brackets[], separated by commas it can have any number of items and they may or may not be different types (integers, float, string,etc) for example lst = [ 1,2,3,4.5,”python”] Tuple : A tuple is defined as ordered collection of python objects. The only difference between tuple and list is that tuples are immutable i.e. tuples cannot be modified after it is created. We can represent tuples using parenthesis (). for example t = (1,2,3,4.5,”python”) Dictionary: Dictionary is an unordered collection of data values. Dictionary consists of key value pair. In python, a dictionary can be created by placing a sequence of elements within curly braces({ }), separated by comma. Dictionary holds pairs of values, one being its key and other corresponding pair element its key: value. Values in a dictionary can be any data type and can be duplicated, where as keys cannot be repeated and must be immutable. For example = { “usn”: 123, “name”: “xyz”, “marks”: 50}
  • 21. Data Types None: None is another special datatype in python. None is frequently used to represent the absence of a value. for example: money = none
  • 22. Indentation Code block1 begins Code block2 begins Code block3 begins Code block2 continues Code block1 continues Usually, we expect indentation from any program code, but in python it is a requirement and not be matter of style. This makes code look clearer and easier to understand and read. Any statements written under another statement with the same indentation is interpreted to belong to the same code block. If there is a next statement with less indentation to the left, then it just means the end of the previous code block. In other words, if a code block has to be deeply nested statements need to be indented further to the right. In the above diagram , code block2 and code block3 are nested under block1. Usually four white spaces or tab space used for indentation. In correct indentation will result in indentation error.
  • 23. Comments As programs get bigger and more complicated, they get more difficult to read. It is often difficult to look at a piece of code and figure out what it is doing or why. For this reason, it is a good idea to add notes to your programs to explain in natural language what the program is doing. These notes are called comments, and in python they start with the “#” symbol. Comments are non-executable statements. There are two types of comments: 1. Single line comment 2. Multiline comment 1. Single line comment: These comments start with a hash symbol (#) and are useful to maintain that entire line till the end should be treated as comment. for example: # program to add two numbers
  • 24. Comments 2. Multiline comments: When we want mark several lines as comment, then writing # symbol in the beginning of every line will be tedious job. Instead of starting every line with # symbol, we can write the “ “ “(triple double quotes) or ‘ ‘ ‘(triple single quotes) in the beginning and ending of the block as: “ “ “ welcome to python Hello world data analytics “ “ “ or ‘ ‘ ‘ welcome to python Hello world data analytic ‘ ‘ ‘
  • 25. Reading input and output To accept an input from keyboard, python provides the input function. This function takes a value from the keyboard and return it as a string. For Example: str = input() # this will wait until we enter a string print(str) It is a better idea to display a message to the user so that the user understands what to enter. This can be done by writing a message inside input() function as For Example: str = input(“enter your name”) print(str)
  • 26. Reading input and output We can use the int() function before the input()function to accept an integer from the keyboard as For Example: x = int(input(“enter x”)) print(x) Similarly to accept a float value from the keyboard, we can use float() function along with the input() function For Example: x = float (input(“enter x”)) print(x)
  • 27. Reading input and output # A Python program to accept 3 integers in the same line separated by # space and display their sum For Example: a, b, c = [ int(x) for x in input(“enter 3 no's”).split()] print(“sum = “ , (a + b + c)) # A Python program to accept 3 integers in the same line separated by # comma and display their sum For Example: a, b, c = [ int(x) for x in input(“enter 3 no's”).split( “,”)] print(“sum = “ , (a + b + c)) # Evaluating an expression entered from keyboard For Example: x = eval(input(“enter an expression”)) print(x) input: 10 + 5 – 4 output : 11
  • 28. Printing Output Format operator: The format operator , % allows us to construct strings, replacing parts of the strings with the data stored in variable. For Example, the format sequence ”%d” means that the operand should be formatted as an integer. a = 10 “%d” %a “ 10” A format sequence can appear anywhere in the string. So you can embed a value in a sentence. For Example: a = 10 “ The value of a is %d” % a output: “the value of a is 10”
  • 29. Printing Output If there is more than one format sequence in the string, the second argument has to be a tuple. Each format sequence is matched with an element of the tuple, in order. The following example uses “%d” to format an integer, %g to format a floating point number, and “%s” to format a string. “in %d years I spotted %g %s” %(3, 0.1 , “camels”) output: “in 3 years I spotted 0.1 camels Format function: is one of the string formatting methods in python3, Which allows multiple substitutions and value formatting. This method lets us concatenate elements within a string through positional formatting. Two types of parameters: • Positional argument • Keyword argument
  • 30. Printing Output Positional argument: It can be integers, floating point numbers, strings, characters and even variables. Keyword argument : They are essentially variable storing some value, which is passed as parameter. Positional arguments are placed in order. For Example: print(“ {0} college {1} department” . format(“Atria”, mca”)) Output: Atria college mca department Positional arguments are not specified, by default it starts positioning from zero For Example: print(“ {} college {} department” . format(“Atria”, mca”)) Output: Atria college mca department . Printing Output Printing Output
  • 31. Printing Output Keyword arguments are called by their keyword name. For Example: print(“MCA department has {0} sections in {college}”. format(“2”, college = “Atria”)) Output: MCA department has 2 sections in Atria f- strings : Formatted strings or f-strings were introduced in python 3.6. A f-string is a string literal that is prefixed with ‘f’ . These strings may contain replacement fields, which are expressions enclosed within curly braces { }. For Example: a = 10 print(f “the value of a is { a}) output : the value of a is 10
  • 32. Type conversion functions Python provides built-in functions that convert values from one type to another. int(): ex1: int(“32”) # string to integer 32 ex2: int(“hello”) value error ex3: int(3.56) # float to integer 3 ex4: int(-2.34) # float to integer -2 float() : ex1: float(32) # convert integer to float 32.0 ex2: float(“3.124”) convert string to float 3.124 str() : ex1: str(32) “ 32” ex2: str(3.124) “3.124”
  • 33. The type() function type() function is used to know the datatype of the value. The expression in parenthesis either a value or a variable. Ex1: type(10) output: <class int> Ex2: type(10.5) output: <class float> Ex3: type(“hello”) output: <class str> Ex4: a = 10 type(a) output: <class int>
  • 34. The is operator The ‘is’ operator is useful to compare whether two objects are same or not. It will internally compare the identity number of the objects. If the identity numbers of the objects are same, it will return True; Otherwise, it returns False. For Example: a = 25 id(a) 1670954952 b = 25 id(b) 1670954952 a is b output: True When two variables are referring to same object, they are called as identical objects. When two variables are referring to different objects, but contain a same, they are known as equivalent objects.
  • 35. The is operator For Example: s1 = input(“enter s1”) # if input hai s2 = input(“enter s2”) # if input hai s1 is s2 # output false s1 == s2 # output true
  • 36. Control flow statement if statement: This statement is used to execute one or more statement depending one or more statement depending on whether a condition is True or not. The general form is: if condition: statements First, the condition is tested. If the condition is True, then the statements given after colon(:) are executed. If the condition is False, then the statements mentioned after colon are not executed. # program to find the biggest of two numbers a = int(input(“enter a”)) b = int(input(“enter b”)) big = a if b > big: big = b
  • 37. The if – else statement The if – else statement executes a group of statements when a condition is true; Otherwise, it will execute another group of statements . The general form of if – else statement is as follows: if condition: statements1 else: statements2 If the condition is True, then it will execute statements1 and if the condition is False, then it will execute statement2.
  • 38. The if – else statement # To check whether the given number is even or not n = int(input(“enter n”)) if n % 2 == 0: print(“even no”) else: print(“odd no”)
  • 39. The if – elif – else statement Sometimes, the programmer has to test multiple conditions and execute statements depending on those conditions if – elif – else statement is useful in such situations. The general form of if – elif – else statement is as follows if condition1: statement1 elif condition 2: statement2 elif condition 3: statement3 - - else: statement4
  • 40. The if – elif – else statement Here, the conditions are tested from top to bottom as soon the true condition is found, then the associated statements are executed. After the execution, the control will be transferred below if—elif –else statement. Example : # to check whether the given number is positive, negative or # equal to zero n = int (input(“enter n “)) if n > 0: print(“positive number”) elif n < 0: print(“negative number”) else: print(“equal to zero”)
  • 41. Nested if statement In if statement , another if statement exists then it is called nested if statement. # program to check whether the given number is positive and even or # odd n = int(input(“enter n”)) if n > 0: if n % 2 == 0: print(“positive and even number”) else: print(“ number is positive and odd”) else: print(“the number is not positive”)
  • 42. Looping statements Repeatedly executing a block of statements is called a loop. While loop: The while loop is useful to execute a group of statements several times depending on the condition is true or false. The general form is as follows: while condition: statements Python interpreter first checks the condition. If the condition is true, then it will execute the statements written after colon(:) . After executing the statements, it will go back and check the condition again. If the condition is again found to be true, then it will execute the statements. In this way, as long as condition is true, python interpreter executes statements again and again. Once the condition is found to be false, then it will come out of the loop.
  • 43. While loop # program to display numbers from 1 to 10 x = 1 while x <= 10: print(x) x = x + 1
  • 44. The for loop The for loop is useful to iterate over the elements of a sequence. It means, the for loop can be used to execute a group of statements repeatedly depending upon the number of elements in the sequence. The for loop work with sequence like string, list and tuple. The syntax of the for loop is given below: For var in sequence: statements The first element of the sequence is assigned to the variable written after for and then statements are executed. Next, the second element of the sequence is assigned to the variable and then the statements are executed second time. In this way, for each element of the sequence , the statements are executed once. So, the for loop is executed as many times as there are number of elements in the sequence.
  • 45. The for loop # a python program to display the characters of a string using for loop str = “hello” for ch in str: print(ch, end = “ “) Output: h e l l o Syntax of for loop with range() function: for variable in range(start, end, steps): statements to be repeated The start and end indicates starting and ending values in the sequence, where end is excluded in the sequence that is sequence is up to end – 1. The default value of start is 0. The argument steps indicates the increment / decrement in the values of the sequence with the default value as 1. Hence the argument steps is optional.
  • 46. The for loop # program to print the message multiple times for i in range (3): print(“hello”) Output: hello hello hello # program to print numbers in sequence for i in range(5): print(i, end = “ “) output: 0 1 2 3 4 #program to display numbers from 5 to 1 for i in range(5,0,-1): print(i, end = “ “) Output: 5 4 3 2 1
  • 47. for loop # program to display odd numbers from 1 to 10 using range function for i in range(1,10,2): print(i, end = “ “) output: 1 3 5 7 9 Nested loops It is possible to write one loop inside another loop is called nested loops. For Example: for i in range(2): for j in range(3): print(“ I =“, I “t”, “j = “,j) Output: i = 0 j =0 i = 1 j = 0 i = 0 j = 1 i = 1 j = 1 I = 0 j = 2 I = 1 j = 2
  • 48. The break statement The break statement is used to terminate a loop when an unusual condition occurs in the body of the loop. For Example: for i in range(10): if i == 4: break print(i, end = “ “) output: 0 1 2 3
  • 49. The continue statement The continue statement is used in a loop to go back to the beginning of the loop. It means, when continue is executed, the next repetition will start when continue is executed, the subsequent statements in the loop are not executed. # program to print odd numbers for i in range(1,10): if i % 2 == 0: continue else: print(I, end = “ “) Output: 1 3 5 7 9
  • 50. Functions • A sequence of instructions intended to perform a specific independent task is known as a function. • You can pass data to be processed, as parameters to the function. Some functions can return data as a result. Function types • Built-in types • User defined functions Built-in Function • Python provides a number of built-in functions that we can use without needing to provide the function definition • Built-in functions are ready to use functions
  • 51. Functions Commonly used modules: Math functions: python has a math module that provides most of the frequently used mathematical functions. Before we use the those functions, we need to import the module as below. ex: import math Some of the functions in math module are: Function Description ceil(x) Raises x value to the next higher integer. If x is an integer, then same value is returned. Ex: ceil(4.3) gives 5
  • 52. Math functions Function Description floor(x) Decreases x value to the previous value. If x is an integer, then the same value is returned. Ex: floor(4.5) gives 4 degree(x) converts angle value x radians into degree radians(x) converts x value from degrees into radians
  • 53. Math functions Functions Description sin(x) gives sine value of x. Here x value is given in radians cos(x) gives cos value of x. Here x value is given in radians fabs(x) gives the absolute value for positive quantity of x Ex: fabs(-4.5) gives 4.5 fatorial(x) Returns factorial of x.
  • 54. Math functions Functions Descriptions fmod(x, y) Returns remainder of division of x and y. fmod() is used to calculate the modulus of float values ex: fmod(14.5,3) gives 2.5 modf(x) returns float and integral parts of x ex: modf(2.56) (0.56,2.0) sqrt(x) returns positive square root of x sqrt(16) = 4
  • 55. Math functions Function Description pow(x, y) Raises x value to the power of y ex: pow(2,3) = 8 gcd( x, y) gives the greatest common divisor of x and y. gcd(14,10) = 2 trun(x) The real value of x is truncated to integer value. Trun(12.3) gives 12. Math.pi the mathematical constant
  • 56. Random numbers • Most of the programs that we write take predefined input values and produces expected output values such programs are said to be deterministic. • Making a program truly non deterministic turns out to be not so easy, but there ways to make it at least seem non-deterministic. One of them is to use algorithms that generate pseudo-random numbers. • The function random returns a random float between 0.0 to 0.1 and for integers( 1 and 100 ) • Python has a nodule called random, in which functions related to random numbers are available. To generate random numbers. Consider an example to generate random numbers import random for i in range(5): x = random.random() print(x)
  • 57. Random numbers • The function randint() takes the parameters low and high, and returns an integer between low and high, and returns an integer between low and high (including both) import random random.randint(5,10) The output may be between 5 and 10. for ex: 6, or, 7 or 9 To choose an element from a sequence from a sequence at random you can use choice import random t = [ 1, 2, 3, 4] random.choice(t) Output: it can choose any element from the list
  • 58. Some of Built-in Functions max() ex: max(“hello world”) output: w display the character having maximum ASCII code min() ex: min(‘hello world’) output: ‘ ‘ display the character having minimum ASCII code len() ex: len(“ hello”) output: 5 display the length of the string
  • 59. User-defined functions The general syntax of a user-defined function: def fname(arg list): statement1 statement2 -------------- --------------- statement n return value def: is a keyword indicating it as a function definition fname: is any valid name given to the function arg list: is list of arguments taken by a function. These are treated as inputs to the function from the position of function call. They may be zero or more arguments to a function. statements : are the list of instructions to perform required task return: is a keyword used to return the output value. This statement is optional.
  • 60. User-defined functions • The first line in the function def fname(arg list): is known as function header function definition. The remaining lines constitute function body. • The function header is terminated by a colon and body must be indented. • To come out of the function, indentation must terminated. # program to add two numbers using function def add(a, b): c = a + b return c s = add(10,20) # function call print(s)
  • 61. Void Functions A function that performs some task, but do not return any value to the calling function is known as void function. Example: def add(): a = 10 b = 20 c = a + b print(c) add() #function call Fruitful functions: The function which returns some result to the calling function after performing a task is known as fruitful function. All built-in functions are called fruitful function.
  • 62. Scope and lifetime of variables • All variables in program may not be accessible at all locations in that program. This depends on where you have declared a variable. • The scope of a variable determines the portion of the program where you can access a particular variable. There are two basic scope of variables in python: global variables local variables Global versus local variables: • Variables that are defined inside a function body have a local scope, and those defined outside have global scope. • This means that local variables can be accessed only inside the function in which they are declared. Where as global variables can be accessed throughout the program body by all function.
  • 63. Scope and lifetime of variables # program to demonstrate global and local variables total = 10 def add(a, b): total = a + b # here total is local variable print(total) add(10,20) print(total) # here total is global variable output: 30 10
  • 64. Default arguments • For some functions, you may want to make some parameters optional and use default values. In case the user does not want provide values for them. This is done with the help of default argument values. • Default argument values can be specified for parameters by appending to the parameter name in the function definition. The assignment operator(=) followed by the default value • Note that the default argument value should be a constant • Only the parameters which are at the end of the parameterlist can be default values. For example: def add(a, b = 5): is valid def add(a = 5,b): is invalid
  • 65. Default arguments # program to demonstrate default arguments def add(a, b = 5): c = a + b print(c) add(10,20) add(30) If we specify the argument values, then it will not take default value. If do not have a corresponding value for a argument then it will take a default value. Output for first function is 30 Output for first function is 35
  • 66. Keyword Arguments If you have some functions with many parameters and you want to specify only some of them, then you can give values for each parameters by naming from them, this is called keyword arguments. We use the name instead of the position to specify the arguments to the function. There are two advantages: 1. Using the function is easier since we do not need to worry about the order of the arguments 2. We can give values to only those parameters to which we want to provided that the parameter have default argument values.
  • 67. Keyword Arguments # program to demonstrate keyword arguments def func(a, b = 5 , c = 10): print(“a is “,a, “and b is”, b, ”and c is”,c) func(3,7) func(25,c = 24) func(b = 20, a =100) Output: a is 3 and b is 7 and c is 10 a is 25 and b is 5 and c is 24 a is 100 and b is 20 and c is 10
  • 68. *args and ** kwargs • Sometimes you might want to define a function that can take any number of parameters, i.e. variable number of arguments, this can be achieved by using the stars. • *args and ** kwagrs are mostly used as parameters in function definition. *args and ** args allows you to pass a variable number of arguments to the calling function. Here variable number of arguments means that the user does not know in advance about how many arguments will be passed to the called function. • *args as parameters in function definition allows you to pass a non- key worded, variable length tuple argument list to the called function. • **kwargs as parameter in function definition allows you to pass key worded. Variable length dictionary argument list to the called functions. • *args come after all the positional parameters and **kwargs must come right at the end.
  • 69. *args and ** kwargs # program to demonstrate *args and ** kwargs def func(a = 5, *numbers,**names): print(“a = “, a) for i in numbers: print(i) for fp,sp in names.items(): print(fp,sp) func(10,20,30,40,xxx = 40, yyy = 50 zzz = 60) output : a = 10 20 30 40 zzz 60 yyy 50 xxx 40
  • 70. Command line arguments The ‘sys’ module provides a global named ‘argv’ that is list of extra text that the user can supply when launching an application from the command prompt. # Python program to display command line arguments import sys n = len(sys.argv) print(“no of command line args =‘, n) print(“the arguments are”, args) print(“the args one by one”) for x in args: print(x) To run a program like this C:> python cmd.py 10,20,hello output : no of command line args = 3 The arguments are [‘10’,’20’,’hello’]
  • 71. Command line arguments #python program to add numbers using command line arguments import sys args = sys.argv sum = 0 for x in args: sum = sum + int(x) print(sum) To run this program c:> python sum.py 10 20 30 output 60
  • 72. Module-2 String: A string is a sequence of characters, Which include letters, numbers, punctuation marks and spaces. Creating and storing strings A string can be created enclosing text in single or double quotes. s = “hello” s1 = ‘python’ To nullify the effect of escape characters, we can create the string as ‘raw’ string by adding ‘r’ before the string as s = r “welcome to t core python n learning” print(s) Output: welcome to t core python n learning
  • 73. Strings Length of a string: Length of a string represents the number of characters in a string. To know the length of a string, we can use the len() function. s = “hello” l = len(s) print(l) output: 5 Basic string operations: 1. Repeating the strings: The repetition operator is denoted by * symbol and is useful o repeat the string for several times. For ex: str * n repeats the string for n times. s = “hai” print(s * 3) output: hai hai hai
  • 74. Strings 2. Concatenation of strings: We can use ‘+’ on strings to attach a string at the end of another string. s1 = “hello” s2 = “world” s3 = s1 + s2 print(s3) Output: Hello world 3. In operator: The in operator returns true if string or character found in the main string. It returns false if the string or character is not found in the main string.
  • 75. Strings # python program to check whether a substring exists in main string or # not str = input(“enter a main string”) sub = input(“enter a sub string”) if sub in str: print(“sub string present in main string”) else: print(“sub string is not present in main string”)
  • 76. Strings 4. Comparing strings: We can use the relational operators like >, ==, <, == or != operators to compare two strings. They return Boolean value i.e. either True or False depending on the strings being compared. s1 = “box” s2 = “boy” if s1 == s2: print(“same”) else: print(“not same”) This code returns ‘not same’ as the strings are not same. While comparing the strings, python interpreter compares them by taking them in English dictionary order. The string which comes first in the dictionary order will have low value than the string which comes next. It means ‘A’ is less than ‘B’ which is less than ‘C’ and so on.
  • 77. Strings # python program to compare two strings s1 = input(“enter a string1”) s2 = input(“enter a string 2”) if s1 == s2: print(“strings are equal”) elif s1 < s2: print(“strings are not equal”) else: print(“s1 is greater than s2”)
  • 78. Strings # Accessing characters in string by index number (Traversing in a st ring”) str = “hello” index = 0 while index < len(str): print(str[index], end = “ “) index = index + 1 # output h e l l o # Another way to traversal a string str = “hello” for ch in str: print(ch, end = “ “) # output h e l l o
  • 79. Strings Accessing characters in string by index number: • We can get at any single character using an index specified in square brackets. • The index value can be an integer and starts at zero. For example: str = “python” Character index str = “python” print(str[0]) # output p print(str[3]) #output h P Y T H 0 N 0 1 2 3 4 5
  • 80. Strings Python supports negative indexing starting from the end of the string as shown below. Character index str = “python” print(str[-3]) #output h print(str[-1]) #output n p y t h o n -6 -5 -4 -3 -2 -1
  • 81. Strings String Slicing: • A segment or a portion of a string is called as slice. • Only required number of characters can be extracted from string using (:) symbol. The basic syntax of slicing a string: String_name[start : end : step] Where, start: the position from where it starts. end: the position where it stops(end – 1) step: also known as stride, is used to indicate number of steps to incremented after extracting first character. The default value of stride is 1.
  • 82. Strings String slicing continued: • If start is mentioned, it means that slice should start from the beginning of the string. • If the end is not mentioned, it indicates the slice should be till end of the string. • If both are not mentioned, it indicates the slice, should be from the beginning till the end of the string. For example: S = “abcdefghij” Character Index Reverse index a b c d e f g h i j 0 1 2 3 4 5 6 7 8 9 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
  • 83. Strings String slicing continued: Slicing Result Description S[2:5] cde Characters at indices 2,3,4 S[:5] abcde First five characters S[5:] fghij Characters at index 5 to the end S[-2:] ij Last two characters S[:] abcdefghij Entire string S[1:7:2] bdf Characters from index 1 to 6 by step 2 S[::-1] jihgfedcba A negative step reverses the string
  • 84. String methods capitalize() : Make the first character have upper case and the rest lower case. Example: str = “hello” print(str.capitalize()) Output: Hello find: This method return the location of the first string occurrence of the sub string from the main string. The find method return -1, if the substring is not found in the main string. The general form is: mainstring.find(substring, beg, end) For example: str = “hello” str1 = “hello world” print(str.find(“l”)) #output 2 print(str.find(“x”)) # returns -1 print(str1.find(“o”,6,9) # returns 6
  • 85. String methods strip(): Return copy of the string with leading and trailing white spaces. For Example: str = “ hello world “ print(str.strip()) output: hello world strip(chars): If chars is given, remove characters specified at both the ends. For example: str = “ ### hello ###” print(str.strip(“#”)) output: hello rstrip(): is to remove white spaces at right side. For Example: str = “hello “ print(str.rstrip()) output: hello
  • 86. String methods lstrip() : it is used to remove the white spaces at left side, For Example: str = “ hello” print(str.lstrip()) # output: hello casefold(): It is an advanced version of lower() method. It converts the upper case letters to lower case letters including some special characters which are not specified in the ASCII table. For Example: str1 = “india” str2 = “INDIA” print(str1.casefold() == str2.casefold()) output: returns a value true startswith(): method returns true if the string starts with the specified value, Otherwise, false. General form is : string.startswith(value, start, end) Value: Required. The value to check if string starts with. Start: Optional. An integer specifying at which position to start the search. End: Optional. An integer specifying at which position to end the search
  • 87. String methods For Example: str = “logical” print(str.startswith(“l”)) #returns true print(str.startswith(“g”)) # returns false print(str.startswith(“l”,2,5) # returns false join() : It is used to join elements of the sequence separated by a string separator. This function joins elements of a sequence and makes it a string. For Example: str1 = “-” str2 = “abc” print(str1.join(str2)) output: a-b-c split(): The split method is used to brake a string into pieces. These are returned as a list. For example: str = “one, two, three, four” str1 = str.split(“,”) print(str1) output: [ “one”, two”, ”three”, ”four”]
  • 88. String methods lower(): The lower method converts the capital letters into lowercase letters. For Example: str = “HELLO” print(str.lower()) # output hello upper(): The upper method is used to convert all the characters of a string into uppercase. swapcase(): This method is used to converts letters into lower case letters and vice versa. str = “python is future” print(str.swapcase()) output: PYTHON IS FUTURE title : The title method converts the string such that each word in the string starts with a capital letter and remaining will be lowercase letters. For Example: str = “python is future” print(str.title()) output: Python Is Future
  • 89. String methods count(): This method is used to count the number of substrings occurs in a main string. str = “hello” print(str.count(“l”)) output : 2 replace(): This method is useful to replace a substring in a string with another sub string. The general form is: stringname.replace(old, new) for Example: str = “this is a beautiful college” str1 = “college” str2= “flower” str3 = str.replace(str1,str2) print(str3) output: this is a beautiful flower
  • 90. String methods isalpha(): Returns true if the string has at least one character and all characters are alphabets(A to Z and a to z). Otherwise, it returns false. For example: str =“hello” print(str.isalpha()) output: True Note: Strings are immutable, an immutable object is object whose content cannot be changed. In python numbers, strings and tuple are immutable. Lists, sets, dictionaries are mutable objects.
  • 91. Sorting strings We can sort a group of strings into alphabetical order using sort() method and sorted() function. When sort() method is used, it will sort the original array i.e. str. So the original order of strings will be lost and will have only one sorted array. To retain the original array even after sorting, we can use sorted() function. str1 = sorted(str) Here, str is the original array whose elements are to be sorted. After sorting the array, the sorted array will be referenced by str1. So, the sorted strings appear in str1. The original array ‘str’ is undistributed.
  • 92. Sorting strings # python program to sort strings in alphabetical order str = [] # empty string n = int(input(“enter how many strings”)) print(“enter strings”) for i in range(n): str.append(input()) str1 = sorted(str) print(“sorted list”) for i in str1: print(i)
  • 93. Lists A list is similar to an array that consists of a group of elements or items. The values inside the lists can be of any type like integers, float, strings and so on. The elements of the lists are enclosed within square brackets. Creating a list with numbers: lst = [10,20,30,40] Creating a list with strings: s = [“xxx”, “yyy”, “zzz”] Creating a list with different types: lst = [10,20,30,40.5,”xxx”] Nested lists can be created as follows: l1 =[10,20,30] l2 = [40.5, “xxx”] l3 = [ l1,l2]
  • 94. Lists Creating a list using range function: 1. l1 = range(4) print(l1) Output: [0,1,2,3] 2. l1 = range(5,10) print(l1) output: [5,6,7,8,9] 3. l1 = range(5,10,2) print(l1) output: [5, 7, 9]
  • 95. Lists Concatenation of lists: l1 = [10,20,30] l1 = l1 + [40,50] print(l1) Output: [10,20,30,40,50] Accessing the elements with in the inner list can be done by double indexing. For example: l = [ [10,20],[xxx, yyy]] print(l[1][0]) output: xxx
  • 96. List slicing We can make a new list from a portion of an existing list using a technique known as slicing. A list slice is an expression of the form: list_name[begin: end: step] • If the begin value is missing, it default to 0(zero) • If the end value is missing, it default to the length of the list • The default step value is 1. list index Reverse index 10 20 30 40 50 60 70 80 90 10 0 1 2 3 4 5 6 7 8 9 -10 -9 -8 -7 -6 -5 -4 -3- -2 -1
  • 97. List slicing For example: lst = [10,20,30,40,50,60,70,80,90,100] print(lst) # output [10,20,30,40,50,60,70,80,90,100] print(lst[0:3]) # [output 10,20,30] print(lst[4:8]) # output [50,60,70,80] print(lst[-5:-3]) # output [60,70] print(lst[:3]) # output [10,20,30] print(lst[4:]) # output [50,60,70,80,90,100] print(lst[:]) # output [10,20,30,40,50,60,70,80,90,100] print(lst[-100:3]) #output [10,20,30] print(lst[4:100]) # output [50,60,70,80,90,100] print(lst[2:-2:2]) #output [30,50,70] print(lst[::2]) # output [10,30,50,70,90]
  • 98. List slicing A begin value less than zero treated as zero. Ex: lst[-100:3] A end value greater than the length of the list is treated as the length of the list. Ex. Lst[4:100] # here 100 is treated as len(lst) Cloning of lists: x = [10,20,30,40] y = x[:] print(x) # output [10,20,30,40] print(y) # output [10,20,30,40]
  • 99. Lists Built-in functions used on lists : There are several built-in functions that operate on lists. Here some useful functions. len – returns the number of items in the list sum – returns the sum of items in the list min – returns the minimum in the list max – returns the maximum element in the list #program to demonstrate built-in functions lst = [30, 10, 50,40,20] print(“length =“, len(lst)) # output 5 print(“sum = “, sum(lst)) # output 150 print(“min =“, min(lst)) # output 10 print(“max =‘, max(lst)) #output 50
  • 100. Methods to process lists Method Example Description Index() lst.index(x) Returns the first occurrence of x in the list append() lst.append(x) Appends x at the end of the list insert() lst.insert(i, x) Inserts x to the list in the position specified by i copy() lst.copy() Copies all the list elements into a new list and returns 1 extend() lst.extend(list1) Appends list1 to list count() lst.count(x) Returns the number of occurrences of x in the list remove() lst.remove(x) Removes x from the list pop() lst.pop() Removes the ending element from the list Sort() lst.sort() Sorts the elements of the list into ascending order reverse() lst.reverse() Reverses the sequence of elements from the list clear() lst.clear() Deletes all elements from the list
  • 101. Lists # a python program to demonstrate list methods lst = [10, 20, 30, 40, 50] lst.append(60) print(“after appending 60 :”,lst) lst.insert(2,15) print(“list after inserting 15 at 2nd position: ”,lst) lst1 = lst.copy() print(“newly created list1 : “, lst1) lst.extend(lst1) print(“list after appending list1 :”, lst) c = lst.count(50) print(“number of times 50 found in the list:”,c) lst.remove(50) print(“list after removing 50”,lst) lst.pop() print(“list after removing ending element:”, lst)
  • 102. Lists # a python program to demonstrate list methods lst.sort() print(“list after sorting :”,lst) lst.reverse() print(“list after reversing:”, lst) lst.clear() print(“list after clearing all elements:”,lst) For Example: lst.sort() :- This will sort list in ascending order. If we want to sort the elements of list into descending order, then we can mention reverse = “True” in the sort function. lst.sort(reverse = True)
  • 103. Lists # python program to find the biggest element in the list lst = [] print(“how many elements”) n = int(input(“enter how many elements”)) print(“enter elements”) for i in range(n): lst.append(int(input()) print(“contents of list:”, lst) big = lst[0] for i in range(1,n): if lst[i] > big: big = lst[i] print(“biggest element = “, big)
  • 104. Lists # Finding common elements in the list lst1 = [10,30,40,50,60] lst2 = [20,30,50,70] s1 = set(lst1) #converts list into set s2 = set(lst2) #converts list into set s3 = s1.intersection(s2) common = list(s3) # converting set to list print(common)
  • 105. Sets A set in python programming is an unordered collection data type that is iterable, mutable and has no duplicate elements. We use curly braces({}) to enclose the elements of the set. For example: s = {10,20,30,40} Set operation: s1 = {0,2,4,6,8} s2 = { 1,2,3,4,5} print(“union of s1 and s2 :”, s1 | s2) print(“intersection of s1 and s2 :”, s1 & s2) print(“difference of s1 and s2 :”, s1 - s2) print(“symmetric difference of s1 and s2 :”, s1 ^ s2)
  • 106. Sets Operations on Sets: Operation Python syntax Meaning Union A | b Elements in A or B or both Intersection A & B Elements common to both A and B Set difference A – B Elements in A but not B Symmetric difference A ^ B Elements in A or B but not both
  • 107. Tuple A tuple is a python sequence which stores a group of elements or items. Tuples are similar to lists but the main difference is tuples immutable where as lists are mutable. Since tuples are immutable, once we create a tuple we cannot modify elements. Tuples are generally used to store data which should not be modified and retrieve that data on demand. Tuples are enclosed with the parenthesis: t = (10,20,30,40) t1 = (10,20,30.5,”xxx”) Accessing the tuple elements (slicing): t = (10,20,30,40,50) print(t[0]) # output 10 print(t[:]) # output (10,20,30,40,50) print(t[1:4]) # output is (20,30,40) print(t[::2]) # output is (10,30,50)
  • 108. Tuple Functions available to process tuples: Function/method Example Description len() len(t) Returns the number of elements in the tuple min() min(t) Returns the smallest element in the tuple max() max(t) Returns the biggest element in the tuple Count() t.count(x) Returns how many times the element x is found in tuple index() t.index() Returns the first occurrence of the element x in tuple. Raises value error if x is not found in the tuple. Sorted() sorted(t) Sorts the elements of the
  • 109. Dictionaries A dictionary represents a group of elements arranged in the form of key-value pairs. In the dictionary, the first element is considered as key and the immediate next element is taken as its value. The key and value are separated by a colon(:). All the key key-value pairs in a dictionary are inserted in curly braces ({}). For Example: dict = {“id” : 123, “name”: “xxx”, “salary”:9000) key value key value key value # A python program to create a dictionary with employee details and # retrieve the values upon giving the key. dict = {“id” : 123, “name”: “xxx”, “salary”:9000) print(“id number =‘, dict[“id”]) print(“name = “, dict[“name”]) print(“salary = “, dict[“salary”])
  • 110. Dictionaries Operations on Dictionaries: 1. If we want know how many key-value pairs are there in a dictionary, we can use the len() function. dict = {“id” : 123, “name”: “xxx”, “salary”:9000} n = len(dict) print(“number of key-value pairs =“, n) #output 3 2. We can modify the existing value of a key by assigning a new value, as shown in the following statement. dict[“salary”] = 9500 3. We can also insert a new key-value pair into an existing dictionary. This is done by mentioning the key and assigning a value to it, as shown in the following statements. dict[“dept”] = “sports”
  • 111. Dictionaries This pair is stored in the dictionary. If we print the dictionary created in the previous statement appears as shown below. print(dict) Output: {“id”:123, “dept”: “sports”, “name”: “xxx”, “salary”: 9500} Observe that “dept”: “sports” is added to the dictionary. Also, observe that this pair is not added at the end of the existing pairs. It may be added at any place in the dictionary. Suppose, we want to delete a key-value pair from the dictionary, we can use ‘del’ statement. del dict[“id”] This will delete the key “id” and its corresponding value from dictionary. Now, the dictionary look like this: {“dept”:”sports, ”name”: “xxx”, “salary” : 9500}
  • 112. Dictionary methods Method Example Description clear() d.clear() Removes all key-value pairs from dictionary copy() d1 = d.copy() Copies all the elements from ‘d’ into a new dictionary ‘d1’ get() d.get( k[,v]) Returns the value associated with key ‘k’ items() d.Items() Returns an object that contains key-value pairs of ‘d’ keys() d.keys() Returns a sequence of keys from the dictionary d. values() d.values() Returns a sequence of values from the dictionary update() d.update(x) Adds all elements from dictionary ‘x’ to ‘d’
  • 113. Dictionary # a python program to create a dictionary from keyboard and display the elements dict = {} # empty dictionary n = int(input(“how many key-value pairs”)) for i in range: print(“enter key”, end = “ “) k = input() # key is string print(“enter its value:”, end = “ “) v = int(input()) dict.update({k:v}) print(dict)
  • 114. Files A file is a collection of related information stored on a disk permanently. Opening a file: To perform a operation on file, we must open a file. The general form of opening a file is. File handler = open(“filename”, ”open mode”) Here, ‘file name’ represents a name on which the data is stored . The file ‘open mode’ represents the purpose of opening file. The file opening modes: File open mode Description w To write data into a file. if any data is already present in the file, it would be deleted and present data will be stored. r To read data from the file. The file pointer is positioned at the beginning of the file
  • 115. The file opening modes File open mode Description a To append data to the file, Appending means adding at the end of the existing file. The file pointer is placed at the end of the file. If file does not exists, it will create a new file for writing data. w+ To write and read data of a file. The previous data in the file will be deleted. r+ To read and write into a file. The previous data in the file will not be deleted. The file pointer is placed at the beginning of the file. a+ To append and read data of a file. The file pointer will be at end of the file if the file exists, If file does not exists, it creates a new file for reading and writing. x To open a file in exclusive creation mode. The file creation fails if the file already exists.
  • 116. Files For example: f = open(“abc.txt”, “w”) Here, ‘f’ represents the file handler or file object. It refers to the file with the name “abc.txt” that is opened in “w” mode. This means, we can write data into the file but we cannot read data from this file. If the file already exists, then its contents are deleted and the present data is stored into the file. Closing a file: A file which is opened should be closed using the close() method. Once a file is opened but not closed, then the data of the file may be corrupted or deleted in some cases. Also, if the file is not closed, the memory utilized by the file not freed, leading to problems like insufficient memory. This happens when we are working with several files simultaneously. Hence it is mandatory to close the file f.close()
  • 117. Files # python program to create a file (write a data) and read data from the # file f = open(“abc.txt”, ”w”) str = input(“enter a text”) f.write(str) f.close() f = open(“abc.txt”, ”r”) str1 = f.read() print(str1) f.close()
  • 118. Files # a python program to store a group of strings into a text file and # retrieve it. f = open(“xyz.txt”, ”w”) print(“enter text ( @ at end) : “) while str != “@”: str = input() if str != “@”: f.write(str + “n”) f.close() f = open(“xyz.txt”, ”r”) print(“file contents”) str1 = f.read() print(str1) f.close()
  • 119. Files # python program to count number of lines, words and characters in a # text f = open(“abc.txt”, “w”) print(“enter a text @ at end:”) while str != “@” str = input() if str != “@”: f.write(str + n) f.close() f = open(“abc.txt”, “r”) cl = cw = cc = 0 for line in f: words = line.split() cl = cl + 1 cw = cw + len(words) cc = cc + len(line) print(“number of lines = “, cl) print(“number of words = “,cw)
  • 120. Class The mechanism that allows us to combine data and operations on those data into a single unit is called class. The general form of class is: A class is created with the keyword class and then writing the class name. The attributes are nothing but variables that contains data. __init__(self) is a special method or constructor to initialize the variables. Method1() and Method2() - - etc are methods that are intended to process the variables. class classname: attributes def __init__(self): def method1(): def method2():
  • 121. class # python program to demonstrate class class Student: def __init__(self): self.usn = “ “ self.name = “ “ self.marks = 0 def getdata(self): self.usn = input(“enter usn”) self.name = input(“enter name”) self.marks = int(input(“enter marks”)) def putdata(self): print(“usn =“, self.usn) print(“name =“,self.name) print(“marks = “,self.marks) s = Student() # creating an object s.getdata() s.putdata()
  • 122. Class Observe that the keyword class is used to declare a class. After this, we should write the class name. So student is our class name. Generally, a class name should start with a capital letter. Hence ‘s’ is capital in student. In the class, we write attributes and methods. To create an object, the following syntax is used: objectname = classname() So, to create an instance for object to the student class, we can write s = Student()
  • 123. The self variable ‘self’ is a default variable that contains the memory address of the instance (object) of the current class. So, we can use ‘self’ to refer to all the instance variable and instance methods. When an instance(object) to the class is created, the instance name contains the memory location of the instance(object). This memory location is internally passed to ‘self’. For example, we create an instance to student class as s = Student() Here s contains the address of the instance (object). This memory address is internally and by default passed to the ‘self’ variable. Since ‘self’ is known as the address of the instance(object). We use self in two ways. The ‘self’ variable is used as first parameter in the constructor as def __init__(self): In this case, self can be used to refer to the instance variables inside the construct0r
  • 124. class ‘self’ can be used as first parameter in the instance method as, def getdata(self): Here, getdata() is instance method as it acts on the instance variables. Constructor: A constructor is a special method that is used to initialize the instance variables of a class. In the constructor, we create the instance variables and initialize them with some starting values. The first parameter of the constructor will be ‘self; variable that contains the memory address of the instance. For example def __init__(self): self.a = 0 self.b = 0 Here, the constructor has only one parameter, i.e. ‘self’. Using the ‘self.a’ and ‘self.b’, we can access the instance variables of the class. A constructor is called when we creating the object of a class.
  • 125. Constrctors # python program to demonstrate a constructor class Cons: def __ init__(self): self.a = 10 self.b = 20 def printdata(self): print(self.a) print(self.b) x = Cons() x.printdata()
  • 126. Parameterized Constructor class Parcons: def __init__(self, m = 0, n = 0): self.a = m self.b = n def putdata(self): print(self.a) print(self.b) x = Parcons() # constructor called without parameter y = Parcons(10,20) # constructor called with arguments x.putdata() y.putdata()
  • 127. Polymorphism ‘Poly’ means ‘many’, morphism means forms. It is an ability to take more than one form. The polymorphism is achieved in python by using method overloading. Method Overloading ; If a method is written such that it can perform more than one task, it is called method overloading. # python program to demonstrate method overloading class Moverload: def add(self, m, n): self.c = m + n print(self.c) m = Moverload() m.add(10,20) # output 30 m.add(“hello”, “world”) # output helloworld (concatenate two strings)
  • 128. Constructor overloading # python program to overload a constructor class Coverload: def __init__(self, *args): for i in args: print(I, end = “ “) x = Coverload(10,20,30) # output 10 20 30 y = Coverload(“hello”, “world”) # output hello world
  • 129. Inheritance The mechanism of deriving a new class from the old class is called inheritance. The old class is called base class and new class is called derived class. There are different types of inheritance. 1. Single level inheritance 2. Multi-level inheritance 3. Hierarchical inheritance 4. Multiple inheritance 1. Single Inheritance : A mechanism of deriving a single class from the base class is called single level inheritance.
  • 130. Single Level Inheritance # Program to demonstrate single level inheritance class A: def __init__(self): self.a = 0 self.b = 0 self.c = 0 def getdata(self): self.a = int(input(“enter a”)) self.b = int(input(“enter b”)) def putdata(self): print(self.a) print(self.b) class B(A): # derived class def sum(self): self.c = self.a + self.b print(self.c) x = B()
  • 131. Multi-level Inheritance # Program to demonstrate multi level inheritance class A: def __init__(self): self.a = 0 self.b = 0 self.c = 0 def getdata(self): self.a = int(input(“enter a”)) self.a = int(input(“enter b”)) def putdata(self): print(self.a) print(self.b)
  • 132. Multi-Level Inheritance Continued class B(A): # derived class def sum(self): self.c = self.a + self.b print(self.c) class C(B): # derived class def prod(self): self.d = self.a * self.b print(self.d) x = C() x.getdata() x.putdata() x.sum() • x.prod()
  • 133. Hierarchical Inheritance # python program to implement Hierarchical inheritance class A: def __init__(self): self.a = 0 self.b = 0 def getdata(self): self.a = int(input(“enter a”)) self.b = int(input(“enter b”)) def putdata(self): print(self.a) print(self.b)
  • 134. Hierarchical Inheritance continued class B(A): # derived class def sum(self): self.c = self.a + self.b print(self.c) class C(A): # derived class def prod(self): self.d = self.a * self.b print(self.d) x = B() x.getdata() x.putdata() x.sum() y = C() y.getdata() y.putdata()
  • 135. Multiple Inheritance # python program to implement Multiple inheritance class A: def __init__(self): self.a = 0 def getdata(self): self.a = int(input(“enter a”)) class B: def __init__(self): self.b = 0 def inputdata(self): self.b = int(input(“enter b”))
  • 136. Multiple Inheritance continued class C(A,B): def sum(self): self.s = self.a + self.b print(self.s) x = C() x.getdata() x.inputdata() x.sum()
  • 137. Method Overriding When there is a method in the super class, Writing the same method in the sub class so that it replaces the super class method is called method overriding. # Python program to demonstrate method overriding class A: def disp(self): print(“welcome to java world”) class B(A): def disp(self): print(“welcome to Python world”) x = B() x.disp() # output is welcome to python world
  • 138. Constructors in super class class A: def __init__(self): print(“super class constructor executed”) class B(A): def __init__(self): print(“sub class constructor called”) x = B() output: sub class constructor executed. If you have constructor written in the super class and subclass, then it will execute sub class constructor. If you do not have a sub class constructor, then it will execute the super class constructor.
  • 139. Module 3 Regular Expression: A regular expression is a string that contains special symbols and characters to find and extract the information needed by us from the given data. A regular expression helps us to search information, match, find and split information as per our requirements. Sequence characters in regular expressions Character Its Description d Represents any digit ( 0 to 9) D Represents any non digit s Represents white space S Represents non white space w Represents any alphanumeric (A to Z, a to z, 0 to 9) W Represents non-alphanumeric b Represents a space around words
  • 140. Regular Expressions Regular expression are used to perform the following important operations. Python provides ‘re’ module that stands for regular expression. This module contains the following methods. • Matching strings • Searching for strings • Finding all strings • Splitting string into pieces • Replacing strings match method() : The match method searches the beginning of the string and if matching string is found, it returns an object that contains the resultant string. Otherwise it returns the none. We can access the string from the returned object using group() method.
  • 141. Regular Expressions # A python program to create a regular expression using match() method to search for strings starting with m and having total 3 characters. import re str = “man, sun, mop, run” result = re.match(r “mww”, str) print(result.group()) output: man . # A python program to create a regular expression using match() method to search for strings starting with m and having total 3 characters. import re str = “sun, man, mop, run” result = re.match(r “mww”, str) print(result) output: none
  • 142. Regular Expressions findall() : Method searches the string from beginning till the end and returns all occurrences of the matching string in the form of list object. If the matching strings are not found , then it returns empty list # A python program to create a regular expression using match() method to search for strings starting with m and having total 3 characters. import re str = “man, sun, mop, run” result = re.findall(r “mww”, str) print(result) Output: [“man”, “mop”]
  • 143. Regular Expressions search(): The search method searches the string from beginning till the end returns the first occurrence of the matching string. Otherwise, it returns none. We can use group() method to retrieve the string from the object returned by this method. # A python program to create a regular expression using match() method to search for strings starting with m and having total 3 characters. import re str = “ sun, man, mop, run” result = re.findall(r “mww”, str) print(result) Output: man
  • 144. Regular Expressions split(): The split() method splits the string according to the regular expression and resultant pieces returned as a list. If there are no string pieces, then it returns an empty list. # A python program to create a regular expression to split string into pieces where one or more white spaces. import re str = “welcome to python” result = re.split(“ s+”, str) print(str) Output: [“welcome”, “to”, “python”]
  • 145. Regular Expressions sub(): This method substitutes or replaces in the place existing strings. After substitution, the main string is returned by this method. import re str = “welcome to java” res = re.sub(r “welcome”, “python”,str) print(res)
  • 146. Module 4 Arrays and Numpy in Python : An array is an object that stores group of elements of same datatype Advantages of Arrays: • Arrays are similar to lists. The main difference is that always can store only one type of elements. Where as the lists can store different types of elements. • The size of the array is not fixed in python. Hence, we need not specify how many elements we are going to store into array in the beginning. • Arrays can grow or shrink in memory dynamically(during run time) • Methods that are useful to process the elements of any array are available in array module.
  • 147. Arrays Creating an array : The type should be specified by using a type code at the time creating the array object as: arrayname = array(typecode, [elements]) The typecode ‘i’ represents I integer type where we can store integer numbers. If the type code is ‘f’ then it represents float type array where we can store numbers with decimal point. The important type codes are given below: Typecode Ctype Minimum size in bytes ‘b’ Signed integer 1 ‘B’ Unsigned integer 1 ‘i’ Signed integer 2 ‘I’ Unsigned integer 2 ‘l’ Signed integer 4 ‘L’ Unsigned integer 4 ‘f’ Double precision 4
  • 148. Arrays Type code Ctype Minimum size in bytes ‘d’ Double precision floating point 8 ‘u’ Unicode character 2
  • 149. Arrays # creating an array using python import array as ar a = ar.array(“i”, [-1,2,3,4]) print(“elements of array”) for i in a: print(i) Output: -1 2 3 4
  • 150. Arrays # Creating array with characters import array as ar a = ar.array(‘u’,[‘a’, ‘b’, ‘c’, ‘d’]) print(“the array elements are”) for ch in a: print(ch) # output a b c d # Creating floating type array import array as ar a = ar.array(‘f ’,[1.5,2.5,3.5.4.5]) print(“the array elements are”) for i in a: print(i) # output 1.5 2.5 3.5 4.5
  • 151. Arrays # A python program to retrieve the elements of an array using index import array as ar a = ar.array(‘I’, [10,20,30,40]) n = len(a) for I in range(n): print(a[i], end= “”) # output 10 20 30 40
  • 152. Array Slicing A slice presents a piece of the array. When we perform slicing operation on any array, we can retrieve a piece of the array that contains a group of elements. The general format of slice is: arrayname[start : stop : step] import array as ar a = ar.array(‘i’, [10,20,30,40,50]) print(a[1:4]) # output [20,30,40] print(a[0:]) # output print all the elements of an array print(a[:4] # output [10,20,30,40] print(a[-4:]) # prints the last four elements [20,30,40,50] print(a[-4: -1] # prints [20,30,40] print(a[0:4:2]) # prints [10,30]
  • 153. Processing the arrays The arrays class of arrays module in python offers methods to process the arrays easily. The programmers can easily perform certain operations by using these methods. Method Description a.append(x) Adds an element ‘x’ at the end of the existing ‘a’ a.count(x) Returns the number of occurrences of x in the array ‘a’ a.extend(x) Appends x at the end of the array a . ‘x’ Can be another array a.fromfile(f, n) Reads n items from the file object a.fromlist(lst) Appends items from the list to the end of the array. a.fromstring(s) Appends items from the string ‘s’ to the end of the array ‘a’
  • 154. Processing the arrays Method Description a.Insert(i, x) Inserts ‘x’ in the position ‘I’ a.pop() Removes the last item from the array ‘a’. a.remove(x) Removes the first occurrence of x in the array ‘a’ a.reverse() Reverses the order of elements in the array ‘a’ a.tolist() Converts the array ‘a’ into list
  • 155. Program to demonstrate array methods import array as ar a = ar.array(‘i’, [10, 20, 30, 40, 50]) a.append(60) print(a) # output [10,20,30,40,50,60] a.insert(2,70) print(a) # output [10,20,70,30,40,50,60] a.remove(20) print(a) # output [10,70,30,40,50,60] a.pop() print(a) # output [10,70,30,40,50] print(a.index(30)) # returns 2 lst = a.tolist() print(lst) # output [10,70,30,40,50]
  • 156. Program to read and print an array using keyboard import array as ar a = ar.array(‘i’, []) # creates an empty array to store integers n = int(input(“enter how many elements”)) for i in range(n): print(“enter an element”) a.append(int(input()) print(“the contents of array”) for i in a: print(i)
  • 157. Numpy Numpy is a package that contains several classes, functions, variable etc, to deal with scientific calculations in python. Numpy is useful to create and also process single and multi-dimensional arrays. In addition, numpy contains a large library of mathematical functions like linear algebra functions and Fourier transformations. Creating array using numpy : import numpy as np a = np.array([10,20,30,40],int) print(a) Creating arrays in numpy can be done in several ways. Some of the important ways are
  • 158. Numpy Creating arrays in numpy can be done in several ways. Some of the important ways are: 1. Using array() function 2. Using linspace() function 3. Using logspace() function 4. Using arange() function 5. Using zeros() and ones() function Creating array using array() We can call array function of numpy module to create an array. When create an array, we can specify the datatype of the elements either ‘int’ or ‘float’. We can create an integer array type array as arr = array([10,20,30,40],int)
  • 159. Numpy To create an array with float type elements, we should specify ‘float’. Import numpy as np arr = np.array([10.5,20.5,30.5.40.5], float) In the array, if python interpreter finds one element belonging to ’float type’, then it will also convert into float type by a decimal point after the element as Import numpy as np arr = np.array([10,20,30.5,40]) If we display this array using print() function, we can see the array as [ 10., 20., 30.5, 40.] To create an array with character type elements, we need not specify the datatype. We can simply write import numpy as np arr = np.array([‘a’, ’b’ ,’c’, ‘d’])
  • 160. Numpy # creating a array using numpy import numpy as np a = np.array([10,20,30,40],int) print(a) Creating arrays using linspace: The linspace() function is used to create an array with evenly spaced points between a starting and ending point. The general form of the linspace() function as: linspace(start, stop, n) ‘start’ represents the starting element and stop represents the ending element. ‘n’ is an integer that represents the number of parts the elements should be divided. If ‘n’ is omitted, then it is taken as 50.
  • 161. Numpy # a python program to creating an array with 5 equal parts using linspace. import numpy as np a = np.linspace(2,10,5) print(“a = “,a) Output: a = [2,4,6,8,10] Creating arrays using logspace: The linspace() function produces evenly spaced points. Similarly, logspace() function produces evenly spaced points on a logarithmically spaced scale. The general form is: logspace(start, stop, n) The logspace() function starts at value which is ‘start’ to the power of 10 and ends at a value which is stop to the power of 10. If n is not specified, then its value is taken as 50. For example: if we write
  • 162. Numpy a = logspace(1,4,5) The function represents values 1 to the power of 10 to 4 to the power of 10. These values are divided into 5 equal points and those points are stored into the array ‘a’. import numpy as np a = np.logspace(1,4,5) print(a) Output: [10.0, 56.2,316.2, 1778.3,10000.0] Creating arrays using arange() function The arange() function in numpy as same as range() function in python. The arange function is used in the following format. arange(start, stop, stepsize) This creates an array with a group of elements from start to stop – 1 in steps of step size. If the step size is omitted, then it is taken as zero. Ex : arange(10) will produce an array with elements 0 to 9. arange(5,10) will produce an array with elements from 5 to 9 arange(1,10,3) will produce 1, 4, 7 arange(5,1,-1) will produce 5,4,3,2
  • 163. Numpy # Creating array with arange function import numpy as np a = np.arange(2,11,2) print(“a =“, a) Output: a = [2,4,6,8,10] Creating arrays using zeros() and ones() function: We can use zeros() functions to create an array with all zeros. The one function is useful to create an array with all 1’s. They are written in the following format. zeros(n, datatype) ones(n, datatype) Where ‘n’ represents the number of elements. We can eliminate the ‘datatype’ argument. If we do not specify the datatype then the default datatype used by numpy as ‘float’.
  • 164. Numpy For example: zeros(4) This will create an array with four elements all zeros as [0.,0.,0.,0.] If we want this array in integer format, we can use ‘int’ as datatype, as zeros(4,int) this will create an array as : [0,0,0,0] If we use ones() function, it will create an array with elements 1. For ex: ones(5,float) will create an array with 5 integer elements are [1.,1., 1.,1.,1.] Creating arrays using zeros() and ones() import numpy as np a = np.zeros(5,int) print(a) b = np.ones(5) # default datatype is float print(b)
  • 165. Numpy We apply mathematical functions like sin(), cos(), sqrt(), exp() and so on the elements of the array. The list of functions that can be used on numpy arrays. Function meaning sin(arr) Calculate the sine value of each element in the array arr. cos(arr) Calculates the cosine value of each element in the array arr. log(arr) Calculates natural logarithmic value of each element in the array arr. abs(arr) Calculates absolute value of each element in the array arr. sqrt(arr) Calculates square root value of each element in the array arr.
  • 166. Numpy Function Meaning exp(arr) Calculates exponentiation value of each element in the array arr. sum(arr) Returns the sum of all elements in the array arr. prod(arr) Returns the product of all the elements in the array arr. min() Returns smallest element in the array arr. max(arr) Returns the biggest element in the array arr. mean(arr) Returns the mean value( average ) of elements in the array arr. median(arr) Returns median value of all elements in the array arr. unique(arr) Gives array that contains unique elements of the array arr. sort(arr) Gives an array with sorted elements of the array arr in ascending order
  • 167. Numpy # python program to demonstrate mathematical function on arrays. import numpy as np arr = np. array([10,20,30,5,40],int) print(“original array = “, arr) print(“after adding 5 = “, arr + 5) print(“sin value = “, sin(arr)) print(“cos value =“, cos(arr)) print(“biggest value =“, max(arr)) print(“minimum value = “, min(arr)) print(“sum of all elements = “, sum(arr)) print(average of all elements = “,avg(arr))
  • 168. Numpy Comparing Arrays : We can use the relational operators >,<,==, >=,<=,>=, and != to compare the arrays of same size. import numpy as np a = np.array([1,2,3,0],int) b = np.array([0,2,3,1],int) c = a== b print(“result of a==b”, c) c = a > b print(“result of a >b”, c) c = a <= b print(“result of a<=b”, c) Result of a==b [False True True False] Result of a>b [True False False False]
  • 169. Numpy any() Function : The any function can be used to determine if any one element of the array is True. all() Function: The all() function can be used to determine whether the all elements in the array are true. The any() and all() functions returns either True or False. # python program to demonstrate all() any() functions. import numpy as np a = np.array([1,2,3,0],int) b = np.array([0,2,3,1],int) c = np.array([0,2,3,1],int) d = a > b print(“check if any one of the element is true”, any(d)) d = b == c print(“check if all elements are true”, all(d)) Output: True True
  • 170. Slicing in Numpy arrays import numpy as np a = np.arrange(1,6) # creates an array an array with 1 to 5 print(a) # prints 1 2 3 4 5 b = a[1:6:2] print(b) # prints [1,3,5] b = a[-2,2:1] print(b) # prints[4,3,2] b = a[: -2 : ] print(b) # prints [1,2,3]
  • 171. Attributes of numpy array (variables) Numpy array class is called ndarray. This class contains the following attributes. The ‘ndim’ attribute : The ‘ndim’ attribute represents the number of dimensions of the array. The number of dimensions is also referred to as rank. For a single dimensional array rank is 1 and for two dimensional array brank is 2. # program to demonstrate ndim attribute import numpy as np a = np.array([1,2,3,4],int) print(a.ndim) # returns 1 b = np.array([[1,2,3],[4,5,6]],int) print(b.ndim) # returns 2 The ‘shape’ atttribute: The ‘shape’ attribute gives the shape of an array. The shape is tuple listing the number of elements along each dimension. For a 1 dimensional array, shape elements in the row. For a two dimensional array, it specifies the number of rows and columns in each row. We can also change the shape using ‘shape’ attribute.
  • 172. Attributes of numpy array (variables) # program to demonstrate shape attribute a = np.array([1,2,3,4],int) print(a.shape) # prints (4,) b = np.array([[1,2,3],[4,5,6]],int) print(b.shape) # prints (2,3) b.shape = (3,2) print(b) # [[1 2] [3 4] [5 6]]
  • 173. Attributes of numpy array (variables) The size attribute: The ‘size’ attribute gives the total number of elements in the array. # Python program to demonstrate size attribute. import numpy as np a = np.array([1,2,3,4,5],int) # prints 5 print(a.size) b = np.array([[1,2,3], [4,5,6]],int) print(b.size) # prints 6 The ‘itemsize’ attribute : The ‘item size’ attribute gives the memory size of the array element in bytes import numpy as np a = np.array([1,2,3,4],int) print(a.size) # prints 4 (long integer) b = np.array([1.5,2.5,3.5,4.5],float) # prints 8 (double precision)
  • 174. Attributes of numpy array (variables) The dtype attribute: The ‘dtype’ attribute gives the datatype of the elements in the array. import numpy as np a = np.array([1,2,3,4],int) print(a.dtype) # prints int32 b = np.array([1.5,2.5,3.5.4.5],float) print(b.type) # pints float64 The nbytes attribute: The ‘nbyte’ attribute gives the total number of bytes occupied by an array. The total number of bytes = size of array * itemsize of each element in the array.
  • 175. Attributes of numpy array (variables) # Python program to demonstrate nbytes attribute import numpy as np a = np.array([1,2,3,4],int) print(a.nbytes) # prints 16 each element occupies 4 bytes b = np.array([[1,2,3],[4,5,6]],int) print(b.nbytes) # prints 24 bytes c = np.array([1.5,2.5.3.5,4.5],int) print(c.nbytes) # prints 32 bytes
  • 176. Numpy The reshape() method : The reshape() method is useful to change the shape of an array. The new array should have the same number of elements as in the original array. # Pyhton program to demonstrate reshape() method import numpy as np a = np.arange(6) print(a) # creates an array [0,1,2,3,4,5] b = np.reshape(2,3) print(b) # change the shape as 2 rows and 3 columns output: [[0 1 2], [3,4,5]]
  • 177. Numpy The flatten method: The flatten method is useful to return a copy of the array collapsed into one dimension. # Python program to demonstrate flatten method a = np.array([[1,2,3],[4,5,6],int) print(a) # [[ 1 2 3] [ 4 5 6]] b = a.flatten() print(b) # prints [1 2 3 4 5 6]
  • 178. Working with multidimensional arrays with numpy The 2d array, 3D arrays , etc . Are called multidimensional arrays. A 2D array contains more than 1 row and 1 column. A 2D array is also considered as matrix. For Ex: A 2D array with m rows and n columns is called m * n matrix. We can create multidimensional arrays in the following ways. 1. Using array Function. 2. Using ones() and zeros() function 3. Using eye() function 4. Using reshape() function The array() Function: Numpy’s array function can be used to create multidimensional array. Usually, we pass lists of elements to this function.
  • 179. Working with multidimensional arrays with numpy # python program to create a multidimensional array. import numpy as np a = np.array([[1,2,3], [4,5,6]]) print(a) Output:[[1 2 3] [4 5 6]] The ones() and zeros() functions : The ones() function is useful to create a 2D array with several rows and columns where all the elements will be taken as 1. The format of this function is: ones ((r, c),datatype) Here ;r; represents number of rows and ‘c’ represents the number of columns. Datatype represents the datatype of the elements in the array.
  • 180. Working with multidimensional arrays with numpy # python program to demonstrate ones() function to create array import numpy as np a = np.one((2,2),float) print(a) Output: [[ 1. 1.] [1. 1.]] Just like the ones() function, we can also use the zeros() function to create a 2d array with elements filled with zeros. # python program demonstrate zeros() to create array import numpy as np a = np.zeros((2,2),int) print(a) Output: [[0 0] [0 0]]
  • 181. Working with multidimensional arrays with numpy The eye() function : The eye() function creates a 2d array and fills the elements in the diagonal with 1’s. The general format of using this function is: eye(n, dtype = datatype) This will create an array with ‘n’ rows and ‘n’ columns. The default datatype float. # Python program to demonstrate eye function import numpy as np a = np.eye(2) print(a) # out put [[1. 0.] [0. 1.]] b = np.eye(2, dtype = int) print(b) # output [[ 1 0] 0 1]]
  • 182. Working with multidimensional arrays with numpy The reshape() function: This function is useful to convert 1D array into multidimensional array. The general form is: reshape(arrayname,(n, r, c)) Here, array represents the name the array whose elements to be converted . ‘n’ indicates the number the number of arrays in the resultant array. ‘r’, ‘c’ indicates the number of rows and columns respectively. # program to demonstrate reshape() function import numpy as np a = np.array([1,2,3,4,5,6]) b = np.reshape(a,(2,3)) print(b) # output [[1 2 3] [4 5 6]]
  • 183. Matrices in numpy In, mathematics, a matrix represents a rectangular array of elements arranged in rows and columns. When a matrix has more than 1 row and more than 1 column, it is called m * n matrix. Where m represents the rows and n represents the columns. # create a matrix import numpy as np a = np.array([[1,2,3],[4,5,6]]) b = np.matrix(a) print(b) # output [[1 2 3] [4 5 6]]
  • 184. Getting Diagonal elements of a matrix To retrieve the diagonal elements of a matrix, we can use diagonal() function: The general for is: a = diagonal(matrix) The diagonal() function returns a 1D array that contains diagonal elements of the original matrix. import numpy as np a = np.matrix(‘1 2 3; 4 5 6; 7 8 9’) print(a) # output [[ 1 2 3] [4 5 6] [7 8 9]] d = np.diagonal(a) print(d) # output [ 1 5 9]
  • 185. Finding maximum and minimum elements To know the maximum element, we use max() method and to the minimum element, we can use min() method. These methods should be using matrix name. # program to demonstrate max(0 and min() method import numpy as np a = np.array([[3,1,2],[8,4,6]]) b = np.matrix(a) big = b.max() small = b.min() print(big) print(small)
  • 186. Finding sum and average of elements To find the sum of all elements in the matrix, we can use sum() method and to find average, we can use mean method. These methods should be called using the matrix name. import numpy as np a = np.array([[1,2,3],[4,5,6]]) b = np.matrix(a) s = b.sum() m = b.mean() print(s) # output 21 print(m) # output 3.5
  • 187. Product of elements It is possible to know the product of elements in a matrix. For this purpose, numpy provides prod() method. For example: prod(0) returns a matrix that contains the products of elements in each column of the original matrix. prod(1) returns a matrix that contains products of elements of each row. These methods should be called using matrix name. # Python program to demonstrate product() a = np.array([[1,2],[3,4]]) # [1 2 3 4] b = np.matrix(a) c = b.prod(0) print(c) # [3 8] r = b.prod(1) print(r) # [[2] [12]]
  • 188. Sorting the matrix Numpy provides sort function that sorts the matrix elements into ascending order. The general syntax is: sort(matrixname, axis) If we use axis = 1, it sorts the elements in each into ascending order. If we use axis = 0, then it sorts the elements in column into ascending order. The default value of axis is 1. # program to demonstrate sort method import numpy as np a = np.array([[3,5,4],[1,8,6]]) # 3 5 4 1 8 6 b = np.matrix(a) r = np.sort(b,1) print(r) # output [[ 3 5 4] [1 6 8]] c = np.sort(b,0) # output [ [1 5 4] [3 8 6]]
  • 189. Transpose a matrix Rewriting matrix rows and into columns and vice versa is called ‘transpose’. Thus the rows in the original matrix will become rows in the original matrix will become rows in the transpose matrix. To find the transpose, we can transpose() and getT() methods in numpy. These methods should be called using matrix name. # Python program to demonstrate transpose method import numpy as np m = np.matrix(‘1,2; 3,4; 5,6’) print(m) # output [[ 1 2] [3 4] [5 6] t = m.transpose() t1 = m.getT() # output [[ 1 3 5] print(t1) [ 2 4 6]]
  • 190. Matrix addition and Multiplication # python program demonstrate arithmetic operations import numpy as np a = np.matrix([[1,2].[3,4]]) a = [ 1 2 3 4] b = np.matrix([[1,2].[3,4]]) b = [1 2 3 4] c = a + b print(c) # output [ [2 4] [6 8]] d = a – b #output [[0 0] [0 0]] print(d) e = a * b # output [[7 10] [15 12]] print(e)