0% found this document useful (0 votes)
43 views180 pages

Python

The document outlines the regulations for a B.Sc in Computer Science (AI & DS) at Periyar University, focusing on algorithms and their characteristics, qualities, and examples. It discusses the building blocks of algorithms, including sequence, selection, and iteration, as well as the importance of functions and flowcharts in programming. Additionally, it covers pseudocode as a tool for algorithm design, emphasizing clarity and readability for both programmers and non-programmers.

Uploaded by

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

Python

The document outlines the regulations for a B.Sc in Computer Science (AI & DS) at Periyar University, focusing on algorithms and their characteristics, qualities, and examples. It discusses the building blocks of algorithms, including sequence, selection, and iteration, as well as the importance of functions and flowcharts in programming. Additionally, it covers pseudocode as a tool for algorithm design, emphasizing clarity and readability for both programmers and non-programmers.

Uploaded by

sarojinisri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

lOMoARcPSD|50662627

PY-BOOK - PERIYAR UNIVERSITY 2023 REGULATIONS


[Link] CS (AI& DS)
Essential Technologies for DataScience(Weka& Intel AI software) (Periyar University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

UNIT-I
1. Algorithms

 Algorithms are step-by-step procedures for solving a problem in a finite


number of steps
 Algorithms are often used to help computers make decisions, and in
programming
 Set of step-by-step instructions that perform a specific task or operation
 Natural language NOT programming language
 Algorithm is the sequence of steps to be performed in order to solve a
problem by the computer
 Three reasons for using algorithms are efficiency, abstraction and
reusability
 Algorithms can be expressed in many different notations, including natural
languages, pseudocode, flowcharts and programming languages
 Analysis of algorithms is the theoretical study of computer program
 The practical goal of algorithm analysis is to predict the performance of
different algorithms in order to guide program design decisions
 Most algorithms do not perform the same in all case
 Normally an algorithm’s performance varies with the data passed to it
 Typically, three cases are recognized: the best case, average case and
worst case
 Worst case analysis of algorithms is considered to be crucial to
applications such as games, finance and robotics
 O-notation, also known as Big O-notation, is the most common notation
used to express an algorithm’s performance in formal manner

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 1

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Characteristics of algorithm

 Algorithms can be written in plain simple English language so that it is


easily understandable even by non-programmers
 In the algorithm each and every instruction should be precise and
unambiguous
 The instruction in an algorithm should not be repeated infinitely
 Ensure that the algorithm will ultimately(finally) terminate
 The algorithm should be written in sequence
 The desired result should be obtained only after the algorithm
terminates

Input: An algorithm must have an input, and that input should not be zero (0)

Output: At the end, you must receive at least one output

Clear instructions: An algorithm must have thorough and clear instructions

Finiteness: An algorithm must consist of a finite number of steps, i.e., it must be


finite and should terminate

Workable: The algorithms must be simple and straightforward and should not
include any future technology or anything else. It should be executable with the
available resources

Qualities of a good algorithm


PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 2

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 Time - Lesser time required


 Memory - Less memory required
 Accuracy - Suitable or correct solution obtained
 Sequence - Must be sequence and some instruction may be repeated in
number of times or until particular condition is met

Examples of algorithm

Problem 1: Find the area of a Circle of radius r

Inputs to the algorithm

Radius r of the Circle\

Expected output

Area of the Circle

Algorithm:

Step 1: Start

Step2: Read input the Radius r of the Circle

Step3: Area ←PI*r*r // calculation of area

Step4: Print Area

Step 5: Stop

Problem2: Write an algorithm to read two numbers and find their sum

Inputs to the algorithm

First num1

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 3

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Second num2

Expected output

Sum of the two numbers

Algorithm

Step1: Start

Step2: Read\input the first num1.

Step3: Read\input the second num2.

Step4: Sum← num1+num2 // calculation of sum

Step5: Print Sum

Step6: Stop

Problem 4: Find the largest number between A and B

Inputs to the algorithm

A, B

Expected output

Largest A or B

Algorithm

Step 1: Start

Step 2:Read A, B

Step 3: If A is less than B, then

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 4

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Big=B

Small=A

Print A is largest

Else

Big=A

else

Small = B

Step 4: Write (Display) BIG, SMALL

Step 5: Stop

Problem 5: To determine student’s average grade and indicate whether


successful or fail

Step 1: Start

Step 2: Input mid-term and final

Step 3: average=(mid-term + final)/2

Step 4: if (average < 60) then

Print “FAIL”

Print “SUCCESS”

Problem 6: A algorithm to find the l rgest v lue of any three numbers

Step1: Start

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 5

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Step2: Read/input A,B and C

Step3: If (A>=B) and (A>=C) then Max=A

Step4: If (B>=A) and (B>=C) then Max=B

Step5:If (C>=A) and (C>=B) then Max=C

Step6: Print Max

Step7: End

1.1 Building blocks of algorithms

 Algorithms can be constructed from basic building blocks namely,


sequence, selection and iteration

1.1.1 Statements

 Statement is a single action in a computer


 In a computer statements might include some of the following actions

input data-information given to the program

process data-perform operation on a given input

output data-processed result

1.1.2 State

 Transition from one process to another process under specified condition


with in a time is called state

1.1.3 Control flow

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 6

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 The process of executing the individual statements in a given order is


called control flow

The control can be executed in three ways

 sequence
 selection
 iteration

Sequence

 All the instructions are executed one after another is called sequence
execution

Example

Add two numbers

Step 1: Start

Step 2: get a,b

Step 3: calculate c=a+b

Step 4: Display c

Step 5: Stop

Selection

 A selection statement causes the program control to be transferred to a


specific part of the program based upon the condition
 If the conditional test is true, one part of the program will be executed,
otherwise it will execute the other part of the program

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 7

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Example

Write an algorithm to check whether he is eligible to vote

Step 1: Start

Step 2: Get age

Step 3: if age >= 18 print “Eligible to vote”

Step 4: else print “Not eligible to vote”

Step 6: Stop

Iteration

 In some programs, certain set of statements are executed again and again
based upon conditional test. i.e. executed more than one time
 This type of execution is called looping or iteration

Example
PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 8

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Write an algorithm to print all natural numbers up to n

Step 1: Start

Step 2: get n value.

Step 3: initialize i=1

Step 4: if (i<=n) go to step 5 else go to step 7

Step 5: Print i value and increment i value by 1

Step 6: go to step 4

Step 7: Stop

1.1.4 Functions

 Function is a sub program which consists of block of code(set of


instructions) that performs a particular task
 For complex problems, the problem is been divided into smaller and
simpler tasks during algorithm design

Benefits of Using Functions

 Reduction in line of code


 code reuse
 Better readability
 Information hiding
 Easy to debug and test
 Improved maintainability

Example

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 9

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Algorithm for addition of two numbers using function

Main function()

Step 1: Start

Step 2: Call the function add()

Step 3: Stop

sub function add()

Step 1: Function start

Step 2: Get a, b Values

Step 3: add c=a+b

Step 4: Print c

Step 5: Return

Example flow chart

1.2 Notation
PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 10

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 Algorithm notations are used to compare efficiency between different


algorithms, the basics are: o(n) faster O(n) faster or equal Θ(n) equal to
Ω(n) slower or equal to

1.2.1 Flow chart

 Flowcharts are the graphical representation of the algorithms


 The algorithms and flowcharts are the final steps in organizing the
solutions
 The purpose of flowchart is making the logic of the program clear in a
visual representation
 Using the algorithms and flowcharts the programmers can find out the
bugs in the programming logic and then can go for coding
 Flowcharts can show errors in the logic and set of data can be easily
tested using flowcharts

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 11

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Rules for drawing a flowchart

 The flowchart should be clear, neat and easy to follow


 The flowchart must have a logical start and finish
 Only one flow line should come out from a process symbol

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 12

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 Only one flow line should enter a decision symbol. However, two or three
flow lines may leave the decision symbol

 Only one flow line is used with a terminal symbol

 Intersection of flow lines should be avoided

Advantages of flowchart

 Communication
 Effective analysis
 Proper documentation
 Efficient Coding
 Proper Debugging
 Efficient Program Maintenance

Example

Convert the algorithm for computing factorial of given number

Solution

The algorithm for computing factorial of given number is

Read N

Set i and F to 1
PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 13

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

While i < = N

F = F*i

Increase the value of i by 1

Display F

End

Example flow chart

Example

Draw a flow chart to accept three distinct numbers find the


greatest and print the result

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 14

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

1.2.2 Pseudo code

 Pseudocode is an artificial and informal language that helps programmers


develops algorithms.
 Pseudocode is a "text-based" detail (algorithmic) design tool
 Pseudo code consists of short, readable and formally styled English
languages used for explain an algorithm
 It does not include details like variable declaration, subroutines
 It is easier to understand for the programmer or non programmer to
understand the general working of the program, because it is not based on
any programming language
 It gives us the sketch of the program before actual coding
 It is not a machine readable
PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 15

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 Pseudo code can’t be compiled and executed


 There is no standard syntax for pseudo code

Common keywords used in Pseudocode

1. //: This keyword used to represent a comment

2. BEGIN,END: Begin is the first statement and end is the last statement

3. INPUT, GET, READ: The keyword is used to inputting data

4. COMPUTE, CALCULATE: used for calculation of the result of the


given expression

5. ADD, SUBTRACT, INITIALIZE used for addition, subtraction and


initialization

6. OUTPUT, PRINT, DISPLAY: It is used to display the output of the


program

7. IF, ELSE, ENDIF: used to make decision

8. WHILE, ENDWHILE: used for iterative statements

9. FOR, ENDFOR: Another iterative incremented/decremented tested


automatically

Syntax for if else

IF (condition)THEN

statement

...

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 16

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

ELSE

statement

...

ENDIF

Example: Greates of two numbers

BEGIN

READ a,b

IF (a>b) THEN

DISPLAY a is greater

ELSE

DISPLAY b is greater

END IF

END

Syntax for For

FOR( start-value to end-value) DO

statement

...

ENDFOR

Example: Print n natural numbers

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 17

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

BEGIN

GET n

INITIALIZE i=1

FOR (i<=n) DO

PRINT i

i=i+1

ENDFOR

END

Syntax for While

WHILE (condition) DO

statement

...

ENDWHILE

Example: Print n natural numbers

BEGIN

GET n

INITIALIZE i=1

WHILE(i<=n) DO

PRINT i

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 18

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

i=i+1

ENDWHILE

END

1.2.3 Programming language

 A programming language is a set of symbols and rules for instructing a


computer to perform specific tasks
 The programmers have to follow all the specified rules before writing
program using programming language
 The user has to communicate with the computer using language which it
can understand

Types of programming language

[Link] language

[Link] language

[Link] level language

Machine language

 The computer can understand only machine language which uses 0’s and
1’s
 In machine language the different instructions are formed by taking
different combinations of 0’s and 1’s
 The program written in machine language can be executed directly on
computer
 In this case any conversion process is not required
 The execution of machine language program is extremely fast
PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 19

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 It is hard to find errors in a program written in the machine language


 Writhing program in machine language is a time consuming process

Assembly language

 To overcome the issues in programming language and make the


programming process easier, an assembly language is developed which is
logically equivalent to machine language but it is easier for people to read,
write and understand
 Assembly languages are symbolic programming language that uses
symbolic notation to represent machine language instructions
 They are called low level language because they are so closely related to
the machines
 Assembler is the program which translates assembly language instruction
in to a machine language
 Machine dependent
 Execution time of assembly language program is more than machine
language program
 Because assembler is needed to convert from assembly language to
machine language

High level language

 High level language contains English words and symbols


 The specified rules are to be followed while writing program in high
level language
 The interpreter or compilers are used for converting these programs
in to machine readable form

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 20

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 A compiler is a program which translates the source code written in a


high level language in to object code which is in machine language
program
 Compiler reads the whole program written in high level language and
translates it to machine language
 If any error is found it display error message on the screen
 Interpreter translates the high level language program in line by line
manner
 The interpreter translates a high level language statement in a source
program to a machine code and executes it immediately before
translating the next statement
 When an error is found the execution of the program is halted and
error message is displayed on the screen.

Examples of various programming languages

Imperative programming languages

 The imperative programming is also called as procedural programming


language

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 21

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Object oriented programming languages

 This language has a modular programming approach

Examples:Lava,Moto

Functional programming

 Computations of functional languages are performed largely through


applying functions to values, i.e., (+ 10 20).
 This expression is interpreted as 10 + 20. The result 30 will be returned

Logic Programming

 In this paradigm(example) we express computation in terms of


mathematical logic only
 It is also called as rule based programming approach

Scripting language

Examples:Apple script,VB script

Markup languages

Examples:HTML,XML

Procedural programming language

Examples:Hyper talk,MATLAB

Concurrent programming language

Examples:Joule,Limbo

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 22

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

1.3 Algorithmic problem solving

 Algorithmic problem solving is solving problem that require the


formulation of an algorithm for the solution

Identify the problem

 Identifying the problem is the first step in solving the problem

Understand the problem

 Before solving any problem it is important to understand it

Identify the alternative ways to solve the problem

 The alternative way to solve the problem must be known to the


developer

Select the best way to solve the problem from list of alternative solutions

 For selecting the best way to solve the problem, the merits and demerits
of each problem must be analyzed

List the instructions using the selected solution

 Based on the knowledgebase (created/used in step 2) the step by step


instructions are listed out

Evaluate the solution

 When the solution is evaluated then


 Check whether the solution is correct or not
 Check whether it satisfies the requirements of the customer or not

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 23

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

1.4 Simple strategies for developing algorithms

 Developing an algorithm is a very important step in problem-solving


 Iteration and Recursion are the simple strategies for developing algorithms
 Basically iteration and recursion perform the same kind of task

1.4.1 Iteration

 A sequence of statements is executed until a specified condition is true is


called iterations
 In iteration the control statements such as for loop, do-while loop or while
is used

Syntax for For:

FOR( start-value to end-value) DO

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 24

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Statement

...

ENDFOR

Example: Print n natural numbers

BEGIN

GET n

INITIALIZE i=1

FOR (i<=n) DO

PRINT i

i=i+1

ENDFOR

END

‘Syntax for While:

WHILE (condition) DO

Statement

...

ENDWHILE

Example: Print n natural numbers

BEGIN

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 25

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

GET n

INITIALIZE i=1

WHILE(i<=n) DO

PRINT i

i=i+1

ENDWHILE

END

1.4.2 Recursion

 A function that calls itself is known as recursion


 Recursion is a process by which a function calls itself repeatedly until
some specified condition has been satisfied

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 26

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 Recursion is a method of solving problems that involves breaking a


problem down into smaller and smaller subproblems until you get to a
small enough problem that it can be solved trivially

Pseudo code for factorial using recursion:

Main function

BEGIN

GET n

CALL factorial(n)

PRINT fact

BIN

Sub function factorial(n)

IF(n==1) THEN

fact=1

RETURN fact

ELSE

RETURN fact=n*factorial(n-1)

Algorithm for factorial of n numbers using recursion

Main function

Step1: Start

Step2: Get n
PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 27

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Step3: call factorial(n)

Step4: print fact

Step5: Stop

Sub function factorial(n)

Step1: if(n==1) then fact=1 return fact

Step2: else fact=n*factorial(n-1) and return fact

UNIT-II
2. Python interpreter

 Python is an interpreted object-oriented programming language


 A python interpreter is a computer program that converts each high-level
program statement into machine code called byte code

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 28

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 This interpreter can be implemented in various languages, such as C, Java,


or even Python itself
 The standard Python interpreter, known as CPython, is written in C
 Interpreters translate programs one statement at a time
 interpreters usually take less time to analyze(study) the source code

 Python interpreter has two components


 The translator checks the statement for syntax
 If found correct, it generates an intermediate byte code
 There is a Python virtual machine which then converts the byte code in
native binary and executes it

Example

#Demonstrating interpreted python

print "\n\n----This line is correct----\n\n" #line1

print Hello #this is wrong #line2

Output

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 29

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 In the above illustration(image), you can see that line 1 was syntactically
correct and hence got successfully executed
 Whereas, in line 2 we had a syntax error
 The interpreter stopped executing the above script at line 2
 This is not valid in the case of a compiled programming language
 Interpreters don’t generate any Object code

2.1 Python interactive mode

 A way of using the Python interpreter by typing commands and


expressions at the prompt
 The Python interactive shell starts is called the Prompt String
 The prompt string suggests that the interactive shell is now ready to take
new commands
 Python has 2 prompt strings, one primary >>> and one secondary ...
which we usually see when an execution unit (statement) spans multiline
 To work in interactive mode, we use an environment Integrated
Development and Learning Environment or IDLE
 IDLE shell is an environment window for executing a single python
statement, generally one at a time
 It produces instant output

Example python prompt

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 30

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 It is automatically installed when Python is installed for Windows


 Alternatively, you can go to the windows command prompt and type
python and press enter. Now you will be able to execute single python
statements

Example

 Before creating actual python programs, let us first practice entering single
statements in IDLE shell, which will help writing short programs later in
script mode
 In python, print is a function used to display some data on the screen
 It is a frequently used in a variety of ways
 As soon as we type the statement print("Hello World!") and press
ENTER, the python interpreter immediately executes it
 The output is displayed in the next line
 Input statements are shown in colors, outputs are in white
 To display a group of characters like "Hello World!", quotations are
needed

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 31

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 A sequence of characters inside quotations is called a string


 In python, generally double and single quotes function similarly
 When we display a number with print, quotations are not needed
 A number without quotations is a numeric value. "Hello World!", 123,
45.6 are values
 Interactive Python is very much helpful for the debugging purpose
 Python has two basic modes: normal and interactive
 The normal mode is the mode where the scripted and finished .py files are
run in the Python interpreter

2.2 Values

 In computer programming, a value is a number, or a character, or a


sequence of chracters, digits, symbols, punctuations etc.

Examples of values

11, -59, 0.4, -3.7, +268 "11", "hello", "abc@#$", "Python is easy
and powerful!"

 The above values have a technical term, literals


 Literals are raw data or fixed values
 Constants do not change during the execution of a program
 Every literal has a data-type
 123 is an integer literal
 It is of integer data-type, and recognized by python as 'int'
 45.6 is a float literal
 Decimal numbers are of float data-type, and recognized as 'float'
 "Hello World!" is a string literal
 It is of string data-type, and recognized as 'str'
PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 32

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 String literals must be enclosed within quotes


 The term data-type is a very important concept(idea) in programming
 We can find the data-type of any literal by using another function type()
 The purpose of type() is to find the data-type of the given literal, variable,
or expression

Example of type()

>>>type("HelloWorld!")
<class 'str'>
 The output <class 'str'> indicates that the given character set "Hello
World!" is of 'str' data-type(string)
>>>type(123)
<class 'int'>
>>>type(56.7)
<class 'float'>
 <class 'int'> confirms that data-type of 123 is 'int'
 <class 'float'> denotes that of 56.7 is a 'float' type

2.3 Data types

Numbers

 Number data type stores Numerical Values


 This data type is immutable [i.e. values/items cannot be changed]
 Python supports integers, floating point numbers and Boolean

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 33

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

2.3.1 Integer

 This value is represented by the int class


 Contains positive or negative integers (not fractions or decimals)
 In Python, there is no limit to the length of an integer value
 There are two types of integers in python int and boolean

Example

x=1

y = 35656222554887711

z = -3255522

Example

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 34

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

a=7

print("Type of a: ", type(a))

Type of a: <class 'int'>

2.3.2 Boolean

 The simplest build-in type in Python is the bool type


 It has two values: True and False. True has the value 1 and False has the
value 0

Example

>>>bool (0)

False

>>>bool (1)

True

>>>bool (‘‘)

False

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 35

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

>>>bool (-34)

True

>>>bool (34)

True

2.3.3 Float

 This is used to store the decimal values


 It is represented by float class
 It is a real number with floating-point representation
 Float or “floating point number” is a number, positive or negative
 In floating-point numbers, there is no fixed number of digits before or
after the decimal point

Example

X = 1.0

Y = 25.125

Z = - 48.1928569

print(X, Y, Z)

type(X)

Output

1.0 25.125 -48.1928569

<class ‘float’>

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 36

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

2.3.4 String

 A string is a collection of characters


 We can use single, double, or triple quotes to represent strings
 Triple quotes multi-line strings can be denoted. Like tuple strings are
immutable
 Python does not have a character data type
 A single character is simply a string with a length of 1
 Each character in a string has its own index
 String is immutable data type means it can never change its value in
place

Example

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 37

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Example

str1 = 'hello eMexo' #string str1

str2 = ' how are you' #string str2

print (str1[0:2]) #printing first two character using slice operator

print (str1[4]) #printing 4th character of the string

print (str1*2) #printing the string twice

print (str1 + str2) #printing the concatenation of str1 and str2

Output

he

hello eMexohello eMexo

hello eMexo how are you

2.3.5 List

 Python lists are similar to C arrays


 A list is a data type that allows you to store various types data in it
 It is a compound data type which means you can have different-2 data
types under a list, for example we can have integer, float and string items
in a same list
 There are commas (,) between items in the list, and square brackets []
surround each item

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 38

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 The concatenation operator (+) and the repeat operator (*) operate on
lists as they would for strings

Example

list1 = [1, "hi", "Python", 2]

#Checking type of given list

print(type(list1))

#Printing the list1

print (list1)

# List slicing

print (list1[3:])

# List slicing

print (list1[0:2])

# List Concatenation using + operator

print (list1 + list1)

# List repetation using * operator

print (list1 * 3)

Output

[1, 'hi', 'Python', 2]

[2]

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 39

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

[1, 'hi']

[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]

[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]

2.4 Variables

 Variable is a named memory location to store the temporary data within


a program
 We have two types of memory in a computer environment (Temporary
Memory- RAM and Permanent Memory – ROM)
 Variables store in the Temporary memory (RAM)
 In Python, We do not need to declare variables before using them or
declare their type
 A variable is created the moment we first assign a value to it
 A variable is a name given to a memory location
 It is the basic unit of storage in a program

2.4.1 Variable naming rules

 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
 The reserved words(keywords) cannot be used to name the variable

2.4.2 Creating variables

 Python has no command(rule) for declaring a variable

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 40

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 A variable is created the moment you first assign a value to it

2.4.3 Single value assignment

 This is a variable where only one data value is assigned to it


 The data values can be of any data type

Syntax

variable=expr

Example

# declaring the variables

x = 123

y = “Udayakumar”

z=10.234

# Print variables

print(x)

print(y)

print(z)

Output

123

Udayakumar

10.234

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 41

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

2.4.4 Multiple data assignment

Assigning a single value to multiple variables

 This is a variable where one data value is assigned to multiple variables

Syntax

var1=var2=var3...varn = expr

Example

a = b = c = 10

print(a)

print(b)

print(c)

Output

10

10

10

2.4.5 Assigning a multiple values to single variables

 This is a variable where more than one data value is assigned to the
variable
 These data values can also be accessed individually

Syntax

var=exp1,exp2,exp3…..exp-n

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 42

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Example

team = "Favour", "Victor", "Clarence"

print(team)

Output

('Favour', 'Victor', 'Clarence')

Let's access the individual data values in team:

team = "Favour", "Victor", "Clarence"

print(team[1])

Output

Victor

Explanation

 Using index count, we start from index 0


 So "Favour" is at index 0, "Victor" at index 1, and "Clarence" at index 2
 We access the data value at index 2

2.4.6 Different data types in one variable

 Python variable contains different data type values

Syntax

var=exp1,exp2,exp3…..exp-n

diff = "Favour", 20, True

print(diff)

Output

('Favour', 20, True)

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 43

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Explanation

The variable diff contains the following data types:

 "Favour": String
 20: Integer
 True: Boolean

Note: In multiple data variables, we use commas (,) to separate the data
values. When accessing these data values individually, we use square
brackets([]) for their index numbers

2.4.7 Assigning different values to multiple variables

 We can also assign the multiple objects to multiple variables

Syntax

var, var, ..., var = expr, expr, ..., expr

Example

a, b, c = 1, 20.2, “uday”

print(a)

print(b)

print(c)

Output

20.2

Uday
PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 44

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

2.5 Expressions

 An expression in python is any valid combination operators, literals and


variables
 An expression is python is any valid combination of operation and atoms
 As expression are the composed of one or more operation

2.5.1 Atoms

 An atom is something that has a value


 Identifiers, literals, string, lists, tuples, sets, dictionaries, etc. are all
atoms

2.5.2 Arithmetic expression

 In arithmetic expression, we perform the mathematical calculation using


arithmetic operators like +, -, *, /, etc.
 These expressions involve numbers (integers, floating-point numbers,
complex numbers) and arithmetic operators

Example

# Program to calculate the sum of two numbers

num1 = 20

num2 = 40

sum = num1 + num2 # An arithmetic expression

print("Sum of two numbers is ", sum)

Output

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 45

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Sum of two numbers is 60

2.5.3 Relational expression

 The relational expression compares two operators using relational


operators, such as >, <, >=, <=, etc. It is also called conditional
expression
 An expression having literals and/or variables of any valid type and
relational operators is a relational expression

Example

# Python program to find greater between three numbers

num1 = int(input("Enter the first number: "))

num2 = int(input("Enter the second number: "))

num3 = int(input("Enter the third number: "))

if num1 > num2 and num1 > num3:

print(num1, 'is a greater number among the three numbers.')

elif num2 > num1 and num2 > num3:

print(num2, 'is a greater number among the three numbers.')

else:

print(num3, 'is a greater number among the three numbers.')

Output

Enter the first number: 20

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 46

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Enter the second number: 10

Enter the third number: 30

30 is a greater number among the three numbers.

2.5.4 Logical expression

 The logical expression uses the logical operators, such as and , or, and not
 It produces a boolean value, either true or false value
 An expression having literals and/or variables of any valid type and
logical operators is a logical expression

Example

p = 10

q = 15

r=5

s = 20

result = p > q and r > s

print("Logical expression (p > q and r > s) returns ", result)

Output

Logical expression (p > q and r > s) returns False

2.5.5 String expression

 Python also provides two string operators + and *, when combined with
string operands and integers, form string expressions

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 47

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 With operator +, the concatenation operator, the operands should be one


string type only
 With * operator, the replication operator, the operands should be one
integer

Example

>>> "Hello, " + "World!"

'Hello, World!'

>>> ("A", "B", "C") + ("D", "E", "F")

('A', 'B', 'C', 'D', 'E', 'F')

>>> [0, 1, 2, 3] + [4, 5, 6]

[0, 1, 2, 3, 4, 5, 6]

Example

>>> "Hello" * 3

'HelloHelloHello'

>>> 3 * "World!"

'World!World!World!'

>>> ("A", "B", "C") * 3

('A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C')

>>> 3 * [1, 2, 3]

[1, 2, 3, 1, 2, 3, 1, 2, 3]

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 48

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

2.6 Statements

 Instructions that a Python interpreter can executes are called statements


 A statement is a unit of code like creating a variable or displaying a value

2.6.1 Multiline python statement

 In Python, every statement ends with a newline character

Example

>>> a=\

10\

+20

>>> a

Output

30

Example

>>> "Hello\

hi"

Output

‘Hellohi’

>>> a=(

10+

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 49

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

20)

>>> a

Output

30

>>> type(a)

<class 'int'>

2.6.2 Multiple python statement in one line

>>> a=7; print(a)

Output

Example

>>> if 2>1: print("2")

Output

2.6.3 String python statements

 To declare strings in python, you may use single or double quotes

>>> "Hello 'user'"

Output

“Hello ‘user'”

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 50

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

2.6.4 Assignment statements in python

 In python, when assigning a value to a variable you use the assignment


statement
 The values can be of any data type
 In python, you don’t have to declare the variable
 The declaration happens automatically during execution

Example

int1=10

string1="This is a sentence"

list1=["PythonGeeks",1,2,3,"syntax"]

dictionary1={"one":1, "two":2}

tuple1=("apple",100)

print(f"The datatype of {int1} is {type(int1)}")

print(f"The datatype of {string1} is {type(string1)}")

print(f"The datatype of {list1} is {type(list1)}")

print(f"The datatype of {dictionary1} is {type(dictionary1)}")

print(f"The datatype of {tuple1} is {type(tuple1)}")

Output

The datatype of 10 is <class ‘int’>

The datatype of This is a sentence is <class ‘str’>

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 51

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

The datatype of [PythonGeeks, 1, 2, 3, ‘syntax’] is <class ‘list’>

The datatype of {‘one’: 1, ‘two’: 2} is <class ‘dict’>

The datatype of (‘apple’, 100) is <class ‘tuple’>

2.6.5 Python indentation

 Indentation is when you add a blank/white space before a statement


 In python, indentation is a very important part of the code
 If you don’t use proper indentation, the code won’t run and you’ll get an
error stating “IndentationError”

Example

Incorrect Indentation in python

password="password"

p=input("please enter a number\n")

if(p!=password):

print("you have entered incorrect password")

else:

print("Successfully signed in")

 The example above shows you how the code would look if the indentation
is incorrect
 When you run this code you will get an error message stating “expected
indentation block” as shown in the output

Example

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 52

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Correct Indentation in python

password="password"

p=input("please enter a number\n")

if(p!=password):

print("you have entered incorrect password")

else:

print("Successfully signed in")

Output

please enter the password

password

Successfully signed in

2.6.6 Compound statements in python

 Multiple statements or a group of statements written together to form


compound statements
 Compound statements together form a block of code
 Every time you work with multiple statements that form a block of code,
indentation is important

Example

Compound statement in python

for num in range (1,20):

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 53

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

if num > 1:

for i in range(2,num):

if (num % i) == 0:

break

else:

print(num)# 2 3 5 7 11 13 17 19

2.7 Tuple in python

Example

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 54

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

2.7.1Accessing elements in a tuple

2.7.2 Tuple is immutable

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 55

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

2.7.3 Tuple operations

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 56

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 57

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 58

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

2.7.4 Tuple methods and built in functions

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 59

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

2.7.5 Nested tuple

2.7.6 Tuple assignment

Example

>>>tup1 = (8, 99, 90, 6.7)

>>>(roll no., english, maths, GPA) = tup1

>>>print(english)

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 60

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

99

>>>print(roll no.)

>>>print(GPA)

6.7

>>>print(maths)

90

Example

>>> (num1, num2, num3, num4, num5) = (88, 9.8, 6.8, 1)

#this gives an error as the variables on the left are more than the number of
elements in the tuple

Output

ValueError: not enough values to unpack

(expected 5, got 4)

2.8 Precedence of operators

 In Python programming, the concept of operator precedence refers to a set of


rules that dictate(readout) the order in which the operators within an
expression
 The order of precedence for Python operators is presented in the following
table, where the highest-precedence operators appear at the top and the
lowest-precedence operators appear at the bottom

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 61

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Example

NOTE: When evaluating expressions that involve multiple operators, those with
higher precedence are processed before those with lower precedence

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 62

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

NOTE: If there are multiple operators with the same level of precedence, then they
are processed on the basis of their associativity

2.9 Comments

 The lines of code in Python that the interpreter ignores while the program
is running are called comments
 A comment is a line of text within a program that is not executed
 Python code can be explained with comments
 The code can be made easier to read by adding comments

2.9.1 Single-line comments

 These comments add a short description or note about a single line of


code
 They start with a '#' symbol and continue until the end of the line

Example

# This is a single-line comment

# This is another single-line comment

2.9.2 Multi-line comments

 These comments add longer descriptions or notes about multiple lines of


code
PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 63

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 They start and end with three single quotes ("''') or three double quotes
(""")

Example

''' This is a multi-line comment.

It can span multiple lines. '''

2.9.3 Docstrings

 In Python, docstring refers to documentation string


 A docstring is included as a first-line inside a function, module, class or
method
 Docstring is a short description of what your function, module or class
does
 Docstrings can be accessed using the help( ) function in Python

Example

def function():

""" The function prints hello world """

print(“Hello, World!”)

2.10 Modules

 A module in Python is simply a file containing Python definitions and


statements, such as functions, classes, and variables
 By organizing code into modules, you can reuse it across multiple
programs and manage large projects more easily

Module file: A Python module is just a .py file

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 64

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Standard Library: Python comes with a large standard library of built-in modules
like math, os, sys, and datetime

Custom Modules: You can create your own modules by placing your Python
code in separate files

2.10.1 Importing standard modules

 Python has a rich set of built-in modules. For example, the math module
provides mathematical functions

Example

# Importing the math module

import math

print([Link](16)) # Output: 4.0

print([Link]) # Output: 3.141592653589793

Example

Creating Your Own Module

 If you have a file named my_module.py, you can create functions inside it
and import them in other scripts
# my_module.py

def greet(name):

return f"Hello, {name}!"

def add(a, b):

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 65

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

return a + b

Main Python Script

# Importing the custom module

import my_module

print(my_module.greet("Alice")) # Outputs: Hello, Alice!

print(my_module.add(5, 7)) # Outputs: 12

Example

Importing Specific Functions

 You can also import specific functions or variables from a module to


avoid having to use the module's name as a prefix

# Importing only the 'add' function from my_module


from my_module import add
print(add(10, 20)) # Outputs: 30

Example

Aliasing Modules

 You can rename the module during import with an alias using the as
keyword

import math as m

print([Link](25)) # Outputs: 5.0

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 66

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

2.10.2 Function in modules

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 67

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

2.11 Functions

 A function is a block of code that performs a specific task


 Functions help in breaking our program into smaller, modular pieces,
making it easier to understand, maintain, and reuse

2.11.1 Function definition and use

Defining a Function

 A function is defined using the def keyword, followed by a function name


and parentheses containing optional parameters

def greet():

print("Hello, World!")

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 68

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Calling a Function

 To execute a function, we call it by its name followed by parentheses


greet() # Output: Hello, World!

Function Arguments

 Functions can accept arguments, which are values passed to the function
when it is called
 We define arguments inside the parentheses

def greet(name):

print(f"Hello, {name}!")

greet("Alice") # Output: Hello, Alice!

Default Arguments

 We can provide default values for function arguments


 If an argument is not passed when the function is called, the default value is
used

def greet(name="World"):

print(f"Hello, {name}!")

greet() # Output: Hello, World!

greet("Alice") # Output: Hello, Alice!

Return Values

 Functions can return values using the return statement

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 69

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

def add(a, b):

return a + b

result = add(3, 5)

print(result) # Output: 8

Keyword Arguments

 When calling a function, we can specify arguments by their parameter


names
 This is useful when a function has many arguments

def greet(first_name, last_name):

print(f"Hello, {first_name} {last_name}!")

greet(first_name="Alice", last_name="Johnson")

Variable-Length Arguments

Python allows functions to accept an arbitrary number of arguments using


*args for non-keyword arguments and **kwargs for keyword arguments

def print_numbers(*args):

for number in args:

print(number)

print_numbers(1, 2, 3, 4)

def print_info(**kwargs):

for key, value in [Link]():

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 70

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

print(f"{key}: {value}")

print_info(name="Alice", age=25)

2.12 Flow of execution

 Python is programming language ,it is easy-to-learn for beginners ,it is


object oriented and it is case sensitive language
 Python is often used as a support language for software developers, for
build control and management, testing, and in many other ways
 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

Work flow

 The first step of work flow is to write a source code in python (simple
English/ high level language)
 Next step is to check the syntax with the set instructions/rules
 After checking of syntax if it didn’t have any error in syntax then it will
send source code to the compiler
 In compiler ,the source code can be converted in byte code
 This byte code send to a PVM(python virtual machine) which contain the
interpreter in it
 This interpreter will check code line by line and convert byte code into
machine code (low level language)

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 71

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 Atleast , the output what we wanted will execute in high level language.
And the total process is done in python engine

2.13 Parameters and Arguments

Parameters

 Parameters are the names that appear in the function definition


 In the example below, name, age, and skill are the parameters as they
appear in the function definition

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 72

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Arguments

 Arguments are the names that appear in the function call


 In the below example, ‘Chetan’, 33, and ‘Python’ are the arguments

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 73

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

UNIT-III
3. Boolean values

 Boolean values are the backbone of decision-making in programming


 They represent true or false states, allowing programs to make choices
based on conditions

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 74

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 This fundamental concept enables developers to create dynamic,


responsive code
 Comparison operators and logical operators work hand-in-hand with
Boolean values
 These tools let programmers craft(technique) complex conditions, evaluate
data, and control program flow

Example

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 75

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Example

>>> 3==5

False

>>> 6==6

True

>>> True+True

>>> False+True

>>> False*True

Boolean values of Constructs in Python

 The values of other data types are True if they are neither empty nor 0,
else they are False

The following values are considered to be False

1. Numbers: 0,0.0,0j

2. Strings: ”,””

3. Lists, tuples: [],()

4. Dictionary:{}

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 76

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

5. False

6. None

7. Other methods that return either 0 or False

1. Numbers

 The numbers with 0 as the values are considered as False and the others are
True

Example

bool(0)

bool(0.0000000000001)

bool(0.0j)

Output

False

True

False

Strings

 Only an empty string is False, the rest of the strings are considered to be
true Even the string with space is True, as space is also a character in
Python

Example

bool(" ")

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 77

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

bool("")

bool('PythonGeeks')

Output

True

False

True

Lists, tuples, and dictionaries

 These will be boolean False if they do not have any element or they are
empty. Else, these are true

Example

bool(())

bool((1,2))

bool([])

bool(['t'])

bool({})

bool({4:'c'})

Output

False

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 78

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

True

False

True

False

True

Others

 Let us check the Boolean for the others too

Example

bool(None)

bool(True)

bool(False)

Output

False

True

False

3.1 Operators

 Operators are used to perform operations on values and variables


 These are the special symbols that carry out arithmetic and logical
computations
 The value the operator operates on is known as Operand

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 79

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Arithmetic Operators

 Arithmetic operators are used for mathematical computations like


addition, subtraction, multiplication, etc.
 They generally operate on numerical values and return a numerical value
 They’re also referred to as mathematical operators

Example

a = 21

b = 10
PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 80

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

# Addition

print ("a + b : ", a + b)

# Subtraction

print ("a - b : ", a - b)

# Multiplication

print ("a * b : ", a * b)

# Division

print ("a / b : ", a / b)

# Modulus

print ("a % b : ", a % b)

# Exponent

print ("a ** b : ", a ** b)

# Floor Division

print ("a // b : ", a // b)

Output

a + b : 31

a - b : 11

a * b : 210

a / b : 2.1

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 81

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

a%b:1

a ** b : 16679880978201

a // b : 2

Comparison/ Relational operators

 Comparison operators are used for comparing two values


 As an output, they return a boolean value, either True or False

Example

a=4

b=5

# Equal

print ("a == b : ", a == b)

# Not Equal

print ("a != b : ", a != b)

# Greater Than

print ("a > b : ", a > b)

# Less Than

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 82

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

print ("a < b : ", a < b)

# Greater Than or Equal to

print ("a >= b : ", a >= b)

# Less Than or Equal to

print ("a <= b : ", a <= b)

Output

a == b : False

a != b : True

a > b : False

a < b : True

a >= b : False

a <= b : True

Logical operators

 These operators are used to perform logical and, or, and not operations
 They operate on Boolean values and return a Boolean value

Example

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 83

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

x = True

y = False

# Logical and

print("x and y =", x and y)

# Logical or

print("x or y =", x or y)

# not operator

print("not x =", not x)

print("not y =", not y)

Output

x and y = False

x or y = True

not x = False

not y = True

Bitwise Operators

 Bitwise operators operate on the binary values of the operands bit-by-bit

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 84

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Bitwise And (&)

 The bitwise AND operator takes two arguments and performs AND
operation on the operands bit by bit

Example

>>> 10&7

2 # output

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 85

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Bitwise Or ( | )

 The bitwise OR operator performs a logical OR operation on each bit of


the operands
 It takes two binary numbers and compares their corresponding bits
 If either bit is 1, the result is 1; if both bits are 0, the result is 0

Example

>>> 10|7

15 #output

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 86

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Bitwise Xor (^)

 The bitwise Xor also takes two operands and performs Xor operation on
the binary digits
 The Xor operation gives 0 as a result when both operands are the same

Example

>>> 10^7

13 #output

>>>

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 87

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Bitwise complement (~)

 The bitwise complement operator works on a single operand and inverts


all the bits of the number
 This means that each 0 in the binary representation is changed to 1, and
each 1 is changed to 0
 Python Ones’ complement of a number ‘A’ is equal to -(A+1).

Example

>>> ~10

-11

>>> ~-10

>>>

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 88

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Left-Shift (<<)

 The bitwise left shift is a binary operator that shifts the number of bits to
its left position
 It shifts all bits to the left according to the values specified on the right-
hand side of the operator
 After performing the left shift operation on the bits, the operator fills the
rightmost bits by 0

Syntax

A << B

Example

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 89

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Right-Shift (>>)

 The bitwise right shift is a binary operator that shifts the number of bits to
its right position
 It shifts all bits to the right according to the values specified on the right-
hand side of the operator
 After performing the right shift operation on the bits, the operator fills the
leftmost bits by 0
 In simple terminology, right side bits are removed

Syntax

A >> B

Example

Example

# x = 9 which is 0001 0001 in binary

x=9

# y = 3 which is 0000 0011 in binary

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 90

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

y=3

# Bitwise AND

print("x&y = ", x&y)

# Bitwise OR

print("x|y = ", x|y)

# Bitwise Not

print("~x = ", ~x)

# Bitwise XOR

print("x^y = ", x^y)

# Bitwise Right Shift

print("x>>2 = ", x>>2)

# Bitwise Left Shift

print("x<<2 = ", x<<2)

Output

x&y = 1

x|y = 11

~x = -10

x^y = 10

x>>2 = 2

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 91

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

x<<2 = 36

Identity operator

 Identity Operators help find out whether the value of operand (variable in
general programming term) shares the same memory location
 If the same value is tied to two variable then Identity operators will
output True
 There are only two types of Identity operators, “is” and “is not”

Example

Consider x= 10 and y = 20 and z = 10

 x is z => True
 x is y => False
 x is not z => False
 y is not z => True

Membership operators

 These operators test for membership in a sequence such as lists, strings or


tuples
 There are two membership operators that are used in Python. (in, not in)
 It gives the result based on the variable present in specified sequence or
string

Example

x=4

y=8

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 92

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

list = [1, 2, 3, 4, 5 ];

if ( x in list ):

print("Line 1 - x is available in the given list")

else:

print("Line 1 - x is not available in the given list")

if ( y not in list ):

print("Line 2 - y is not available in the given list")

else:

print("Line 2 - y is available in the given list")

Output

Line 1 - x is available in the given list

Line 2 - y is not available in the given list

3.2 Decision making statements/Conditional statements

 These conditional statements, known as decision making statements in


Python because they execute a block of statements based on a decision
 They use the boolean expression for conditional test
 The boolean expression may be either a single expression or multiple
expressions

3.2.1 If statement

 The if statement is the simplest form


 It takes a condition and evaluates to either True or False

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 93

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 If the condition is True, then the True block of code will be executed
 If the condition is False, then the block of code is skipped, and the
controller moves to the next line

Syntax

if condition:

statement 1

statement 2

statement n

Flow diagram

Example

number = 6

if number > 5:

# Calculate square

print(number * number)

print('Next lines of code')


PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 94

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Output

36

Next lines of code

3.2.2 If – else statement

 The if-else statement checks the condition and executes the if block of code
when the condition is True, and if the condition is False, it will execute
the else block of code

Syntax

if condition:

statement 1

else:

statement 2

 If the condition is True, then statement 1 will be executed If the condition


is False, statement 2 will be executed

Flow diagram

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 95

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Example

password = input('Enter password ')

if password == "PYnative@#29":

print("Correct password")

else:

print("Incorrect Password")

Output 1:

Enter password PYnative@#29

Correct password

Output 2:

Enter password PYnative

Incorrect Password

3.2.3 Chained conditional (if-elif-else)

 In Python, the if-elif-else condition statement has an elif blocks to chain


multiple conditions one after another
 This is useful when you need to check multiple conditions
 The elif statement checks multiple conditions one by one and if the
condition fulfills, then executes that code

Syntax

if condition-1:

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 96

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

statement 1

elif condition-2:

stetement 2

elif condition-3:

stetement 3

...

else:

statement

Flow diagram

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 97

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Example

if age>7 and age<=10:

print(">7-10")

elif (age<=3):

print("1-3")

elif (age<=5):

print("4-5")

elif (age<=7):

print("6-7")

else:

print("error")

Output

If the value of the variable is equal to 8, 9 or 10

>7-10

3.3 Iteration/Looping /control flow Statements

 In a programming language, a looping statement contains instructions


that continually repeat until a certain condition is reached
 Looping simplifies complicated problems into smooth ones
 It allows programmers to modify the flow of the program so that rather
than writing the same code, again and again

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 98

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 Programmers are able to repeat the code a finite number of times

3.3.1 While loop

 In Python, a while loop is used to execute a block of code repeatedly as


long as a specified condition is true
 It continues to execute the block of code until the condition becomes false
 It is also called a pre-tested loop
 When the condition becomes false, the loop ends and moves to the next
statement after the loop

Syntax

while condition:

statement(s)

Flow diagram

Example

num = 10

sum = 0

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 99

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

i=1

while i <= num:

sum = sum + i

i=i+1

print("Sum of first 10 number is:", sum)

3.3.2 For loop

 The for loop is used in the case where a programmer needs to execute a
part of the code until the given condition is satisfied
 The for loop is also called a pre-tested loop
 It is best to use for loop if the number of iterations is known in advance
 The for loop works well with iterable objects like lists, tuples, strings, etc.
 In Python, there is no C style for loop, i.e., for (i=0; i<n; i++)

Syntax

for variable in sequence:

statements(s)

Flow diagram

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 100

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Example

for i in range(1, 11):

print(i)

Output

10

3.3.3 Break

 The break statement is useful when you want to exit out of the loop if some
condition is true

Syntax

break

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 101

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Flow diagram

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 102

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Example

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

88

The number 88 is found

Terminating the loop

3.3.4 Continue

 The continue statement is used to skip the current iteration and continue
with the next iteration

Syntax

while (test_expression1): for var in sequence:

statement(s) statement(s)

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 103

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

if (test_expression2): if (test_expression2):

continue continue

Flow diagram

Example

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 104

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Example

names = ["Bill Gates", "Billie Eilish", "Mark Zuckerberg", "Hussain"]

for name in names:

if name == "Mark Zuckerberg":

print("Skipping this iteration.")

continue # Skip iteration if true.

print(name)

print("Out of the loop")

Output

Bill Gates

Billie Eilish

Skipping this iteration.

Hussain

Out of the loop

3.3.5 Pass

 The pass is the keyword In Python


 Sometimes there is a situation in programming where we need to define a
syntactically empty block
 We can define that block with the pass keyword

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 105

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Syntax

pass

Flow diagram

Example

months = ['January', 'June', 'March', 'April']

for mon in months:

pass

print(months)

Output

['January', 'June', 'March', 'April']

3.4 Fruitful functions

 Fruitful functions differ from void functions


 The fruitful functions are the functions that return values

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 106

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 Void functions allow you to perform calculations, manipulate data, and


generate outputs
 With fruitful functions, we can reduce code redundancy
 To define a fruitful function in Python, you need to use the keyword "def"
followed by the function name
 Fruitful functions still allow the user to provide information (arguments)
 Most of the built-in functions that we have used are fruitful >>>
abs(−42)

3.4.1 Return values

 The return statement lies at the heart of fruitful functions


 The value can be returned from a function using the keyword return
 The Keyword return is used to return back the value to the called function
 Returning single values
 Returning multiple values using tuples
 Utilizing conditional statements in return statements
 Error handling and exception raising
 Creating a very simple mathematical function that we will call square
 The square function will take one number as a parameter and return the
result of squaring that number
 Here is the black-box diagram with the Python code following

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 107

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Syntax

return (expression_list)

Example

def square(original_number):

squared_value = original_number * original_number

return squared_value

to_square = 10

result = square(to_square)

print("The result of", to_square, "squared is", result)

Output

The result of 10 squared is 100

3.4.2 Parameter

 Parameter is the input data that is sent from one function to another

Syntax Functioncall statement

Result=function_name(param1,param2)

The parameters are of two types

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 108

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Formal parameter

 The parameter defined as part of the function definition


 The actual parameter is received by the formal parameter

Actual parameter

 The parameter is defined in the function call

Example

def cube(x):

return x*x*x #x is the formal parameter

a=input(“Enter the number=”)

b=cube(a) #a is the actual parameter

print”cube of given number=”,b

Output

Enter the number=2

Cube of given number=8

3.4.3 Local and Global scope

 The global variables are those variables that are declared and defined
outside the function and can be used inside the function
 The local variables are those variables that are declared and defined
inside a function
 A global variable is one that can be accessed anywhere
 A local variable is the opposite, it can only be accessed within its frame

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 109

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 The difference between the global and local is that global variables can
be accessed locally, but not modified locally

Example

def my_function():

a = 10

print('Inside my_function a value is: ', a)

my_function()

#print('Outside my_function a value is: ', a) # Not accessible

Accessing Global Variable Inside and Outside of the Function

x= “First Global Variable” #Global Variable declaration

def myfunc():

print(“Accessing Inside a function: “ +x)

myfunc()

print(“Accessing Outside a function: “ +x)

Output

Accessing Inside a function: First Global Variable

Accessing Outside a function: First Global Variable

Note: The program will show an error if one tries to modify the global scope
variable value inside a function

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 110

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Global keyword

 The Global keyword is used to make changes in a local context in the


global variable
 The keyword ‘Global’ is used to create or declare a global variable inside
a function

Syntax

def func():

global Variable

Example

def myfunc():

global x #Creating global scope variable inside a function

x = “awesome global scope”

print(“Printing Inside a Function: “ + x)

myfunc()

print(“Printing Outside a Function: “ + x)

Output

Printing Inside a Function: awesome global scope

Printing Outside a Function: awesome global scope

3.5 Function composition

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 111

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 Function composition is a technique where you combine multiple


functions into a single function
 It involves applying one function to the result of another function
 The composition of two functions f and g is denoted f(g(x))
 x is the argument of g, the result of g is passed as the argument of f and the
result of the composition is the result of f

Example

def double(x):

return x * 2

def increment(x):

return x + 1

# Function composition: increment followed by double

def composed_function(x):

return double(increment(x))

# Test the composed function

print(composed_function(3)) # Output: 8 (first increment -> 4, then double -


> 8)

Explanation

The double function

def double(x):

return x * 2

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 112

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

This function takes an argument x and returns x multiplied by 2. For example, if x


= 3, double(3) will return 6

The increment function

def increment(x):

return x + 1

This function takes an argument x and adds 1 to it. For example, if x = 3,


increment(3) will return 4

The composed_function function

def composed_function(x):

return double(increment(x))

This is where function composition happens:

 increment(x) is called first, which increments the value of x by 1.


 The result of increment(x) is then passed as an argument to double(x), which
multiplies the result by 2

step 1: The function composed_function(3) is called with x = 3

Step 2: Inside composed_function, the increment(3) function is called, which gives


the result 3 + 1 = 4

Step 3: The result 4 is then passed to the double(4) function, which gives the result
4*2=8

Thus, composed_function(3) results in 8

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 113

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

3.6 Recursion

 Recursion means iteration


 A function which calls itself during its execution is known as recursive
function

Example

def factorial(n):
# Base case: factorial of 0 is 1
if n == 0:
return 1
else:
# Recursive case: n * factorial of (n-1)
return n * factorial(n - 1)

Base Case

 The function first checks if n == 0


 This is the base case for recursion, which ensures that the recursion stops
when the function reaches 0

First call: factorial(5):

The function checks if n == 0. Since n = 5, this is false.

The function returns 5 * factorial(4).

Second call: factorial(4):

The function checks if n == 0. Since n = 4, this is false.

The function returns 4 * factorial(3).

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 114

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Third call: factorial(3):

The function checks if n == 0. Since n = 3, this is false.

The function returns 3 * factorial(2).

Fourth call: factorial(2):

The function checks if n == 0. Since n = 2, this is false.

The function returns 2 * factorial(1).

Fifth call: factorial(1):

The function checks if n == 0. Since n = 1, this is false.

The function returns 1 * factorial(0).

Sixth call: factorial(0):

The function checks if n == 0. Since n = 0, this is true.

The function returns 1 (base case)

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 115

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

3.7 Strings
 A string is a sequence of characters
 A character can be anything
 A string is a data type in python
 Python string is a sequence of characters or a single charter enclosed in
single, double, or triples quote
 Python treats single and double quotes the same way
 An individual character in a string is accessed using a index
 The index should always be an integer (positive or negative).
 A index starts from 0 to n-1
 Strings are immutable i.e. the contents of the string cannot be changed
after it is created
 Python will get the input at run time by default as a string
 Python does not support character data type
 A string of size 1 can be treated as characters

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 116

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

3.7.1 String slices

 The process of extracting a sub string from a string is called slicing


 This technique is very similar to accessing the string character
 A sub-part of the original string is called substring
 This slice syntax returns the sequence of characters beginning at the start
index and extending up to but not including the end index

String Slicing using slice operator

string_name[start:end[:step]]
 A start parameter specifies the starting index
 A stop parameter specifies the ending index where a string object’s slicing
comes to a halt
 A step parameter is an optional parameter that specifies the increment
 The slicing operator, colon (:)

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 117

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Example

String = "string slicing example"

print(String[1:3]) # tr

print(String[-5:-1]) # ampl

print(String[:4]) # stri

print(String[8:]) # licing example

print(String[-3:]) # ple

 In the above slice operation, we have not specified the step argument
along with the start and stop arguments

Example

str = 'Scientech Easy'

print('Original string:',str)

my_sub1 = str[Link]

print('Substring containing every second character :',my_sub1)

my_sub2 = str[::3]

print('Substring containing every third character:',my_sub2)

Output

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 118

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Original string: Scientech Easy

Substring containing every second character : SinehEs

Substring containing every third character: See s

Explanation

(a) In my_sub1, the slice [Link] takes the character at position 0 and will
print every second character in the string extending till 16th character
(excluding)
(b) In my_sub2, we have omitted both start and end index values to consider
the entire range of characters in the string by specifying two colons. We
have specified step argument 3 to skip characters

3.7.2 Immutability

 Python strings are “immutable” as they cannot be changed after they are
created
 Therefore [ ] operator cannot be used on the left side of an assignment

3.7.3 String functions and methods

 A method is a function that “belongs to” an object


[Link]()
a=”happy birthday”

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 119

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Here, a is the string name

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 120

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

3.7.4 String module

 A module is a file containing Python definitions, functions, statements


 Standard library of Python is extended as modules

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 121

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 To use these modules in a program, programmer needs to import the


module
 Once we import a module, we can reference or use to any of its functions or
variables in our code
 There is large number of standard modules also available in python
 Standard modules can be imported the same way as we import our user-
defined modules

Syntax

import module_name

Example

import string

print([Link])

print([Link])

print([Link])

print([Link]("happy birthday"))

print([Link])

print([Link])

Output

!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

0123456789

0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 122

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

KLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

Happy Birthday

0123456789abcdefABCDEF

01234567

Example

>>>import string

>>>string.ascii_letters

'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

>>>string.ascii_uppercase

'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

>>>string.ascii_lowercase

'abcdefghijklmnopqrstuvwxyz'

>>>[Link]

' \t\n\r\x0b\x0c'

3.8 Lists as arrays

Array

 Array is a collection of similar elements


 Elements in the array can be accessed by index
 Array index starts with 0
 Array can be handled in python by module named array

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 123

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 To create array have to import array module in the program

Syntax

import array

Syntax to create array

Array_name = module_name.function_name(‘datatype’,[elements])

Example

a=[Link](‘i’,[1,2,3,4])

a- array name

array- module name

i- integer datatype

Example

import array

sum=0

a=[Link]('i',[1,2,3,4])

for i in a:

sum=sum+i

print(sum) #10

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 124

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Convert list into array

 fromlist() function is used to append list to array. Here the list is act like a
array

Syntax

[Link](list_name)

Example

import array

sum=0

l=[6,7,8,9,5]

a=[Link]('i',[])

[Link](l)

for i in a:

sum=sum+i

print(sum)# 35

Example

import array

# Create a list

my_list = [10, 20, 30, 40, 50]

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 125

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

# Convert the list to an array

my_array = [Link]('i', my_list) # 'i' is the type code for integers

# Print the array

print(my_array) # Output: array('i', [10, 20, 30, 40, 50])

# Accessing elements in the array

print(my_array[2]) # Output: 30 (third element in the array)

List of floats to array

import array

# Create a list of floats

my_float_list = [1.1, 2.2, 3.3, 4.4]

# Convert the list to an array of floats ('f' for float type)

my_float_array = [Link]('f', my_float_list)

# Print the array

print(my_float_array) # Output: array('f', [1.1, 2.2, 3.3, 4.4])

# Accessing elements in the array

print(my_float_array[1]) # Output: 2.2

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 126

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

UNIT-IV
4. Lists

 It is an ordered collection of data


 Values in the list are called elements / items
 It is similar to an array in other programming languages
 The python list can also hold different data types at the same time
 It is dynamic, not static
 Size need not be specified while declaring
 It is the most widely used data type
 The list is a mutable(changeable)
 We can perform operations that change, add, remove and update
elements/items from the list
 List index count starts from 0
 Python list also allows duplicate elements
 Lists are created using squared brackets [] or list() python constructor

Syntax
list_name = [element_1, element_2, element_3, . . . . ., element_n]
or,
list_name = [value1, value2, value3, . . . . ., valuen]
Declaration of List

 A list can be created by placing the comma-separated values in square


brackets [ ]

Example

# Empty List

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 127

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

x = []

print("\n Empty List")

print(x)#output Empty List []

# Python program to create an empty list.

empty_list = []

print(type(empty_list))

Output

<class 'list'>

# List with single data type

y = ["takeuforward", "striver", "tuf"]

print("\n List with Same data type ")

print(y) #output List with Same data type ['takeuforward', 'striver', 'tuf']

# List with multiple data types

z = ["takeuforward", 8.90, 7, 9+899j, ["tuf", "striver"]]

print("\n List with multiple data types")

print(z) #output List with multiple data types

[‘takeuforward’, 8.9, 7, (9+899j), [‘tuf’, ‘striver’]]

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 128

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

4.1.1 List operations

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 129

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

4.1.2 List slices

 List slicing is an operation that extracts a subset of elements from an list


and packages them as another list

Syntax

Listname[start:stop]

Listname[start:stop:steps]

 default start value is 0


 default stop value is n-1
 [:] this will print the entire list
 [2:2] this will create a empty slice

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 130

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

4.1.3 List methods

 Methods used in lists are used to manipulate the data quickly


 These methods work only on lists
 They do not work on the other sequence types that are not mutable

Syntax

list [Link] name( element/index/list)

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 131

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

4.1.4 List loop

List using For Loop

 The for loop in Python is used to iterate over a sequence (list, tuple, string)
or other iterable objects
 Iterating over a sequence is called traversal

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 132

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 Loop continues until we reach the last item in the sequence


 The body of for loop is separated from the rest of the code using
indentation

Syntax

for val in sequence:

List using While loop

 The while loop in Python is used to iterate over a block of code as long as
the test expression (condition) is true
 When the condition is tested and the result is false, the loop body will be
skipped and the first statement after the while loop will be executed

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 133

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Syntax

while (condition):

body of while

Example

a=[1,2,3,4,5]

i=0

sum=0

while i<len(a):

sum=sum+a[i]

i=i+1

print(sum)

Output

15

Infinite Loop

 A loop becomes infinite loop if the condition given never becomes false
 It keeps on running. Such loops are called infinite loop

Example

a=1

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 134

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

while (a==1):

n=int(input("enter the number"))

print("you entered:" , n)

Output

Enter the number 10

you entered:10

Enter the number 12

you entered:12

Enter the number 16

you entered:16

4.1.5 Mutability

 Lists are mutable. (can be changed)


 In Python, mutability refers to the ability of an object to be changed or
modified after it is created

Appending or Removing Elements

 You can add elements to the list using methods like append(), insert(), or
extend it with extend()
 You can remove elements with methods like remove(), pop(), or clear()

Example

my_list = [1, 2, 3]

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 135

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

my_list.append(4) # Adds 4 to the end of the list

print(my_list) # Output: [1, 2, 3, 4]

my_list.remove(2) # Removes the first occurrence of 2

print(my_list) # Output: [1, 3, 4]

Resizing Lists

Lists in Python can be resized dynamically (i.e., their length can


change).

my_list = [10, 20, 30]

my_list.append(40) # Adds a new element to the end of the list

print(my_list) # Output: [10, 20, 30, 40]

my_list.pop() # Removes the last element from the list

print(my_list) # Output: [10, 20, 30]

Nested Lists (Lists within Lists)

 Lists can also contain other lists as elements


 Lists are mutable; you can modify both the inner list and the outer list

Example

my_list = [[1, 2], [3, 4], [5, 6]]

my_list[0][0] = 10 # Modify the first element of the first nested list

print(my_list) # Output: [[10, 2], [3, 4], [5, 6]]

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 136

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Insertion without removal

 The slice A[0:0] specifies an empty range, so no elements are removed


from the list
 Instead, the elements [20, 30, 45] are inserted before the first element of
the list

4.1.6 Aliasing(copying)

 Creating a copy of a list is called aliasing


 When you create a copy both list will be having same memory location
changes in one list will affect another list
 Aliasing refers to having different names for same list values

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 137

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 In this a single list object is created and modified using the subscript
operator []
 When the first element of the list named “a” is replaced, the first element of
the list named “b” is also replaced
 This type of change is what is known as a side effect
 This happens because after the assignment b=a, the variables a andb refer
to the exact same list object
 They are aliases for the same object. This phenomenon is known as
aliasing
 To prevent aliasing, a new object can be created and the contents of the
original can be copied which is called cloning

4.1.7 Cloning

 In Python, cloning a list means creating a copy of the list so that the
original and the cloned lists are separate objects
 This allows modifications to the cloned list without affecting the original
list

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 138

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Example Using the copy()

original = [1, 2, 3, 4, 5]

cloned = [Link]()

print("Original List:", original)

print("Cloned List:", cloned)

# Modify the cloned list

cloned[0] = 100

print("After modifying cloned list:")

print("Original List:", original)

print("Cloned List:", cloned)

Output

Original List: [1, 2, 3, 4, 5]

Cloned List: [1, 2, 3, 4, 5]

After modifying cloned list:

Original List: [1, 2, 3, 4, 5]

Cloned List: [100, 2, 3, 4, 5]

Using Slicing (Shallow Copy)

 You can also create a shallow copy of a list using slicing ([:])
 This works in the same way as the copy() method, by creating a new list
object with the same elements as the original list
PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 139

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Example

original = [1, 2, 3, 4, 5]
cloned = original[:]

print("Original List:", original)


print("Cloned List:", cloned)

# Modify the cloned list


cloned[1] = 200

print("After modifying cloned list:")


print("Original List:", original)
print("Cloned List:", cloned)

Output

Original List: [1, 2, 3, 4, 5]


Cloned List: [1, 2, 3, 4, 5]
After modifying cloned list:
Original List: [1, 2, 3, 4, 5]
Cloned List: [1, 200, 3, 4, 5]

Using the list() constructor (Shallow Copy)

 The list() constructor can also be used to clone a list


 It works similarly to slicing and the copy() method

Example

original = [1, 2, 3, 4, 5]

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 140

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

cloned = list(original)

print("Original List:", original)

print("Cloned List:", cloned)

# Modify the cloned list

cloned[2] = 300

print("After modifying cloned list:")

print("Original List:", original)

print("Cloned List:", cloned)

Output

Original List: [1, 2, 3, 4, 5]

Cloned List: [1, 2, 3, 4, 5]

After modifying cloned list:

Original List: [1, 2, 3, 4, 5]

Cloned List: [1, 2, 300, 4, 5]

4.1.8 List as parameters

 In python, arguments are passed by reference


 If any changes are done in the parameter which refers within the function,
then the changes also reflects back in the calling function

Example

def remove(a):
PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 141

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

[Link](1)

a=[1,2,3,4,5]

remove(a)

print(a)

Output

[2,3,4,5]

Example

def inside(a):

for i in range(0,len(a),1):

a[i]=a[i]+10

print(“inside”,a)

a=[1,2,3,4,5]

inside(a)

print(“outside”,a)

Output

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

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

Example

def insert(a):

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 142

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

[Link](0,30)

a=[1,2,3,4,5]

insert(a)

print(a)

Output

[30, 1, 2, 3, 4, 5]

4.2 Tuples

 A tuple is same as list, except that the set of elements is enclosed in


parentheses instead of square brackets
 A tuple is an immutable list. i.e. once a tuple has been created, you can't
add elements to a tuple or remove elements from the tuple
 But tuple can be converted into list and list can be converted in to tuple
 Tuples in python is an in-built data structure
 A Tuple is a type of data container in Python which is used to store
multiple data in one variable
 It can contain elements of different data types
 Elements in a tuple are ordered and can be accessed using it's index
[Link] lists
 A tuple is basically a read-only list
 Items are separated by commas
 Tuples are faster than lists
 Tuples can be used as keys in dictionaries, while lists can't

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 143

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Operations on Tuples

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 144

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Tuple methods

4.2.1 Tuple assignment

Example

Swapping using temporary variable:

a=20

b=50

temp = a

a=b

b = temp

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 145

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

print("value after swapping is",a,b)

Output

value after swapping is 50 20

Example

Swapping using tuple assignment

a=20

b=50

(a,b)=(b,a)

print("value after swapping is",a,b)

Output

value after swapping is 50 20

Multiple assignments

 Multiple values can be assigned to multiple variables using tuple


assignment

Example

>>>(a,b,c)=(1,2,3)

>>>print(a)

>>>print(b)

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 146

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

>>>print(c)

4.2.2 Tuple as return value

 A Tuple is a comma separated sequence of items


 It is created with or without ( )
 A function can return one value
 If you want to return more than one value from a function. we can use
tuple as return value

Example

def div(a,b):

r=a%b

q=a//b

return(r,q)

a=eval(input("enter a value:"))

b=eval(input("enter b value:"))

r,q=div(a,b)

print("reminder:",r)

print("quotient:",q)

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 147

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Output

enter a value:4

enter b value:3

reminder: 1

quotient: 1

Example2

def min_max(a):

small=min(a)

big=max(a)

return(small,big)

a=[1,2,3,4,6]

small,big=min_max(a)

print("smallest:",small)

print("biggest:",big)

Output

smallest: 1

biggest: 6

4.3 Dictionaries

 A dictionary is a collection of objects that have a key and a value

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 148

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 It's similar to a hash table or an associative array in that each key stores a
single value
 It is similar to maps in other programming languages
 Each key-value pair are separated by a colon
 Each key is separated by a ‘comma’
 The data types of key and value can be different
 The keys can also have different data types
 Values can be of any data type and can be duplicated
 keys can’t be duplicated
 dictionary can be created by placing comma-separated key-value pairs in
curly braces { }
 Dictionary is an unordered collection of elements
 Keys must be immutable data type (numbers, strings, tuple)

Note: Dictionary keys are case sensitive, which means the same name with
a different case will be treated distinctly

Example

name = {'name':'allinpython','age':19,'collage':'unknown'}

print(name)

print(type(name))

Output

{‘name’: ‘allinpython’, ‘age’: 19, ‘collage’: ‘unknown’}

<class ‘dict’>

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 149

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Example

# Empty Dictonary

dict = {}

print("Empty Dictonary")

print(dict)

Output

Empty Dictonary

{}

Example

# Creating a dictionary

my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}

# Accessing values using keys

print(my_dict['name']) # Output: Alice

print(my_dict['age']) # Output: 30

print(my_dict['city']) # Output: New York

 You can also add new key-value pairs to a dictionary, modify existing
values, or delete items

# Adding a new key-value pair

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 150

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

my_dict['email'] = 'alice@[Link]'

# Modifying a value

my_dict['age'] = 31

# Deleting an item

del my_dict['city']

print(my_dict) # Output: {'name': 'Alice', 'age': 31, 'email': 'alice@[Link]'}

4.3.1 Operations on dictionary

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 151

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

4.3.2Methods in dictionary

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 152

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

4.4 Advanced list processing - list comprehension..

 List comprehension in Python is a short-hand way of creating a new list


from an existing list
 It was introduced in the Python 2.0 version
 List comprehension is a powerful technique for creating, filtering, and
transforming a given list into another list
 The obtained result is a new list that we can use immediately or store for
further processing
 The list comprehension always returns a result list

Syntax

list=[ expression for item in list if conditional]

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 153

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Example

# Create an empty list.

sq_list = []

for n in range(10):

sq = n ** 2

# Adding square values to the empty list using append() method.

sq_list.append(sq)

print(sq_list)

Output

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Example list comprehension

# This statement creates a new list that contains squares of the first 10 natural
numbers

sq_list = [n ** 2 for n in range(10)]

print(list(sq_list))

Output

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

 List comprehension is more readable than For Loop and Lambda


function

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 154

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Example

[i**2 for i in range(2,10)]

For Loop

sqr = []

for i in range(2,10):

[Link](i**2)

sqr

Lambda + Map

list(map(lambda i: i**2, range(2, 10)))

Output

[4, 9, 16, 25, 36, 49, 64, 81]

UNIT-V
[Link]
 A file is some information or data which stays in the computer storage
devices
 Python gives you easy ways to manipulate these files
 Generally files divide in two categories text file and binary file
 Text files are simple text where as the binary files contain binary data
which is only readable by computer
5.1 Text files
 Text files are human readable files which contains characters
 Python has inbuilt functions to read, write and create text files

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 155

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 Text files have end line character by default at the end of each line
 In Python, the EOL (End of Line) character is represented by the newline
character \n
 These text files are txt files
5.1.1 Basic File Operations

Opening a File

 In order to open a file we will make use of the open() function which is an
inbuilt function
 open() function creates a file object that serves as a link to a file residing
on the computer
 Specify the filename and the mode ('r' for reading, 'w' for writing, 'a' for
appending, 'b' for binary mode, etc.)

Syntax

Performing Operations

 Once the file is open, you can perform operations like reading, writing, or
manipulating the content

Closing a File

 Always close the file using the close() method to free up resources

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 156

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Writing Content

file = open('[Link]', 'w')

[Link]('Hello, this is a sample text.')

[Link]()

Reading Content

file = open('[Link]', 'r')

content = [Link]()

print(content)

[Link]()

Output

Hello, this is a sample text.

Example

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 157

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 If you open same file name again in the ‘w’ mode the old data will be
overwritten the below example

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 158

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Append mode

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 159

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

5.1.2 Format operator

 In Python, the format() operator is a powerful way to format strings


 It's commonly used to insert values into a string, making the string more
readable and dynamic
 The syntax involves placing curly braces {} in the string as placeholders
 The format() method to replace those placeholders with the

Example

Basic String Formatting

name = "Alice"

age = 30

# Using format() to insert variables into the string

formatted_string = "My name is {} and I am {} years old.".format(name,


age)

print(formatted_string)

Output

My name is Alice and I am 30 years old.

Example

Positional Formatting

 You can specify the order of arguments explicitly using positional indices

formatted_string = "My name is {0} and I am {1} years old. {0} likes
Python.".format(name, age)

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 160

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

print(formatted_string)

Output

My name is Alice and I am 30 years old. Alice likes Python.

Example

Named Arguments

 You can use named placeholders, which can make your code more
readable

formatted_string = "My name is {name} and I am {age} years


old.".format(name="Bob", age=25)

print(formatted_string)

Output

My name is Bob and I am 25 years old.

Formatting Numbers

 You can format numbers using format specifiers, like floating-point


precision, padding, and alignment

pi = 3.141592653589793

formatted_string = "Pi to 3 decimal places: {:.3f}".format(pi)

print(formatted_string)

Output

Pi to 3 decimal places: 3.142

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 161

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Alignment and Padding

 You can also align text and numbers using width specifications

formatted_string = "|{:<10}|{:^10}|{:>10}|".format("left", "center", "right")

print(formatted_string)

Output

|left | center | right|

5.2 Command line arguments

 Python allows the programmer to control the program via arguments passed
at run time, by using Command Line Arguments (CLA)
 The sys module also provides access to any command-line arguments via
[Link]
 len([Link]) is the number of command-line arguments
 To use argv, you will first have to import it (import sys)
 The first argument, [Link][0], is always the name of the program
 [Link][1] is the first argument you pass to the program
Python allows the support the CLA by using following modules
1. sys Module
2. argparse Module
sys Module
Example

# file name "[Link]"


import sys
programname=[Link][0];
arguments=[Link][1:]

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 162

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

count=len(arguments)
print(programname)
print(arguments)
print("number of arguments",count)
Output
C:\Users\Admin>[Link] 45 56
C:\Users\Admin\AppData\Local\Programs\Python\Python312\Scripts\
[Link]
['45', '56']
number of arguments 2
Example
#[Link]
import sys
print("The name of the script file: ", [Link][0])
print("Number of the command line arguments: ", len([Link]))
print("The arguments are: " , str([Link]))
argList = ["apple","banana","strawberry"]
i = 0;
for cmd in [Link] :
print("Argument[", i, "] = ",cmd)
i=i+1
Run the script with the command line argument as shown below

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 163

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Output

argparse Module
 argparse is a powerful library for creating user-friendly command-line
interfaces
 argparse module is part of Python's standard library just like [Link]
 import the argparse module
 create the parser
 add arguments
 parse the arguments
CommandLineArgParser_02.py
import argparse
# Create the argument parser
parser = [Link](description="A script that takes
exactly three arguments")
# Add arguments to the parser
parser.add_argument("arg1", help="First argument")
parser.add_argument("arg2", help="Second argument")
parser.add_argument("arg3", help="Third argument")

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 164

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

# Parse the command line arguments


args = parser.parse_args()
# Access the parsed arguments and print them
print("arg1:", args.arg1)
print("arg2:", args.arg2)
print("arg3:", args.arg3)
Output
C:\> python CommandLineArgParser_02.py apple banana strawberry
arg1: apple
arg2: banana
arg3: strawberry

5.3 Error in python

Errors are nothing but mistakes in the code

 Some common examples of syntax errors include incorrect indentation,


missing colons, and misspelled keywords

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 165

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Example

# incorrect indentation

def add_numbers(x, y):

return x + y

Output

File "<ipython-input-1-7163263e7970>", line 2

return x + y

IndentationError: expected an indented block

Runtime Errors

Runtime errors, also known as exceptions

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 166

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

 These errors can occur due to a variety of reasons, such as invalid input,
incorrect data types, or unexpected behavior of the program
 Some common examples of runtime errors in Python include
ZeroDivisionError, ValueError, and TypeError

5.4 Exceptions

 Computer programs can be syntactically correct but still fail during


runtime (execution) because of some fundamental logical issues
 The errors detected during runtime are known as exceptions
 If exceptions remain unhandled, they can cause abnormal termination of
the program and hence confuse the programmer

Flowchart for exception handling process is as follows:

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 167

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Handling exceptions

Try block in Python

 Try Block: Code that might raise an exception is enclosed within the “try”
block
 Except Block: This block catches the exception and handles the exception
 Else Clause:else block is used to define a block of code to be executed if
no errors were raised
 Finally Block (Optional):If included, the final block is run whether or not
an exception occurred. Mainly, the finally block is used to release the
external resource

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 168

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Syntax

try:

statement(s)

except [exception_class]:

statement(s)

else:

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 169

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

statement(s)

finally:

statement(s)

Example

# Division by zero - causing an exception named ZeroDivisionError

numerator = 10

denominator = 0

try:

result = numerator / denominator # Attempting division by zero

print("Result:", result)

except ZeroDivisionError as e:

print("Error:", e)

print("Division by zero is not allowed!") # user-friendly message.

Output

Error: division by zero

Division by zero is not allowed!

Example

try:

x = 1/1

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 170

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

except:

print('Something went wrong')

else:

print('Nothing went wrong')

# Prints Nothing went wrong

Example

# finally clause is always executed

try:

x = 1/0

except:

print('Something went wrong')

finally:

print('Always execute this')

# Prints Something went wrong

# Prints Always execute this

Example

# Execute same block of code for multiple exceptions

try:

x = 1/0

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 171

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

except (ZeroDivisionError, ValueError):

print('ZeroDivisionError or ValueError is raised')

except:

print('Something else went wrong')

# Prints ZeroDivisionError or ValueError is raised

5.5 Modules

 A file containing Python definitions and statements is called a Python


Module
 A Module can have functions, classes, variables, and statemens
 A Module can be considered similar to a code library
 In python, a piece of code in a module can be inherited to other module
using the "import" keyword
 A module is basically a bunch of related code saved in a file with the
extension .py

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 172

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Example

# simple_math.py

def add(a, b):

return a + b

def substract(a, b):

return a – b

# [Link]

from simple_math import add, substract

print(add(100, 50))

# output: 150

print(substract(100, 50))

# output:50

 In above code we have created a module called "simple_math.py" and


imported it's functions in the other module "[Link]" and used them
 In python source code we can find many reusable modules like os, math,
collections, etc.

Example

# [Link]

def welcome_message(course):

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 173

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

print("Thank you for subscribing to our " + course + " course. You will get
all the details in an email shortly.")

import welcome

welcome.welcome_message ("Python Essentials")

Output

Thank you for subscribing to our Python Essentials course. You will get all the
details in an email shortly

from welcome import welcome_message

welcome_message ("Python Essentials")

Output

Thank you for subscribing to our Python Essentials course. You will get all the
details in an email shortly.

Example

>>>import sys

>>>[Link]

Output

['C:/Users/Admin/Desktop', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\
Python\\Python312\\Lib\\idlelib', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\
Python\\Python312\\[Link]', 'C:\\Users\\Admin\\AppData\\Local\\
Programs\\Python\\Python312\\Lib', 'C:\\Users\\Admin\\AppData\\Local\\
Programs\\Python\\Python312\\DLLs', 'C:\\Users\\Admin\\AppData\\Local\\

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 174

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Programs\\Python\\Python312', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\
Python\\Python312\\Lib\\site-packages']

Example

>>>import platform

>>>x = [Link]()

>>>print(x) #output Windows

5.6 Packages in python

 Packages in Python are similar to directories or folders


 Just like a directory that can contain subdirectories and folders and sub-
folders
 A Python package can have sub-packages and modules (modules are
similar to files, they have .py extension)
 Each package should contain a file named __init__.py. This file usually
includes the initialization code for the corresponding package
 This file can be empty or may contain initialization code that executes
when the package is imported
 Subdirectories within the package can also be considered subpackages,
and they, too, must contain an __init__.py file to be recognized as
packages
 Here's an example of the my_model package with three sub-packages:
training, submission, and metrics

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 175

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

To access code from a Python package, you can either import the entire
package or its specific modules and sub-packages

Import the whole package with import my_model;

Import the metrics sub-package with import my_model.metrics;

Import the [Link] module with either of these code snippets:

import my_model.[Link]

# or

from my_model.metrics import precision

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 176

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Popular Python Standard Library Packages

 Python comes with a rich standard library that includes many built-in
packages, providing a wide range of functionalities
 os: For interacting with the operating system
 math: For mathematical operations and functions
 random: For generating random numbers and choices
 datetime: For working with dates and times
 json: For encoding and decoding JSON data

Math Library (math): Provides a range of mathematical operations and

Functions

Example

>>>import math

>>>x = [Link](64)

>>>print(x)# output 8.0

Random Library (random): Allows for generating random numbers and


performing random selections

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 177

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

Example

#First time
>>>import random
>>>rand_num = [Link](1, 10)
>>>print(rand_num) # 4

#Second time
>>>import random
>>>rand_num = [Link](1, 10)
>>>print(rand_num) # 8

OS Library (os): Provides a way to interact with the operating system, allowing
you to perform tasks like navigating directories, working with files, and
executing system commands

Example

>>>import os

>>>current_dir = [Link]()

>>>print(current_dir)

Output

C:\Users\Admin\AppData\Local\Programs\Python\Python312

Datetime Library (datetime): Offers classes for manipulating dates and times

Example

>>>import datetime

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 178

Downloaded by Saro Saro (sarojini1341@[Link])


lOMoARcPSD|50662627

[Link]/HOD/AI&DS/M.G.R COLLEGE/HSOUR

>>>x = [Link]()

>>>print(x) # 2024-11-23 [Link].483802

JSON Library (json): Facilitates the encoding and decoding of JSON data

>>>import json

>>data = {'name': 'Alice', 'age': 30}

>>>json_data = [Link](data) # Converts a Python dictionary to a


JSON string

>>>print(json_data)# {"name": "Alice", "age": 30}

Python Third-Party Packages

 These packages can be installed using package managers like pip


 NumPy
 Pandas
 Matplotlib
 Seaborn
 scikit-learn
 Requests
 urllib3
 NLTK
 Pillow
 Pytest

PERIYAR UNIVERSITY/2023 REGULATIONS/PYTHON/SEM-II Page 179

Downloaded by Saro Saro (sarojini1341@[Link])

You might also like