You are on page 1of 72

PYTHON PROGRAMMING

By

Trainer

Mohammad Majeed

TechIn It processing
Syllabus

Introduction To Python
History of Python Features of Python
Python Syntax
Python Variables
Python Comments
Python Data Types
Python Numbers
Python Casting
Python Strings
Python Booleans
Python Operators
Python List
Python Tuples
Python Dictionaries
Python If… Else
Python While Loops
Python For Loops
Python Functions
Python Lambda
Python Arrays
Python Classes/Objects
Python Inheritance
Python Iterators
Python Polymorphism
Python Scope
Python Modules
Python Dates
Python Math
Python JSON
Python RegEx
Python PIP
Python Try… Except
Python User Input
Python String Formating
File Handling
Python File Handling
Python Read Files Python

2
Introduction to Python and installation:

Python is a widely used general-purpose, high level programming language. It was initially designed by Guido van
Rossum in 1991 and developed by Python Software Foundation. It was mainly developed for emphasis on code
readability, and its syntax allows programmers to express concepts in fewer lines of code.
Python is a programming language that lets you work quickly and integrate systems more efficiently.
There are two major Python versions- Python 2 and Python 3.

On 16 October 2000, Python 2.0 was released with many new features.
On 3rd December 2008, Python 3.0 was released with more testing and includes new features.

Beginning with Python programming:


Finding an Interpreter:
Before we start Python programming, we need to have an interpreter to interpret and run our programs. There are
certain online interpreters like https://ide.geeksforgeeks.org/, http://ideone.com/ or http://codepad.org/ that can be
used to start Python without installing an interpreter.
Windows: There are many interpreters available freely to run Python scripts like IDLE (Integrated Development
Environment) which is installed when you install the python software from http://python.org/downloads/

Why to use Python:

The following are Features of python:


Python is object-oriented
Structure supports such concepts as polymorphism, operation overloading and multiple inheritance.
Indentation
Indentation is one of the greatest feature inIt’s free (open source)
Downloading python and installing python is free and easy
It’s Powerful
Dynamic typing
Built-in types and tools
Library utilities
Third party utilities (e.g. Numeric, NumPy, sciPy)
Automatic memory management
It’s Portable
Python runs virtually every major platform used today
As long as you have a compaitable python interpreter installed, python programs will run in exactly the same
manner, irrespective of platform.
3
It’s easy to use and learn
No intermediate compile
Python Programs are compiled automatically to an intermediate form called byte code, which the interpreter then
reads.
This gives python the development speed of an interpreter without the performance loss inherent in purely
interpreted languages.
Structure and syntax are pretty intuitive and easy to grasp.
Interpreted Language
Python is processed at runtime by python Interpreter
Interactive Programming Language
Users can interact with the python interpreter directly for writing the programs
Straight forward syntax
The formation of python syntax is simple and straight forward which also makes it popular.

Installation:
There are many interpreters available freely to run Python scripts like IDLE (Integrated Development
Environment) which is installed when you install the python software from http://python.org/downloads/
Steps to be followed and remembered:
Step 1: Select Version of Python to Install. Step 2: Download Python Executable Installer. Step 3: Run Executable
Installer.
Step 4: Verify Python Was Installed On Windows.

4
Step 5: Verify Pip Was Installed.
Step 6: Add Python Path to Environment Variables (Optional)

Working with Python Python Code Execution:


Python’s traditional runtime execution model: Source code you type is translated to byte code, which is then run by
the Python Virtual Machine (PVM). Your code is automatically compiled, but then it is interpreted.
Source Byte code Runtime
Source code extension is .py

PVM
m.py m.pyc

Byte code extension is .pyc (Compiled python code)

There are two modes for using the Python interpreter:


Interactive Mode
Script Mode

5
Running Python in interactive mode:
Without passing python script file to the interpreter, directly execute code to Python prompt. Once you’re inside
the python interpreter, then you can start.
>>> print("hello world") hello world
# Relevant output is displayed on subsequent lines without the >>> symbol
>>> x=[0,1,2]
# Quantities stored in memory are not displayed by default.
>>> x
#If a quantity is stored in memory, typing its name will display it. [0, 1, 2]
>>> 2+3
5

The chevron at the beginning of the 1st line, i.e., the symbol >>> is a prompt the python interpreter uses to indicate
that it is ready. If the programmer types 2+6, the interpreter replies 8.

Data types:
The data stored in memory can be of many types. For example, a student roll number is stored as a numeric value
and his or her address is stored as alphanumeric characters. Python has various standard data types that are used to
define the operations possible on them and the storage method for each of them.
Int:
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
>>> print(24656354687654+2) 24656354687656
>>> a=10
>>> print(a) 10

# To verify the type of any object in Python, use the type() function:
>>> type(10)
<class 'int'>
>>> a=11
>>> print(type(a))
<class 'int'>
Float:
Float, or "floating point number" is a number, positive or negative, containing one or more decimals.
Float can also be scientific numbers with an "e" to indicate the power of 10.
>>> y=2.8
>>> y 2.8
>>> y=2.8
>>> print(type(y))
<class 'float'>
6
>>> type(.4)
<class 'float'>
>>> 2.
2.0

Boolean:
Objects of Boolean type may have one of two values, True or False:
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>

String:

1. Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python
allows for either pairs of single or double quotes.
'hello' is the same as "hello".
Strings can be output to screen using the print function. For example: print("hello").
>>> print("TECHIN IT college") TECHIN IT college
>>> type("TECHIN IT college")
<class 'str'>

7
>>> print('TECHIN IT college') TECHIN IT college
>>> " "
''

Escape Usual Interpretation of Character(s) After Backslash


Sequence “Escaped” Interpretation
\' Terminates string with single quote opening delimiter Literal single quote (') character
\" Terminates string with double quote opening delimiter Literal double quote (") character
\newline Terminates input line Newline is ignored
\\ Introduces escape sequence Literal backslash (\) character

In Python (and almost all other common computer languages), a tab character can be specified by the escape
sequence \t:
>>> print("a\tb") a b
List:
It is a general purpose most widely used in data structures
List is a collection which is ordered and changeable and allows duplicate members. (Grow and shrink as
needed, sequence type, sortable).
To use a list, you must declare it first. Do this using square brackets and separate values with commas.
We can construct / create list in many ways. Ex:
>>> list1=[1,2,3,'A','B',7,8,[10,11]]
>>> print(list1)
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]

8
>>> x=list()
>>> x []

>>> tuple1=(1,2,3,4)
>>> x=list(tuple1)
>>> x
[1, 2, 3, 4]
Variables:
Variables are nothing but reserved memory locations to store values. This means that when you create a variable
you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the
reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals or
characters in these variables.
Rules for Python variables:
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE are three different variables)
Assigning Values to Variables:
Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically
when you assign a value to a variable. The equal sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is
the value stored in the variable.

9
For example −
a= 100 # An integer assignment b = 1000.0 # A floating point
c = "John" # A string print (a)
print (b) print (c)
This produces the following result −
100
1000.0
John
Multiple Assignment:
Python allows you to assign a single value to several variables simultaneously. For example :
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned to the same memory
location. You can also assign multiple objects to multiple variables.
For example −
a,b,c = 1,2,"TECHIN IT“
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string object
with the value "john" is assigned to the variable c.
Output Variables:
The Python print statement is often used to output variables.
Variables do not need to be declared with any particular type and can even change type after they have been set.

10
Expressions:
An expression is a combination of values, variables, and operators. An expression is evaluated using assignment
operator.
Examples: Y=x + 17
>>> x=10
>>> z=x+20
>>> z 30

>>> x=10
>>> y=20
>>> c=x+y
>>> c 30
A value all by itself is a simple expression, and so is a variable.
>>> y=20
>>> y 20
Python also defines expressions only contain identifiers, literals, and operators. So,
Identifiers: Any name that is used to define a class, function, variable module, or object is an identifier.
Literals: These are language-independent terms in Python and should exist independently in any programming
language. In Python, there are the string literals, byte literals, integer literals, floating point literals, and imaginary
literals.
Operators: In Python you can implement the following operations using the corresponding tokens.

11
Operator Token

Add +

Subtract -

Multiply *

Integer Division /

Remainder %

Binary left shift <<

Binary right shift >>

And &

Or \

Less than <

Greater than >

Less than or equal to <=

Greater than or equal to >=

Check equality ==

Check not equal !=

12
Comments:
Single-line comments begins with a hash(#) symbol and is useful in mentioning that the whole line should be
considered as a comment until the end of line.
A Multi line comment is useful when we need to comment on many lines. In python, triple double quote(“ “ “)
and single quote(‘ ‘ ‘)are used for multi-line commenting.
Example:

Output:
C:/Users/TECHIN IT/AppData/Local/Programs/Python/Python38-32/pyyy/comm.py 30

13
Modules:
Modules: Python module can be defined as a python program file which contains a python code including python
functions, class, or variables. In other words, we can say that our python code file saved with the extension (.py) is
treated as the module. We may have a runnable code inside the python module. A module in Python provides us
the flexibility to organize the code in a logical way. To use the functionality of one module into another, we must
have to import the specific module.
Syntax:
import <module-name>
Every module has its own functions, those can be accessed with . (dot)
Note: In python we have help ()
Enter the name of any module, keyword, or topic to get help on writing Python programs and using Python
modules. To quit this help utility and return to the interpreter, just type "quit".
Some of the modules like os, date, and calendar so on……
>>> import sys
>>> print(sys.version)
3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)]
>>> print(sys.version_info)
sys.version_info(major=3, minor=8, micro=0, releaselevel='final', serial=0)
>>> print(calendar.month(2021,5))

>>> print(calendar.isleap(2020)) True


>>> print(calendar.isleap(2017)) False

14
Functions:

Functions and its use: Function is a group of related statements that perform a specific task. Functions help break
our program into smaller and modular chunks. As our program grows larger and larger, functions make it more
organized and manageable. It avoids repetition and makes code reusable.

Basically, we can divide functions into the following two types:

Built-in functions - Functions that are built into Python. Ex: abs(),all().ascii(),bool()………so on….
integer = -20

print('Absolute value of -20 is:', abs(integer))

Output:

Absolute value of -20 is: 20


User-defined functions - Functions defined by the users themselves. def add_numbers(x,y):
sum = x + y return sum

print("The sum is", add_numbers(5, 20))

Output:

The sum is 25

Flow of Execution:
The order in which statements are executed is called the flow of execution
Execution always begins at the first statement of the program.
Statements are executed one at a time, in order, from top to bottom.
Function definitions do not alter the flow of execution of the program, but remember that statements inside the
function are not executed until the function is called.
Function calls are like a bypass in the flow of execution. Instead of going to the next statement, the flow jumps to
the first line of the called function, executes all the statements there, and then comes back to pick up where it left
off.

15
Note: When you read a program, don’t read from top to bottom. Instead, follow the flow of execution. This means
that you will read the def statements as you are scanning from top to bottom, but you should skip the statements of
the function definition until you reach a point where that function is called.
Example:
#example for flow of execution
print("welcome") for x in range(3):
print(x)
print("Good morning college")
Output:
C:/Users/TECHIN IT/AppData/Local/Programs/Python/Python38-32/pyyy/flowof.py welcome
0
1
2
Good morning college
The flow/order of execution is: 2,3,4,3,4,3,4,5

16
Output:
C:/Users/TECHIN IT/AppData/Local/Programs/Python/Python38-32/pyyy/flowof.py hi
hello
Good morning TECHIN IT
done!
The flow/order of execution is: 2,5,6,7,2,3,4,7,8

Parameters and arguments:

Parameters are passed during the definition of function while Arguments are passed during the function call.

Example:
#here a and b are parameters

def add(a,b): #//function definition return a+b

#12 and 13 are arguments #function call result=add(12,13) print(result)

Output:

C:/Users/TECHIN IT/AppData/Local/Programs/Python/Python38-32/pyyy/paraarg.py 25
There are three types of Python function arguments using which we can call a function.

Default Arguments
Keyword Arguments
Variable-length Arguments

Syntax:
def functionname():

17
statements
.
.
.
functionname()

Function definition consists of following components:

Keyword def indicates the start of function header.


A function name to uniquely identify it. Function naming follows the same rules of writing identifiers in Python.
Parameters (arguments) through which we pass values to a function. They are optional.
A colon (:) to mark the end of function header.
Optional documentation string (docstring) to describe what the function does.
One or more valid python statements that make up the function body. Statements must have same indentation
level (usually 4 spaces).
An optional return statement to return a value from the function.

Example:
Syntax:
def function name(parameters):

#function body(statements)

Return expression

Ex: def add():


print(“welcome to function”)

18
The return statement is used to exit a function and go back to the place from where it was called. This statement
can contain expression which gets evaluated and the value is returned. If there is no expression in the statement or
the return statement itself is not present inside a function, then the function will return the None object.

19
# Passing Arguments

Syntax:
def function_name(parameter1:data_type,paramete2:data_type…):
Body of the function
Return expression

Ex:
def add(num1:int,num2:int):
#add two numbers
num3=num1+num2
Return num3

#drive code
ans=add(5,15)
#Keyword Arguments
When we call a function with some values, these values get assigned to the arguments according to their
position.
Python allows functions to be called using keyword arguments. When we call functions in this way, the order
(position) of the arguments can be changed.
In this arguments are assigned based on the name of arguments
Ex. def display_info(first_name,last_name):
print(“firstname:”,first_name)
print(“lastname:”,last_name)
display_info(last_name=’mohammad’,first_name=’majed’)

#function with arbitary arguments

def find_sum(*num):
result=0
for i in num:
result=result+i
return result
#function call with 3 args
add_result=find_sum(1,2,3)
print("sum=",add_result)
#function call with 2 args
add_result1=find_sum(4,9)
print("sum two args",add_result1)

o/p;
sum=6
sum=13

20
Python Recursive Function
In Python, we know that a function can call other functions. It is even possible for the function to call itself. These
types of construct are termed as recursive functions.
The following image shows the working of a recursive function called recurse.

3!=3*2*1=6

Factorial of given number

def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""

if x == 1:
return 1
else:
return (x *factorial(x-1))

num = int(input("enter a number to find factorial"))

print("The factorial of", num, "is", factorial(num))

Output
The factorial of 3 is 6
factorial(3) # 1st call with 3
3 * factorial(2) # 2nd call with 2
3 * 2 * factorial(1) # 3rd call with 1
3*2*1 # return from 3rd call as number=1
3*2 # return from 2nd call
6 # return from 1st call

21
Lambda function:

In python lambda is a special type of function without function name


Syntax:
lambda argument(s) : expression

Here arguments -any value passed to the lambda function


Expression- executed and returned

Ex.
greet =lambda : print(‘hello world’)

#call the lambda


greet()

Variable scope in functions:


1. Local scope
2.Global scope
1. Local scope :A variable created inside a function belongs to the local scope of that function,and can only be used
inside that function.

Ex. def my_fun() :


X=300
print(x)
my _fun()

print(x)
def my_fun1():
x=400
print(x)
my_fun1()

2.Global scope:
A variable created in the main body of the python code is a global variable and belongs to the global scope

*global variables are available from within any scope,global and local

Ex. x=300 # global varible


def myfun() :
y=400 # local variable
print(x)
print(y)
myfun()
22
print(x)
print(y)#error y not defined.
Note:if global and local variables have same name then use global keyboard to utilise as global scope.
Ex.X=300 # global varible
def myfun() :
X=400 # local variable
print(global x)
print(x)
myfun()
300
400

Conditional statements:

Based on a particular condition the block of statements will be executed

If else
Nested if else
Elif

1.If else

Syntax:

If condition:
Do this(block of statements)
Else:
Do this(block of statements)

ex:water_level=50
If water_level>=80:
print(“drain water”)
23
Else:
print(“continue”)

var_n=int(input(“enter a no to check whether given no is even or odd”))


If var_n%2==0:
print(“given no is even”)
Else:
print(“given no is odd”)

2Nested if else

Syntax:

If condition1:
If another condition2:
Do this.block1
Else:
Do this…..block2
Else:
Do this…..block3

If condition 1 and 2 both are true then block1 will be executed


If condition 1 is true but condition 2 is false then block 2 will be executed
If condition 1 is false then block3 will be excecuted.

3.ELIF:

24
If condition1:

Block1
Elif condition2:
Block2
Else
block3
Looping statements:

Looping statements executes block of statements no of times until condition becomes false.
Python supports 3 types loop statements:
25
1.while loop
2.for loop
3.nested loop
1.while loop:
While loop executes block of statements based on condition it will execute statements until condition becomes falls

Syntax:
while <condition>:

{blok of statements }

Ex.counter=0
While counter<10

counter=counter+3

print(“print loop”)

For loop:
For loop used to iterate block of statement

Through a list,tuple,dictionary other objects of python

26
Syntax:
For variable in collection:

{code block }
ex.
To print square of given list values.

numbers=[4,2,6,7,3,5,8,10,6,1,9,2]

square=0
#variable to store the square of the no

#creating an empty list


squares=[]

#creating a for loop

27
For i in numbers:
square=i**2
squares.append(square)
Print("this is square value is",squares)
# append function syntax:
list or tuple or dictionary name.append(variable)

o/p;
This is square value is [16]
This is square value is [16,4]
This is square value is [16,4,]
This is square value is [16,4,36]

#append function adds a list value


Write a python programme to print n even numbers using while loop?

n=int(input(“enter n value”))
i=0
While i<=n:
If i%2==0:
print(“even no is”,i)
i+=2
Output:
Enter n value 100
Even no is 0
Even no is 2
Even no is 4
Even no is 6
Even no is 8
Even no is 10
Even no is 12

Write a python programme to print n even numbers using for loop?

n=int(input(“enter n value”))

For i in range(n):
If i%2==0:
print(i)

Output:
0
2
4
6
8
10

28
#range(start,stop,step)
#range(0,10,1)

Write a python programme to print squares of n even numbers? While loop

n=int(input(“enter n value”))
i=2
While i<=n:
If i%2==0:
j=i**2
print(“even number square is”,j)

i+=2
Output:
Even number square is 4
Even number square is 16
Even number square is 36
Even number square is 64
Even number square is 100
Even number square is 144
Even number square is 196
Write a python programme to print squares of n even numbers? for loop.

29
Break and continue:
In Python, break and continue statements can alter the flow of a normal loop. Sometimes we wish to terminate the
current iteration or even the whole loop without checking test expression. The break and continue statements are
used in these cases.

Break:

The break statement terminates the loop containing it and control of the program flows to the statement
immediately after the body of the loop. If break statement is inside a nested loop (loop inside another loop), break
will terminate the innermost loop.

Flowchart:

The following shows the working of break statement in for and while loop:
for var in sequence:
# code inside for loop If condition:
break (if break condition satisfies it jumps to outside loop) # code inside for loop
# code outside for loop

30
while test expression
# code inside while loop If condition:
break (if break condition satisfies it jumps to outside loop) # code inside while loop
# code outside while loop

Example:
for val in "TECHIN IT COLLEGE": if val == " ":
break print(val)

print("The end")

Output:
MRCET
The end

# Program to display all the elements before number 88

for num in [11, 9, 88, 10, 90, 3, 19]:


print(num) if(num==88):
print("The number 88 is found") print("Terminating the loop") break

Output:
11
9
88
The number 88 is found

31
Terminating the loop

#
for letter in "Python": # First Example if letter == "h":
break
print("Current Letter :", letter )

Output:
C:/Users/TECHIN IT/AppData/Local/Programs/Python/Python38-32/pyyy/br.py = Current Letter : P
Current Letter : y Current Letter : t Continue:
The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not
terminate but continues on with the next iteration.
Flowchart:

The following shows the working of break statement in for and while loop:

32
for var in sequence:
# code inside for loop If condition:
continue (if break condition satisfies it jumps to outside loop) # code inside for loop
# code outside for loop

while test expression


# code inside while loop If condition:
continue(if break condition satisfies it jumps to outside loop) # code inside while loop
# code outside while loop

Example:
# Program to show the use of continue statement inside loops

for val in "string": if val == "i": continue


print(val) print("The end") Output:
C:/Users/TECHIN IT/AppData/Local/Programs/Python/Python38-32/pyyy/cont.py s
trng
The end

# program to display only odd numbers for num in [20, 11, 9, 66, 4, 89, 44]:

33
# Skipping the iteration when number is even if num%2 == 0:
continue
# This statement will be skipped for all even numbers print(num)

Output:

C:/Users/TECHIN IT/AppData/Local/Programs/Python/Python38-32/pyyy/cont2.py 11
9
89

#
for letter in "Python": # First Example if letter == "h":
continue
print("Current Letter :", letter) Output:

C:/Users/TECHIN IT/AppData/Local/Programs/Python/Python38-32/pyyy/con1.py Current Letter : P


Current Letter : y Current Letter : t Current Letter : o Current Letter : n

Pass:

In Python programming, pass is a null statement. The difference between a comment and pass
statement in Python is that, while the interpreter ignores a comment entirely, pass is not ignored.
pass is just a placeholder for functionality to be added later.

Example:
sequence = {'p', 'a', 's', 's'} for val in sequence:
pass

Output:

C:/Users/TECHIN IT/AppData/Local/Programs/Python/Python38-32/pyyy/f1.y.py

34
>>>

Similarily we can also write,

def f(arg): pass # a function that does nothing (yet) class C: pass # a class with no methods (yet)
String module:

This module contains a number of functions to process standard Python strings. In recent versions, most
functions are available as string methods as well.

It’s a built-in module and we have to import it before using any of its constants and classes Syntax: import string
Note:
help(string) --- gives the information about all the variables ,functions, attributes and classes to be used in string
module.

Example:
import string print(string.ascii_letters) print(string.ascii_lowercase) print(string.ascii_uppercase) print(string.digits)
print(string.hexdigits) print(string.whitespace) print(string.punctuation)

Output:
C:/Users/TECHIN IT/AppData/Local/Programs/Python/Python38-32/pyyy/strrmodl.py
=========================================
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
0123456789abcdefABCDEF
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

Python arrays:
Array is a container which can hold a fix number of items and these items should be of the same type. Most of the
data structures make use of arrays to implement their algorithms. Following are the important terms to understand
the concept of Array.

Element− Each item stored in an array is called an element.


Index − Each location of an element in an array has a numerical index, which is used to identify the element.

Array Representation
Arrays can be declared in various ways in different languages. Below is an illustration.
Elements

Int array [10] = {10, 20, 30, 40, 50, 60, 70, 80, 85, 90}

Type Name Size Index 0

As per the above illustration, following are the important points to be considered.
Index starts with 0.
Array length is 10 which means it can store 10 elements.
35
Each element can be accessed via its index. For example, we can fetch an element at index 6 as 70

Basic Operations

Following are the basic operations supported by an array.


Traverse − print all the array elements one by one.
Insertion − Adds an element at the given index.
Deletion − Deletes an element at the given index.
Search − Searches an element using the given index or by the value.
Update − Updates an element at the given index.
Array is created in Python by importing array module to the python program. Then the array is declared as
shown below.
from array import * arrayName=array(typecode, [initializers])
Typecode are the codes that are used to define the type of value the array will hold. Some common typecodes
used are:

Typecode Value

b Represents signed integer of size 1 byte/td>

B Represents unsigned integer of size 1 byte

36
c Represents character of size 1 byte

i Represents signed integer of size 2 bytes

I Represents unsigned integer of size 2 bytes

f Represents floating point of size 4 bytes

d Represents floating point of size 8 bytes

Creating an array:
from array import *
array1 = array('i', [10,20,30,40,50]) for x in array1:
print(x)

Output:
>>>
RESTART: C:/Users/TECHIN IT/AppData/Local/Programs/Python/Python38-32/arr.py 10
20
30
40
50

Access the elements of an Array:


Accessing Array Element
We can access each element of an array using the index of the element. from array import *
array1 = array('i', [10,20,30,40,50])
print (array1[0]) print (array1[2])

37
Output:
RESTART: C:/Users/TECHIN IT/AppData/Local/Programs/Python/Python38-32/pyyy/arr2.py 10
30

Array methods:
Python has a set of built-in methods that you can use on lists/arrays.

Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the first item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

38
LISTS, TUPLES, DICTIONARIES
Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list parameters, list
comprehension; Tuples: tuple assignment, tuple as return value, tuple comprehension; Dictionaries: operations and
methods, comprehension;
Lists, Tuples, Dictionaries:
List:
It is a general purpose most widely used in data structures
List is a collection which is ordered and changeable and allows duplicate members. (Grow and shrink as
needed, sequence type, sortable).
To use a list, you must declare it first. Do this using square brackets and separate values with commas.
We can construct / create list in many ways. Ex:
>>> list1=[1,2,3,'A','B',7,8,[10,11]]
>>> print(list1)
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]

>>> x=list()
>>> x []

>>> tuple1=(1,2,3,4)
>>> x=list(tuple1)
>>> x
[1, 2, 3, 4]

39
List operations:
These operations includeindexing, slicing,adding,multiplying, and checking for membership

Basic List Operations:

Lists respond to the + and * operators much like strings; they mean concatenation and repetition here too,
except that the result is a new list, not a string.

Python Expression Results Description

len([1, 2, 3]) 3 Length

[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation

['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition

3 in [1, 2, 3] True Membership

for x in [1, 2, 3]: print x, 123 Iteration

Indexing, Slicing, and Matrixes

Because lists are sequences, indexing and slicing work the same way for lists as they do for strings.
Assuming following input −
L = ['TECHIN IT', 'college', 'TECHIN IT!']

Python Expression Results Description

L[2] TECHIN IT Offsets start at zero

40
L[-2] college Negative: count from the right

L[1:] ['college', 'TECHIN IT!'] Slicing fetches sections

Aliasing:
An alias is a second name for a piece of data, often easier (and more useful) than making a copy.
If the data is immutable, aliases don’t matter because the data can’t change.
But if data can change, aliases can result in lot of hard – to – find bugs.
Aliasing happens whenever one variable’s value is assigned to another variable.

For ex:
a = [81, 82, 83]

Tuples:
A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets.
Supports all operations for sequences.
Immutable, but member objects may be mutable.
If the contents of a list shouldn’t change, use a tuple to prevent items from
accidently being added, changed, or deleted.
Tuples are more efficient than list due to python’s implementation.

We can construct tuple in many ways: X=() #no item tuple


X=(1,2,3)
X=tuple(list1) X=1,2,3,4

Example:
>>> x=(1,2,3)
>>> print(x) (1, 2, 3)
>>> x (1, 2, 3)

>>> x=()
>>> x ()

>>> x=[4,5,66,9]
>>> y=tuple(x)
>>> y
(4, 5, 66, 9)

>>> x=1,2,3,4
>>> x
(1, 2, 3, 4)

41
Some of the operations of tuple are:
Access tuple items
Change tuple items
Loop through a tuple
Count()
Index()
Length()

42
Access tuple items: Access tuple items by referring to the index number, inside square brackets
>>> x=('a','b','c','g')
>>> print(x[2]) c
Change tuple items: Once a tuple is created, you cannot change its values. Tuples are unchangeable.

>>> x=(2,5,7,'4',8)
>>> x[1]=10
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module> x[1]=10
TypeError: 'tuple' object does not support item assignment
>>> x
(2, 5, 7, '4', 8) # the value is still the same

Loop through a tuple: We can loop the values of tuple using for loop
>>> x=4,5,6,7,2,'aa'
>>> for i in x:
print(i)

4
5
6
7
2
aa

Count (): Returns the number of times a specified value occurs in a tuple
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> x.count(2) 4

Index (): Searches the tuple for a specified value and returns the position of where it was found

43
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> x.index(2) 1

(Or)

>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=x.index(2)
>>> print(y) 1

Length (): To know the number of items or values present in a tuple, we use len().
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=len(x)
>>> print(y) 12

Tuple Assignment
Python has tuple assignment feature which enables you to assign more than one variable at a time. In here, we have
assigned tuple 1 with the college information like college name, year, etc. and another tuple 2 with the values in it
like number (1, 2, 3… 7).
For Example, Here is the code,
>>> tup1 = ('TECHIN IT', 'eng college','2004','cse', 'it','csit');
>>> tup2 = (1,2,3,4,5,6,7);
>>> print(tup1[0])
TECHIN IT
>>> print(tup2[1:4])
(2, 3, 4)
Tuple 1 includes list of information of TECHIN IT Tuple 2 includes list of numbers in it
Dictionaries:

A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with
curly brackets, and they have keys and values.
Key-value pairs
Unordered
We can construct or create dictionary like:
X={1:’A’,2:’B’,3:’c’}
X=dict([(‘a’,3) (‘b’,4)] X=dict(‘A’=1,’B’ =2)

Example:
>>> dict1 = {"brand":"TECHIN IT","model":"college","year":2004}
>>> dict1
{'brand': 'TECHIN IT', 'model': 'college', 'year': 2004}

44
Classes and objects:
OOP:
Object oriented programming
Object:
Real world entity of a class
Instance of a class

It combines attributes and methods into single unit

Attribute: variables
🚗 Is an object

Attributes:
Speed=0
Fuel=6

Methods:
Drive()
Speed ()
Cam()
Gps()
Creating a class:
Syntax:
Class <classname>:
Attributes
Methods
Creating object:
Syntax:

Object name=class name()


Class:

Class is Blue print of an object


Class comes into reality when only object created.

How to access class variables and methods.

Ex
class CarBluePrint
Speed=0
Fuel=5
def Drive()
Print("drive within limit")
def Speed()
Print("don't over speed")
#object =class name()

Car=CarBluePrint() 45
Car.speed=40
Car.fuel =5
Car.Drive()
Car.speed()

Programme: create turtle 🐢 with coral color and move 100 and draw same color line.

from turtle import Turtle,Screen


timmy=Turtle()
Print(timmy)
Timmy.shape("turtle")
Timmy.color("coral")
Timmy.forward(100)
My_screen=Screen()
Print(my_screen.canvheight)
My_Screen.exitonclick()

06/06/2023
Constructor:

In python constructor is a special type of method executed at the time of object creation.

Class CarBluePrint:
Attributes
Methods
car=CarBluePrint()#constuctor

_ _init_ _ method:

1.For every class defination init method exist for variable declaration.
2.When ever an object created for a class init will be executed.
3.It is a default initiavilzer method
For every class
4.It is specialy designed for attributes initialisation
Syntax.

_ _init_ _(self,params)

Self is a default object of init

Params means arguments of init

Ex.
class CarBluePrint
def _init_(self,seats,fuel)
self.seats=5
self.fuel=6
Resources={water:water, coffee:cofee,milk:milk}

Inheritance : 46
Inheritance is a core concept of python which allow to derive super class properties and
methods to subclass

It very useful for reusability

Syntax.
class Subclass name (super class name):

Ex
Class Animal:
def _ _init_ _(self):
Self.num_eyes=2
def breath(self):

Print("inhele,exhile")

class Fish(Animal):
def _ _init_ _(self): super._ _init_ _(self):
Super.breath()
…..,
…..
08/06/23

Python Inheritance
Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides code
reusability to the program because we can use an existing class to create a new class instead
of creating it from scratch.

In inheritance, the child class acquires the properties and can access all the data members and
functions defined in the parent class. A child class can also provide its specific
implementation to the functions of the parent class. In this section of the tutorial, we will
discuss inheritance in detail.

In python, a derived class can inherit base class by just mentioning the base in the bracket
after the derived class name. Consider the following syntax to inherit a base class into the
derived class.

Python Inheritance
Syntax

class derived-class(base class):


<class-suite>

A class can inherit multiple classes by mentioning all of them inside the bracket. Consider the
following syntax.

Syntax
class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
<class - suite>
Example 1 47
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak()
ADVERTISEMENT
ADVERTISEMENT
Output:

dog barking
Animal Speaking

Python Multi-Level inheritance:

Multi-Level inheritance is possible in python like other object-oriented languages. Multi-


level inheritance is archived when a derived class inherits another derived class. There is no
limit on the number of levels up to which, the multi-level inheritance is archived in python.

Base class
!
Child class1
!
Child class2
.
.

Python Inheritance
The syntax of multi-level inheritance is given below.

Syntax
class class1:
<class-suite>
class class2(class1):
<class suite>
class class3(class2):
<class suite>
.
.

class Animal:
def speak(self):
print("Animal Speaking")
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self): 48
print("dog barking")
#The child class Dogchild inherits another child class Dog
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
d.bark()
d.speak()
d.eat()
Output:
dog barking
Animal Speaking
Eating bread…

2.Python Multiple inheritance;

Python provides us the flexibility to inherit multiple base classes in the child class.

Python Inheritance
The syntax to perform multiple inheritance is given below.

Syntax
class Base1:
<class-suite>

class Base2:
<class-suite>
.
.
.
class BaseN:
<class-suite>

class Derived(Base1, Base2, ...... BaseN):


<class-suite>
Example
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(d.Summation(10,20))
print(d.Multiplication(10,20))
print(d.Divide(10,20))
Output: 49
30
200
0.5
The ….issubclass(sub,sup) method:
The issubclass(sub, sup) method is used to check the relationships between the specified
classes. It returns true if the first class is the subclass of the second class, and false otherwise.

Consider the following example.

Example
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(issubclass(Derived,Calculation2))
print(issubclass(Calculation1,Calculation2))
Output:

True
False

….>The isinstance (obj, class) method:

The isinstance() method is used to check the relationship between the objects and classes. It
returns true if the first parameter, i.e., obj is the instance of the second parameter, i.e., class.

Consider the following example.

Example
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(isinstance(d,Derived))
Output:

True 50
Method Overriding
We can provide some specific implementation of the parent class method in our child class.
When the parent class method is defined in the child class with some specific
implementation, then the concept is called method overriding. We may need to perform
method overriding in the scenario where the different definition of a parent class method is
needed in the child class.

Consider the following example to perform method overriding in python.

Example
class Animal:
def speak(self):
print("speaking")
class Dog(Animal):
def speak(self):
print("Barking")
d = Dog()
d.speak()
Output:

Barking

3.Hierarchical Inheritance:
When more than one derived class are created from a single base this type of inheritance is
called hierarchical inheritance. In this program, we have a parent (base) class and two child
(derived) classes.

Example:

# Python program to demonstrate


# Hierarchical inheritance

# Base class
class Parent:
def func1(self):
print("This function is in parent class.")

# Derived class1

class Child1(Parent): 51
def func2(self):
print("This function is in child 1.")

# Derivied class2

class Child2(Parent):
def func3(self):
print("This function is in child 2.")

# Driver's code
object1 = Child1()
object2 = Child2()
object1.func1()
object1.func2()
object2.func1()
object2.func3()
Output:

This function is in parent class.


This function is in child 1.
This function is in parent class.
This function is in child 2.
Hybrid Inheritance:
Inheritance consisting of multiple types of inheritance is called hybrid inheritance.

Example:

# Python program to demonstrate


# hybrid inheritance

class School:
def func1(self):
print("This function is in school.")

class Student1(School):
def func2(self):
print("This function is in student 1. ")

class Student2(School):
def func3(self):
print("This function is in student 2.")
52
class Student3(Student1, School):
def func4(self):
print("This function is in student 3.")

# Driver's code
object = Student3()
object.func1()
object.func2()
Output:

This function is in school.


This function is in student 1.

4. Hybrid Inheritance:
Inheritance consisting of multiple types of inheritance is called hybrid inheritance.

Example:

# Python program to demonstrate


# hybrid inheritance

class School:
def func1(self):
print("This function is in school.")

class Student1(School):
def func2(self):
print("This function is in student 1. ")

class Student2(School):
def func3(self):
print("This function is in student 2.")

class Student3(Student1, School): 53


def func4(self):
print("This function is in student 3.")

# Driver's code
object = Student3()
object.func1()
object.func2()
Output:

pattern, which allows you to traverse a container and access its elements. The iterator pattern
decouples the iteration algorithms from container data structures.

Iterators take responsibility for two main actions:

Returning the data from a stream or container one item at a time


Keeping track of the current and visited items
In summary, an iterator will yield each item or value from a collection or a stream of data
while doing all the internal bookkeeping required to maintain the state of the iteration
process.

Polymorphism:

Polymorphism means poly is Greek word it means many morphism means forms

Same function name with different signature

len() function.
To calculate length of given variable

Polymorphism in built in function:

len("india")
5

len([10,12,6,7])
4
len() same function but using with different argument type .

Polymorphism in user difined functions:

Ex def add(a,b,c)
Return a+b+c

X=add(10,20)
Y=add(4,5,10)

Same function but different arguments


54
Polymorphism in classes:
Let us take two classes with same function name but the logic is different.

class India():
def capital(self):
print("New Delhi is the capital of India.")

def language(self):
print("Hindi is the most widely spoken language of India.")

def type(self):
print("India is a developing country.")

class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")

def language(self):
print("English is the primary language of USA.")

def type(self):
print("USA is a developed country.")

obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
country.capital()
country.language()
country.type()
Output
New Delhi is the capital of India.
Hindi is the most widely spoken language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.
Polymorphism with Inheritance:

In Python, Polymorphism lets us define methods in the child class that have the same name as
the methods in the parent class. In inheritance, the child class inherits the methods from the
parent class. However, it is possible to modify a method in a child class that it has inherited
from the parent class. This is particularly useful in cases where the method inherited from the
parent class doesn’t quite fit the child class. In such cases, we re-implement the method in the
child class. This process of re-implementing a method in the child class is known as Method
Overriding.

class Bird:
def intro(self):
print("There are many types of birds.") 55
def flight(self):
print("Most of the birds can fly but some cannot.")

class sparrow(Bird):
def flight(self):
print("Sparrows can fly.")

class ostrich(Bird):
def flight(self):
print("Ostriches cannot fly.")

obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()

obj_bird.intro()
obj_bird.flight()

obj_spr.intro()
obj_spr.flight()

obj_ost.intro()
obj_ost.flight()
Output
There are many types of birds.
Most of the birds can fly but some cannot.
There are many types of birds.
Sparrows can fly.
There are many types of birds.
Ostriches cannot fly.

class India():
def capital(self):
print("New Delhi is the capital of India.")

def language(self):
print("Hindi is the most widely spoken language of India.")

def type(self):
print("India is a developing country.")

class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")

def language(self):
print("English is the primary language of USA.")56
def type(self):
print("USA is a developed country.")

obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
country.capital()
country.language()
country.type()
Output
New Delhi is the capital of India.
Hindi is the most widely spoken language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.

Polymorphism with Inheritance:

In Python, Polymorphism lets us define methods in the child class that have the same name as
the methods in the parent class. In inheritance, the child class inherits the methods from the
parent class. However, it is possible to modify a method in a child class that it has inherited
from the parent class. This is particularly useful in cases where the method inherited from the
parent class doesn’t quite fit the child class. In such cases, we re-implement the method in the
child class. This process of re-implementing a method in the child class is known as Method
Overriding.

class Bird:
def intro(self):
print("There are many types of birds.")

def flight(self):
print("Most of the birds can fly but some cannot.")

class sparrow(Bird):
def flight(self): 57
print("Sparrows can fly.")
class ostrich(Bird):
def flight(self):
print("Ostriches cannot fly.")

obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()

obj_bird.intro()
obj_bird.flight()

obj_spr.intro()
obj_spr.flight()

obj_ost.intro()
obj_ost.flight()

Python Modules:or packages

Python Modules
In this tutorial, you will learn to create and import custom modules in Python. Also, you will
find different techniques to import and use custom and built-in modules in Python.

As our program grows bigger, it may contain many lines of code. Instead of putting
everything in a single file, we can use modules to separate codes in separate files as per their
functionality. This makes our code organized and easier to maintain.

Module is a file that contains code to perform a specific task. A module may contain
variables, functions, classes etc. Let's see an example,

Let us create a module. Type the following and save it as addition.py.

# Python Module addition

def add(a, b):

result = a + b
return result
Here, we have defined a function add() inside a module . The function takes in two numbers
and returns their sum.

Import modules in Python


We can import the definitions inside a module to another module or the interactive interpreter
in Python.

We use the import keyword to do this. To import our previously defined module example, we
type the following in the Python prompt.
58
Using the module name we can access the function using the dot . operator. For example:

addition.add(4,5) # returns 9
Note:

Import Python Standard Library Modules


The Python standard library contains well over 200 modules. We can import a module
according to our needs.

Suppose we want to get the value of pi, first we import the math module and use math.pi. For
example,

# import standard math module


import math

# use math.pi to get value of pi


print("The value of pi is", math.pi)
Run Code
Output

The value of pi is 3.141592653589793


Python import with Renaming:
In Python, we can also import a module by renaming it. For example,

# import module by renaming it


import math as m

print(m.pi)

# Output: 3.141592653589793
Run Code
Here, We have renamed the math module as m. This can save us typing time in some cases.

Note that the name math is not recognized in our scope. Hence, math.pi is invalid, and m.pi is
the correct implementation.

Python from...import statement:


We can import specific names from a module without importing the module as a whole. For
example,

# import only pi from math module


from math import pi

print(pi)

# Output: 3.141592653589793
Run Code
Here, we imported only the pi attribute from the math module.
59
Import all names
In Python, we can import all names(definitions) from a module using the following construct:

# import all names from the standard module math


from math import *

print("The value of pi is", pi)


Run Code

Importing everything with the asterisk (*) symbol is not a good programming practice. This
can lead to duplicate definitions for an identifier.

Python Datetime module:

Python datetime
In this tutorial, we will learn to manipulate date and time in Python with the help of
examples.

Python has a module named datetime to work with dates and times.

It provides a variety of classes for representing and manipulating dates and times, as well as
for formatting and parsing dates and times in a variety of formats.

Example 1: Get Current Date and Time


import datetime

# get the current date and time


now = datetime.datetime.now()

print(now)
Run Code
Output

2022-12-27 08:26:49.219717
Here, we have imported the datetime module using the import datetime statement.

One of the classes defined in the datetime module is the datetime class.

We then used the now() method to create a datetime object containing the current local date
and time.

Example 2: Get Current Date


import datetime

# get current date


current_date = datetime.date.today()

print(current_date)
Run Code
Output 60
2022-12-27
In the above example, we have used the today() method defined in the date class to get a date
object containing the current local date.

Attributes of datetime Module


We can use the dir() function to get a list containing all attributes of a module.

import datetime

print(dir(datetime))
Run Code
Output

['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__',


'__name__', '__package__', '__spec__', '_divide_and_round', 'date', 'datetime',
'datetime_CAPI', 'time', 'timedelta', 'timezone', 'tzinfo']
Programiz

Python has a module named datetime to work with dates and times.

It provides a variety of classes for representing and manipulating dates and times, as well as
for formatting and parsing dates and times in a variety of formats.

datetime.datetime - represents a single point in time, including a date and a time.


datetime.date - represents a date (year, month, and day) without a time.
datetime.time - represents a time (hour, minute, second, and microsecond) without a date.
datetime.timedelta - represents a duration, which can be used to perform arithmetic with
datetime objects.
Python datetime.date Class
In Python, we can instantiate date objects from the date class. A date object represents a date
(year, month and day).

Example 3: Date object to represent a date


import datetime

d = datetime.date(2022, 12, 25)


print(d)
Run Code
Output

2022-12-25
Here, date() in the above example is a constructor of the date class. The constructor takes
three arguments: year, month and day.

Import Only date Class


We can only import the date class from the datetime module. For example,
61
from datetime import date
d = date(2022, 12, 25)
print(d)
Run Code
Output

2022-12-25
Here, from datetime import date only imports the date class from the datetime module.

Example 4: Get current date using today()


We can create a date object containing the current date by using the class method named
today(). For example,

from datetime import date

# today() to get current date


todays_date = date.today()

print("Today's date =", todays_date)


Run Code
Output

Today's date = 2022-12-27


Example 5: Get date from a timestamp
We can also create date objects from a timestamp.

A Unix timestamp is the number of seconds between a particular date and January 1, 1970 at
UTC. You can convert a timestamp to date using the fromtimestamp() method.

from datetime import date

timestamp = date.fromtimestamp(1326244364)
print("Date =", timestamp)
Run Code
Output

Date = 2012-01-11
Example 6: Print today's year, month and day
We can get year, month, day, day of the week etc. from the date object easily. For example,

from datetime import date

# date object of today's date


today = date.today()

print("Current year:", today.year)


print("Current month:", today.month)
print("Current day:", today.day)
Run Code 62
Output
Current year: 2022
Current month: 12
Current day: 27
Python datetime.time Class
A time object instantiated from the time class represents the local time.

`
Python strftime() Method
The strftime() method is defined under classes date, datetime and time. The method creates a
formatted string from a given date, datetime or time object.

Let's see an example.

from datetime import datetime

# current date and time


now = datetime.now()

t = now.strftime("%H:%M:%S")
print("Time:", t)

s1 = now.strftime("%m/%d/%Y, %H:%M:%S")
# mm/dd/YY H:M:S format
print("s1:", s1)

s2 = now.strftime("%d/%m/%Y, %H:%M:%S")
# dd/mm/YY H:M:S format
print("s2:", s2)
Run Code
Output

time: 04:34:52
s1: 12/26/2018, 04:34:52
s2: 26/12/2018, 04:34:52
Here, %Y, %m, %d, %H etc. are format codes. The strftime() method takes one or more
format codes and returns a formatted string based on it.

In the above example, t, s1 and s2 are strings.

%Y - year [0001,..., 2018, 2019,..., 9999]


%m - month [01, 02, ..., 11, 12]
%d - day [01, 02, ..., 30, 31]
%H - hour [00, 01, ..., 22, 23
%M - minute [00, 01, ..., 58, 59]
%S - second [00, 01, ..., 58, 59]
Python RegEx

A RegEx, or Regular Expression, is a sequence of63 characters that forms a search pattern.
RegEx can be used to check if a string contains the specified search pattern.
RegEx Module
Python has a built-in package called re, which can be used to work with Regular
Expressions.
Import the re module:
import re
RegEx in Python
When you have imported the re module, you can start using regular expressions:
Search the string to see if it starts with "The" and ends with "Spain":
import re

txt = "The rain in Spain"


x = re.search("^The.*Spain$", txt)
RegEx Functions
The re module offers a set of functions that allows us to search a string for a match:
Function Description

findall Returns a list containing all matches

search Returns a Match object if there is a match anywhere in the string

split Returns a list where the string has been split at each match

sub Replaces one or many matches with a string

Metacharacters
Metacharacters are characters with a special meaning:
Character Description Example

[] A set of characters "[a-m]"

\ Signals a special sequence (can also be used to escape special characters) "\d"

. Any character (except newline character) "he..o"

^ Starts with "^hello"

$ Ends with "planet$"

* Zero or more occurrences "he.*o"

+ One or more occurrences "he.+o"

? Zero or one occurrences "he.?o"

{} Exactly the specified number of occurrences "he.{2}o"

| Either or "falls|stays"

() Capture and group 64


import re

pattern = '^a...s$'
test_string = 'abyss'
result = re.match(pattern, test_string)

if result:
print("Search successful.")
else:
print("Search unsuccessful.")

output:
Search successful.

Python pip

What is pip?
pip is the standard package manager for Python. We can use pip to install additional packages
that are not available in the Python standard library. For example,

pip install numpy

If we had installed pip on our system, this command would have installed the numpy library.

How to install pip?

pip comes pre-installed on the Python versions 3.4 or older. We can check if pip is installed
by using the following command in the console:

pip –version

If pip is already available in the system, the respective pip version is displayed, like:
pip 19.3.1 from C:\Python37\lib\site-packages\pip (python 3.7)
If we are using an older version of Python or do not have pip installed for some other reason,
follow the steps as described in this link

Using pip

pip is a command-line program. After its installation, a pip command is added which can be
used with the command prompt. 65
The basic syntax of pip is:
pip <pip arguments>

Installing Packages with pip

Apart from the standard Python library, the Python community contributes to an extensive
number of packages tailored for various development frameworks, tools, and libraries.
Most of these packages are officially hosted and published to the Python Package
Index(PyPI). pip allows us to download and install these packages.

Basic Package Installation

The install command used to install packages using pip. Let's take an example:
Suppose we want to install requests, a popular HTTP library for Python. We can do it with
the help of the following command.

pip install requests

Here, we can see that the pip has been used with the install command followed by the
name of the package we want to install (requests).

Listing Installed Packages with pip

The pip list command can be used to list all the available packages in the current Python
environment.
pip list

Output
Package Version
---------- ----------
certifi 2019.11.28
chardet 3.0.4
idna 2.8
pip 19.3.1
requests 2.22.0
setuptools 45.0.0
urllib3 1.25.7
wheel 0.33.6

Python Exception Handling


In the last tutorial, we learned about Python exceptions. We know that exceptions abnormally
terminate the execution of a program.
This is why it is important to handle exceptions. In Python, we use the try...except block

Python try...except Block 66


The try...except block is used to handle exceptions in Python. Here's the syntax
of try...except block:
try:
# code that may cause exception
except:
# code to run when exception occurs
Here, we have placed the code that might generate an exception inside the try block.
Every try block is followed by an except block.
When an exception occurs, it is caught by the except block. The except block cannot be used
without the try block.
Example: Exception Handling Using try...except
try:
numerator = 10
denominator = 0

result = numerator/denominator

print(result)
except:
print("Error: Denominator cannot be 0.")

# Output: Error: Denominator cannot be 0.


Run Code
In the example, we are trying to divide a number by 0. Here, this code generates an
exception.
To handle the exception, we have put the code, result = numerator/denominator inside
the try block. Now when an exception occurs, the rest of the code inside the try block is
skipped.
The except block catches the exception and statements inside the except block are executed.

Catching Specific Exceptions in Python


For each try block, there can be zero or more except blocks. Multiple except blocks allow us
to handle each exception differently.
The argument type of each except block indicates the type of exception that can be handled
by it. For example,
try:

even_numbers = [2,4,6,8]
print(even_numbers[5])

except ZeroDivisionError:
print("Denominator cannot be 0.")

except IndexError:
print("Index Out of Bound.")

# Output: Index Out of Bound


Run Code
In this example, we have created a list named even_numbers.
Since the list index starts from 0, the last element
67of the list is at index 3. Notice the
statement,
print(even_numbers[5])
Here, we are trying to access a value to the index 5. Hence, IndexError exception occurs.
When the IndexError exception occurs in the try block,
The ZeroDivisionError exception is skipped.
The set of code inside the IndexError exception is executed.

Python try...finally
In Python, the finally block is always executed no matter whether there is an exception or not.
The finally block is optional. And, for each try block, there can be only one finally block.
Let's see an example,
try:
numerator = 10
denominator = 0

result = numerator/denominator

print(result)
except:
print("Error: Denominator cannot be 0.")

finally:
print("This is finally block.")
Run Code
Output
Error: Denominator cannot be 0.
This is finally block.

Python File I/OPython File Operation


A file is a container in computer storage devices used for storing data.
When we want to read from or write to a file, we need to open it first. When we are done, it
needs to be closed so that the resources that are tied with the file are freed.
Hence, in Python, a file operation takes place in the following order:
Open a file
Read or write (perform operation)
Close the file

Opening Files in Python


In Python, we use the open() method to open files.
To demonstrate how we open files in Python, let's suppose we have a file named test.txt with
the following content.

68
Different Modes to Open a File in Python
Mode Description

r Open a file for reading. (default)

Open a file for writing. Creates a new file if it does not exist or truncates the file if it
w
exists.

x Open a file for exclusive creation. If the file already exists, the operation fails.

Open a file for appending at the end of the file without truncating it. Creates a new file
a
if it does not exist.

t Open in text mode. (default)

b Open in binary mode.

+ Open a file for updating (reading and writing)


Here's few simple examples of how to open a file in different modes,
file1 = open("test.txt") # equivalent to 'r' or 'rt'
file1 = open("test.txt",'w') # write in text mode
file1 = open("img.bmp",'r+b') # read and write in binary mode

Reading Files in Python


After we open a file, we use the read() method to read its contents. For example,
# open a file
file1 = open("test.txt", "r")
69
# read the file
read_content = file1.read()
print(read_content)
Output
This is a test file.
Hello from the test file.

Different Modes to Open a File in Python


Mode Description

r Open a file for reading. (default)

Open a file for writing. Creates a new file if it does not exist or truncates the file if it
w
exists.

x Open a file for exclusive creation. If the file already exists, the operation fails.

Open a file for appending at the end of the file without truncating it. Creates a new file
a
if it does not exist.

t Open in text mode. (default)

b Open in binary mode.

+ Open a file for updating (reading and writing)


Here's few simple examples of how to open a file in different modes,
file1 = open("test.txt") # equivalent to 'r' or 'rt'
file1 = open("test.txt",'w') # write in text mode
file1 = open("img.bmp",'r+b') # read and write in binary mode

Reading Files in Python


After we open a file, we use the read() method to read its contents. For example,
# open a file
file1 = open("test.txt", "r")

# read the file


read_content = file1.read()
print(read_content)
Output
This is a test file.
Hello from the test file.

70
Project

71
.Python Program to Find the Largest Among Three Numbers:

Programme:

# Python program to find the largest number among the three input numbers

# change the values of num1, num2 and num3


# for a different result
num1 = float(input("enter first number\n"))
num2 = float(input("enter second number\n"))
num3 = float(input("enter third number"))

# uncomment following lines to take three numbers from user


#num1 = float(input("Enter first number: "))
#num2 = float(input("Enter second number: "))
#num3 = float(input("Enter third number: "))

if (num1 >= num2) and (num1 >= num3):


largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3

print("The largest number is", largest)

output:

enter first number


12
enter second number
456
enter third number10
The largest number is 456.0

72

You might also like