0% found this document useful (0 votes)
18 views116 pages

Python Programming Course Overview

This document outlines a skill enhancement course on Python programming, covering its history, installation of Anaconda and Jupyter Notebook, and fundamental programming concepts such as identifiers, keywords, data types, control flow statements, and operators. It includes sample experiments to practice programming skills and provides detailed instructions for installing necessary software. The document serves as a comprehensive guide for beginners to understand and utilize Python effectively.
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)
18 views116 pages

Python Programming Course Overview

This document outlines a skill enhancement course on Python programming, covering its history, installation of Anaconda and Jupyter Notebook, and fundamental programming concepts such as identifiers, keywords, data types, control flow statements, and operators. It includes sample experiments to practice programming skills and provides detailed instructions for installing necessary software. The document serves as a comprehensive guide for beginners to understand and utilize Python effectively.
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

PYTHON PROGRAMMING

(SKILL ENHANCEMENT COURSE)

UNIT- 1
History of Python Programming Language, Thrust Areas of Python, Installing Anaconda
Python Distribution, Installing and Using Jupyter Notebook.
Parts of Python Programming Language: Identifiers, Keywords, Statements and Expressions,
Variables, Operators, Precedence and Associativity, Data Types, Indentation, Comments,
Reading Input, Print Output, Type Conversions, the type () Function and Is Operator, Dynamic
and Strongly Typed Language.
Control Flow Statements: if statement, if-else statement, if...elif…else, Nested if statement,
while Loop, for Loop, continue and break Statements, Catching Exceptions Using try and
except Statement.

Sample Experiments:
1. Write a program to find the largest element among three Numbers.
2. Write a Program to display all prime numbers within an interval
3. Write a program to swap two numbers without using a temporary variable.
4. Demonstrate the following Operators in Python with suitable examples.
i) Arithmetic Operators ii) Relational Operators iii) Assignment Operators
iv) Logical Operators v) Bit wise Operators vi) Ternary Operator vii) Membership Operators
viii) Identity Operators
5. Write a program to add and multiply complex numbers
6. Write a program to print multiplication table of a given number.
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23
S
Learning Material
1.1 History of Python Programming Language
 Python was first developed by Guido van Rossum in the late 80’s and early 90’s at the
National Research Institute for Mathematics and Computer Science in the Netherlands.
 It has been derived from many languages such as ABC, Modula-3, C, C++, Algol-68,
SmallTalk,UNIX shell and other scripting languages.
 Since early 90’s Python has been improved tremendously. Its version 1.0 was released
in1991, which introduced several new functional programming tools.
 While version 2.0 included list comprehension was released in 2000 by the
BeOpenPythonLabs team.
 Python 2.7 which will be supported till 2020

Python continues to evolve with regular releases (e.g., Python 3.10, 3.11) that introduce new
 features, optimizations, and improvements.

1.2 Thrust Areas of Python


 Data Science
 Automation
 Application Development
 AI & Machine Learning
 Audio/Video Applications
 Console Applications

1.3 Installing Anaconda Python Distribution

Steps to install Anaconda Python Distribution


1. Download the Anaconda installer.
2. Go to your Downloads folder and double-click the installer to launch.
3. Click Next.
4. Read the licensing terms and click I Agree.
5. It is recommended that you install for Just Me, which will install Anaconda Distribution to
just the current user account.
6. Click Next.

Dhanekula Institute of Engineering & Technology Dept. Of CSE A.Y: 2024-25 2


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23
S
7. Select a destination folder to install Anaconda and click Next.

8. Choose whether to add Anaconda to your PATH environment variable or register Anaconda

as your default Python.


9. Click Install. If you want to watch the packages Anaconda is installing, click Show Details.
10. Click Next Or click Continue to proceed.

11. After a successful installation you will see the “Thanks for installing Anaconda” dialog box:

Dhanekula Institute of Engineering & Technology Dept. Of CSE A.Y: 2024-25 3


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23
S
12. Click the Finish button.

1.4 Installing and Using Jupyter Notebook


Steps to install Jupyter Notebook
1. Install Anaconda
2. Type ‘anaconda prompt’ in search box and click on the icon indicated below.

3. You will see that a command window opens. Just wait for few seconds until you see
a file location (something like shown below)

4. Type “jupyter notebook” in the command prompt and then Press Enter

5. In few seconds, you will see that your command is executed as shown below.

Dhanekula Institute of Engineering & Technology Dept. Of CSE A.Y: 2024-25 4


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23
S

Dhanekula Institute of Engineering & Technology Dept. Of CSE A.Y: 2024-25 5


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

6. At the same time, you will also see that your browser opens showing Jupyter
Notebook Interface. Click on “New” located at upper right corner if you wish
to open Jupyter Notebook.

7. This will open Jupyter Notebook in an another tab as shown below

8. Now you can start creating your new notebook.


Using Jupyter Notebook
 The Jupyter Notebook is an open-source web application that allows you to create
and share documents that contain live code, equations, visualizations, and
narrative text.
 Uses include data cleaning and transformation, numerical simulation, statistical
modeling, data visualization, machine learning, and much more.
 Jupyter has support for over 40 different programming languages and Python is
one of them.
 Python is a requirement (Python 3.3 or greater, or Python 2.7) for installing the
Jupyter Notebook itself.
Steps to use Jupyter Notebook
1. create a new notebook by clicking on the new button at the top right corner.

2. The web page will appear like this

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 6


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

3. After successfully installing and creating a notebook in Jupyter Notebook. Jupyter


notebook provides a cell for writing code in it. The type of code depends on the type
of notebook you created.

4. To run a code either click the run button or press shift ⇧ + enter ⏎ after selecting the
cell you want to execute. After writing the above code in the jupyter notebook, the
output was:

1.5 Parts of Python Programming Language


1.5.1 Identifiers
Identifiers are names given to identify something. This something can be a variable,
function, class, module or other object. For naming any identifier, there are some basic
rules like:
 The first character of an identifier must be an underscore ('_') or a letter (upper or
lowercase).
 The rest of the identifier name can be underscores ('_'), letters (upper or lowercase), or
digits (0-9).
 Identifier names are case-sensitive. For example, myvar and myVar are not the same.
 Punctuation characters such as @, $, and % are not allowed within identifiers.
 Examples of valid identifier names are sum, __my_var, num1, r, var_20, First, etc.
 Examples of invalid identifier names are 1num, my-var, %check, Basic Sal, H#R&A,
etc.,

1.5.2 Keywords
 Keywords are the reserved words in Python. We cannot use a keyword as variable
name, function name or any other identifier.
 Here's a list of all keywords in Python Programming.
 There are 33 keywords in Python [Link] number can vary slightly in course of time.

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 7


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

 All the keywords except True, False and None are in lowercase and they must be
written as it is. The list of all the keywords are given below.

Keywords in Python Programming


Language

False class finally is return

None continue for lambda try

True def from nonlocal while

and del global not with

as elif if or yield

assert else import pass

break except in raise

1.5.3 Statements and Expressions


 A statement is an instruction that the Python interpreter can execute. Some other
kinds of statements are while statements, for statements, if statements,
and import statements.
 An expression is a combination of values, variables, operators, and calls to
functions. Expressions need to be evaluated.
 An expression is a combination of operators and operands that is interpreted to
produce some other value.
 In any programming language, an expression is evaluated as per the precedence of
its operators. So that if there is more than one operator in an expression, their
precedence decides which operation will be performed first. .
1.5.4 Variables
 Variable means its value can vary. You can store any piece of information in a
variable.
 Variables are nothing but just parts of your computer’s memory where information is
stored. To identify a variable easily, each variable is given an appropriate name.
1.5.5 Operators
 Operators are special symbols in Python that carry out arithmetic or logical
computation. The value that the operator operates on is called the operand.
 For example:
2+3
5
Here, + is the operator that performs addition. 2 and 3 are the operands and 5 is the
output of the operation.

Python supports the following operators

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 8


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

 Arithmetic operators
 Comparison (Relational) operators
 Unary Operators
 Bitwise operators
 Shift Operators
 Logical Operators
 Membership and Identity Operators
 Assignment operators
Arithmetic Operators
 Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication etc.
 This operator will work on two operands.
 Example: If a=100 and b=200 then look at the table below, to see the result of
arithmetic operations.

Comparision (Relational) Operators


 A Relational or Comparison operator checks the relationship between two operands.
If the relation is true, it returns 1; if the relation is false, it returns value 0
 For Example assuming a=100 and b=2000,we can use the comparison operators on
them as specified in the following table.

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 9


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

Unary Operator
 Unary operators act on single operands. Python supports unary minus operator.
 Unary minus operator is strikingly different from the arithmetic operator that operates
on two operands and subtracts the second operand from the first operand.
 When an operand is preceded by a minus sign, the unary operator negates its value.
 For example, if a number is positive, it becomes negative when preceded with a unary
minus operator. Similarly, if the number is negative, it becomes positive after
applying the unary minus operator. Consider the given example.
b = 10 a = -(b)
 The result of this expression, is a = -10, because variable b has a positive value. After
applying unary minus operator (-) on the operand b, the value becomes -10, which
indicates it as a negative value.

Bitwise Operators
 As the name suggests, bitwise operators perform operations at the bit level.
 These operators include bitwise AND, bitwise OR, bitwise XOR, and shift operators.
 Bitwise operators expect their operands to be of integers and treat them as a sequence
of bits.
 The truth tables of these bitwise operators are given below.

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 10


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

Example: If a=60 and b=13 then look at the table below, to see the result of Bitwise
operations.

Operator Description Example

& Operator copies a bit to the result if it exists in (a & b) =12


Binary AND both operands (means 0000 1100)

| It copies a bit if it exists in either operand. (a | b) = 61 (means


Binary OR 0011 1101)

^ It copies the bit if it is set in one operand but (a ^ b) = 49


Binary XOR not both. (means 0011 0001)

~ (~a ) = -61
Binary Ones (means 1100 0011 in
Complement It is unary and has the effect of 'flipping' bits. 2's complement form
due to a signed binary
number.

<< The left operands value is moved left by the a << 2 = 240
Binary Left Shift number of bits specified by the right operand. (means 1111 0000)

>> The left operands value is moved right by the


a >> 2 = 15 (means
Binary Right number of bits specified by the right operand.
0000 1111)
Shift

Shift Operators
 Python supports two bitwise shift operators. They are shift left (<<) and shift right
(>>).
 These operations are used to shift bits to the left or to the right. The syntax for a shift
operation can be given as follows:

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 11


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

Logical Operators

 Logical operators are used to simultaneously evaluate two conditions or expressions


with relational operators.
 Logical AND (and) If expressions on both the sides (left and right side) of the logical
operator are true, then the whole expression is true.
o For example, If we have an expression (a>b) and (b>c), then the whole
expression is true only if both expressions are true. That is, if b is greater than
a and c.
 Logical OR (or) operator is used to simultaneously evaluate two conditions or
expressions with relational operators. If one or both the expressions of the logical
operator is true, then the whole expression is true.
For example, If we have an expression (a>b) or (b>c), then the whole expression is true if
either b is greater than a or b is greater than c.
 Logical NOT (not) operator takes a single expression and negates the value of the
expression. Logical NOT produces a zero if the expression evaluates to a non-zero
value and produces a 1 if the expression produces a zero. In other words, it just
reverses the value of the expression.
o For example, a = 10; b = not a; Now, the value of b = 0.

Membership and Identity Operators


Membership Operator

 Python supports two types of membership operators–in and not in. These operators,
test for membership in a sequence such as strings, lists, or tuples.

 in Operator: The operator returns true if a variable is found in the specified sequence
and false otherwise. For example, a in nums returns 1, if a is a member of nums.
 not in Operator: The operator returns true if a variable is not found in the specified
sequence and false otherwise. For example, a not in nums returns 1, if a is not a
member of nums.

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 12


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

Identity Operators

 is Operator: Returns true if operands or values on both sides of the operator point to
the same object and false otherwise. For example, if a is b returns 1, if id(a) is same as
id(b).
 is not Operator: Returns true if operands or values on both sides of the operator does
not point to the same object and false otherwise. For example, if a is not b returns 1, if
id(a) is not same as id(b).

Assignment Operators
 Assignment operators are used in Python to assign values to variables.
 a = 5 is a simple assignment operator that assigns the value 5 on the right to the
variable a on the left.
 There are various compound operators in Python like a += 5 that adds to the variable
and later assigns the same. It is equivalent to a = a + 5.

Assignment operators in
Python

Operator Example Equivatent to

= x=5 x=5

+= x += 5 x=x+5

-= x -= 5 x=x-5

*= x *= 5 x=x*5

/= x /= 5 x=x/5

%= x %= 5 x=x%5

//= x //= 5 x = x // 5

**= x **= 5 x = x ** 5

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 13


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

&= x &= 5 x=x&5

|= x |= 5 x=x|5

^= x ^= 5 x=x^5

>>= x >>= 5 x = x >> 5

<<= x <<= 5 x = x << 5

1.5.6 Precedence and Associativity


In Python, operators have different levels of precedence, which determine the order in
which they are evaluated. When multiple operators are present in an expression, the ones
with higher precedence are evaluated first. In the case of operators with the same
precedence, their associativity comes into play, determining the order of evaluation.
Precedence Operators Description Associativity

1 () Parentheses Left to right

2 ** Exponentiation Right to left

3 +x, -x, ~x Positive, negative, bitwise NOT Right to left

Multiplication, matrix, division,


4 *, @, /, //, % Left to right
floor division, remainder

5 +, – Addition and subtraction Left to right

6 <<, >> Shifts Left to right

7 & Bitwise AND Left to right

8 ^ Bitwise XOR Left to right

9 | Bitwise OR Left to right

in, not in, is, is


Comparisons, membership tests,
10 not, <, <=, >, >=, ! Left to Right
identity tests
=, ==

11 := Assignment expression Right to left

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 14


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

1.5.7 Data Types


 The variables can hold values of different type called Data Type.
 Data type is a set of values and the allowable operations on those values.
 Python has a great set of useful data types. Python's data types are built in the core of
the language. They are easy to use and straightforward.
 Example a person age is stored in a number ,his name is made only with characters,
and his address is made with mixture of numbers and characters.
 Python ha various standard data types to define the operations possible on them and
storage method for each of them.
 Python supports the following five standard data types
[Link]
[Link]
[Link]
[Link]
[Link]
The Following Diagram shows the classification of Python Data Types.

1.5.8 Indentation
 Indentation refers to the spaces at the beginning of a code line.
 Where in other programming languages the indentation in code is for readability only,
the indentation in Python is very important.
 Python uses indentation to indicate a block of code.
 Python indentation is a way of telling a Python interpreter that the group of statements
belongs to a particular block of code.
Example
if 5 > 2:
print("Five is greater than two!")

output: Five is greater than two!

 Python will give you an error if you skip the indentation

Example

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 15


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

if 5 > 2:
print("Five is greater than two!")

output:

print("Five is greater than two!")


^
IndentationError: expected an indented block

1.5.9 Comments
 Python has commenting capability for the purpose of in-code documentation.
 Comments can be used to explain Python code.

 Comments can be used to make the code more readable.

 Comments can be used to prevent execution when testing code.

 Comments start with a symbol # , and Python will render the rest of the line as a
comment.
 Python does not really have a syntax for multiline comments.

 To add a multiline comment you could insert a # for each line.

Example
#This is a comment.
print("Hello, World!")
Output: Hello, World!
1.5.10 Reading Input
 In Python, we use the input() function to read input from the user.
 Whatever you enter as input, the input function converts it into a string. If you
enter an integer value still input() function converts it into a string.
Syntax: input(prompt)
Example:
name = input('What is your name?\n')
print(name)
output:
What is your name?
Ram
Ram
1.5.11 Print Output
 The print() function prints the specified message to the screen, or other standard
output device.
 The message can be a string, or any other object, the object will be converted into
a string before written to the screen.

Examples:

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 16


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

1. print("Hello World")
2. print("Hello", "how are you?")
3. x = ("apple", "banana", "cherry")
print(x)
1.5.12 Type Conversions
 Python defines type conversion functions to directly convert one data type to
another.
 There are two types of Type Conversion in Python:
1. Implicit Type Conversion
 The Python interpreter automatically performs Implicit Type Conversion.
 It converts one data type to another without any user involvement.
 Python prevents Implicit Type Conversion from losing data.

2. Explicit Type Conversion


 In Explicit Type Conversion in Python, the data type is manually
changed by the user as per their requirement.
 With explicit type conversion, there is a risk of data loss since we are
forcing an expression to be changed in some specific data type.
Example
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)

1.5.13 type ( ) Function and Is Operator


type ( ) Function
 The type() function returns the type of the specified object
 Syntax: type(object, bases, dict)
Example
x = 10
print(type(x))
output: <class 'int'>
Is Operator
 Python identity operators (is, is not) are used to compare objects based on their
identity.
 When the variables on either side of an operator point at the exact same object,
the “is” operator's evaluation is true. Otherwise, it is false.
 For example, if a is b returns 1, if id(a) is same as id(b).

1.5.14 Dynamic and Strongly Typed Language


 Python is both a strongly typed and a dynamically typed language.
 Python is a dynamically typed language. It doesn’t know about the type of the
variable until the code is run.
 Dynamic typing means that the type of the variable is determined only during

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 17


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

runtime.
 Strong typing means that variables do have a type and that the type matters when
performing operations on a variable.
1.6 Control Flow Statements
 A control Flow statement is a statement that determines the control flow of a set of
instructions, i.e., it decides the sequence in which the instructions in a program are to be
executed.
 Selection/Conditional Control: To execute only a selected set of statements.
 Iterative Control: To execute a set of statements repeatedly.
 Un-conditional Control:

Selection /Conditional Branching Statements:


 Python language supports different types of conditional branching statements which are
as follows:
 if Statement
 if-else Statement
 if-elif-else statement
 Nested if statement
1.6.1 if Statement:
 An if statement is a selection control statement which is based on the value of a given
Boolean Expression.
Syntax:
if test_expression:
statement 1
.....
statement n

statement x

 if structure may include 1 or n statements enclosed within if block.


 First, test expression is evaluated. If the test expression is true, the statement of if
block (statement 1 to n) are executed, otherwise these statements will be skipped and
the execution will jump to statement x.
Flow chart:

Example:

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 18


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

1.6.2 if else Statement:


 The if .... else statement executes a group of statements when a test expression is true;
otherwise, it will execute another group of statements.
Syntax:
if (test expression):
statement_block 1

else:

statement_block 2

statement x

 If the condition is true, then it will execute statement block 1 and if the condition is
false then it will execute statement block 2.
Flowchart:

Example: Write a program to determine whether a person is eligible to vote:

1.6.3 if-elif-else Statement :


 Python supports if-elif-else statements to test additional conditions apart from the
initial test expression.
 The if-elif-else construct works in the same way as a usual if-else statement.
 If-elif-else construct is also known as nested-if construct.

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 19


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

 A series of if and elif statements have a final else block, which is executed if none of
the if or elif expressions is True.
Syntax:
if (test expression 1):
statement block1
elif (test expression 2):
statement block2
. . . . . . . . . . . . . . ..
elif( test expression N):
statement block N
else:
statement block X
Flowchart:

Program: To test whether a number entered by the user is negative, positive, or zero

1.6.4 Nested if Statements:


 A statement that contains other statements is called a compound statement.
 To perform more complex checks, if statements can be nested, that is, can be placed
one inside the other.
 In such a case, the inner if statement is the statement part of the outer one.
 Nested if statements are used to check if more than one conditions are satisfied.
 if statements can be nested resulting in multi-way selection.

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 20


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

Example: Program that prompts the user to enter a number and then print the interval

Looping Statements/Iterative Structure:


 Iterative statements are decision control statements that are used to repeat the execution
of a list of statements.
 Python supports 2 types of iterative statements-while loop and for loop.

1.6.5 while Loop:


 The While loop provides a mechanism to repeat one or more statements while a
particular condition is TRUE.
Syntax:
Statement x
while (condition):
Statement block

Statement y

 In while loop, the condition is tested before any of the statements in the statement
block is executed.
 If the condition is TRUE, only then the statements will be executed otherwise if the
condition is False, the control will jump to statement y, that is the immediate
statement outside the while loop block.

Flowchart:

Example: Program to print first 10 numbers using a while loop


i=0
while(i<=10):
print(i, end=” “)

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 21


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

i=i+1

Output: 0 1 2 3 4 5 6 7 8 9 10

1.6.6 for Loop:


 For loop provides a mechanism to repeat a task until a particular condition is True. It
is usually known as a determinate or definite loop because the programmer knows
exactly how many times the loop will repeat.
 The for...in statement is a looping statement used in Python to iterate over a sequence
of objects.
Syntax:
for loop_control_var in sequence:
statement block

Flowchart:

range() Function :

o The range( ) function is a built-in function in Python that is used to iterate over
a sequence of numbers.
o Syntax:
 range(beg, end, [step])
o The range( ) produces a sequence of numbers starting with beg (inclusive) and
ending with one less than the number end.
o The step argument is option (that is why it is placed in brackets). By default,
every number in the range is incremented by 1 but we can specify a different
increment using step. It can be both negative and positive, but not zero.

Example: Program to print first n numbers using the range() in a for loop

o If range( ) function is given a single argument, it produces an object with values


from 0 to argument-1. For example: range(10) is equal to writing range(0, 10).

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 22


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

o If range( ) is called with two arguments, it produces values from the first to the
second. For example, range(0, 10) gives 0-9.
o If range( ) has three arguments then the third argument specifies the interval of
the sequence produced. In this case, the third argument must be an integer. For
example, range(1, 20, 3) gives 1, 4, 7, 10, 13, 16, 19.

Example:

1.6.7 continue
 The continue statement can only appear in the body of a loop.
 When the compiler encounters a continue statement then the rest of the statements in
the loop are skipped and the control is unconditionally transferred to the loop-
continuation portion of the nearest enclosing loop.
Syntax:
Continue

Example: Program to demonstrate continue statement

 Note that the code is meant to print numbers from 0 to [Link] as soon as i becomes
equal to 5, the continue statement is encountered, so rest of the statements in the loop
are skipped. In the output, 5 is missing as continue caused early increment of i and
skipping of statement that printed the value of i on screen.
 Below figure illustrates the use of continue statement in loops.

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 23


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

 It can be concluded that the continue statement is somewhat the opposite of the break
statement. It forces the next iteration of the loop to take place, skipping any code in
between itself and the test condition of the loop.
 The continue statement is usually used to restart a statement sequence when an error
occurs.
1.6.8 break
 The break statement is used to terminate the execution of the nearest enclosing loop
in which it appears.
 The break statement is widely used with for loop and while loop.
 When compiler encounters a break statement, the control passes to the statement that
follows the loop in which the break statement appears.
Syntax:
break
Example: Program to demonstrate the break statement

 Above code is meant to print first 10 numbers using a while loop, but it will actually
print only numbers from 0 to 4. As soon as i becomes equal to 5, the break statement
is executed and the control jumps to the following while loop.
 Hence, the break statement is used to exit a loop from any point with in its body, by
passing its normal termination expression. Below, Figure shows the transfer of control
when the break statement is encountered.

1.6.9 Catching Exceptions Using try and except Statement


 Try and Except statement is used to handle the exceptions in python code.
 The try block is used to check some code for errors i.e the code inside the try block
will execute when there is no error in the program.

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 24


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

 Whereas the code inside the except block will execute whenever the program
encounters some error in the preceding try block.
 The try contains statements that can raise exceptions, whereas the except clause
contains statements that handle the exception.
Syntax:
try:
# Some Code
except:
# Executed if error in the try block
Example:
a=[1,2,3]
try:
print(a[10])
except IndexError:
print(“You are not giving valid index”)
output:-
You are not giving valid index

Sample Experiments:
1. Write a program to find the largest element among three Numbers.
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
num3 = input("Enter third number: ")
if (num1 >= num2) and (num1 >= num3):
largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3
print("The largest number is", largest)
output:

2. Write a Program to display all prime numbers within an interval.


a = int(input ("Enter the Lowest Range Value: "))
b = int(input ("Enter the Upper Range Value: "))
print ("The Prime Numbers in the range are: ")
for number in range (a, b + 1):
if number > 1:
for i in range (2, number):
if (number % i) == 0:
break
else:

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 25


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

print (number)
output:

3. Write a program to swap two numbers without using a temporary variable.


x=5
y = 10
x, y = y, x
print("x =", x)
print("y =", y)
output:
x = 10
y=5
4. Demonstrate the following Operators in Python with suitable examples.
i) Arithmetic Operators ii) Relational Operators iii) Assignment Operators
iv) Logical Operators v) Bit wise Operators vi) Ternary Operator vii) Membership
Operators viii) Identity Operators.
i) Arithmetic Operators
a = int(input("enter a"))
b = int(input("enter b"))
# addition
print ('Sum: ', a + b)
# subtraction
print ('Subtraction: ', a - b)
# multiplication
print ('Multiplication: ', a * b)
# division
print ('Division: ', a / b)
# floor division
print ('Floor Division: ', a // b)
# modulo
print ('Modulo: ', a % b)
# a to the power b
print ('Power: ', a ** b)
output:
enter a 10
enter b 5
Sum: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
Floor Division: 2
Modulo: 0
Power: 100000

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 26


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

ii) Relational Operators


a = int(input("enter a"))
b = int(input("enter b"))
print('a == b =', a == b)
print('a != b =', a != b)
print('a > b =', a > b)
print('a < b =', a < b)
print('a >= b =', a >= b)
print('a <= b =', a <= b)
output:
enter a 5
enter b 8
a == b = False
a != b = True
a > b = False
a < b = True
a >= b = False
a <= b = True
iii) Assignment Operators
a = 10
b=5
a += b
print(a)
output:
15
iv) Logical Operators
Program 1
a=5
b=6
print((a > 2) and (b >= 6))
output:
True
Program 2
# logical AND
print(True and True)
print(True and False)
# logical OR
print(True or False)
# logical NOT
print(not True)
output:
True
False
True
False
v) Bit wise Operators
a = int(input("enter a"))
b = int(input("enter b"))

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 27


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

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


print("a | b =", a | b)
print("a ^ b =", a ^ b)
print("~a =", ~a)
print("a << 1 =", a << 1)
print("b << 1 =", b << 1)
output:
enter a 5
enter b 10
a&b=0
a | b = 15
a ^ b = 15
~a = -6
a << 1 = 10
b << 1 = 20
vi) Ternary Operator
num1 = 30
num2 = 50
max = num1 if num1 > num2 else num2
print(max)
output:
50
vii) Membership Operators
message = 'Hello world'
print('H' in message) # prints True
print('hello' not in message) # prints True
output:
True
True
viii) Identity Operators
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]
print(x1 is not y1)
print(x2 is y2)
print(x3 is y3)
output:
False
True
False

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 28


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

[Link] a program to add and multiply complex numbers


c1=(4+3j)
c2=(3-7j)
print("Addition of two complex numbers : ",c1+c2)
print("Multiplication of two complex numbers : ",c1*c2)
output:
Addition of two complex numbers : (7-4j)
Multiplication of two complex numbers : (33-19j)
6. Write a program to print multiplication table of a given number.
num = 5
for i in range(1, 11):
print(num, 'x', i, '=', num*i)
output:
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 29


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

UNIT-II

Functions: Built-In Functions, Commonly Used Modules, Function Definition and


Calling the function, return Statement and void Function, Scope and Lifetime of
Variables, Default Parameters, Keyword Arguments, *args and **kwargs, Command
Line Arguments.

Strings: Creating and Storing Strings, Basic String Operations, Accessing Characters
in String by Index Number, String Slicing and Joining, String Methods, Formatting
[Link]: Creating Lists, Basic List Operations, Indexing and Slicing in Lists, Built-
In Functions Used on Lists, List Methods, del Statement.

Sample Experiments:
1. Write a program to define a function with multiple return values.
2. Write a program to define a function using default arguments.
3. Write a program to find the length of the string without using any library functions.
4. Write a program to check if the substring is present in a given string or not.
5. Write a program to perform the given operations on a list:
i. Addition ii. Insertion iii. slicing
6. Write a program to perform any 5 built-in functions by taking any list.

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 30


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

i) Introduction to Function

 A function in Python is a reusable block of code that performs a specific


task. Functions help to organize code into smaller, modular chunks, which
can be used and reused to perform operations within a program.
 This promotes code reuse, readability, and maintainability.

Basic Structure of a Function

 A function in Python is defined using the `def` keyword, followed by the function name,
parentheses `()`, and a colon `:`.
 Inside the parentheses, you can specify parameters that the function can accept.
 The code block within the function is indented.

**Syntax:**

def function_name(parameters):
# Code block
return result

**Example:**

def greet(name):
print(f"Hello, {name}!")

 In this example, `greet` is a function that takes one parameter, `name`, and
prints a greeting message.

Uses of Functions in Python

1. **Code Reusability:**
 Functions allow you to reuse code. Instead of writing the same code multiple
times, you can define a function once and call it whenever needed.

**Example:**
def add(a, b):
return a + b

result = add(3, 5)
print(result) # Output: 8
```

2. **Modularity:**
 Functions help to break down complex problems into smaller, manageable
parts. Each function can focus on a single task.

**Example:**
def calculate_area(length, width):
return length * width

def print_area(length, width):


area = calculate_area(length, width)
print(f"The area is {area}")

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 31


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

print_area(5, 3)

3. **Improved Readability:**
 Functions with descriptive names make the code easier to understand. Each
function name gives a clear indication of what the function does.

**Example:**
def calculate_tax(income):
return income * 0.2

def print_tax(income):
tax = calculate_tax(income)
print(f"The tax on an income of {income} is {tax}")

print_tax(50000)

4. **Maintainability:**
 Functions make it easier to maintain and update code. If a change is needed,
it can be made in one place (the function) rather than multiple places in the
code.

**Example:**
def discount(price, percentage):
return price * (1 - percentage / 100)

def print_discounted_price(price, percentage):


discounted_price = discount(price, percentage)
print(f"The discounted price is {discounted_price}")

print_discounted_price(100, 10)

5. **Testing and Debugging:**


 Functions make it easier to test and debug specific parts of the code. You
can isolate functions and test them independently.

**Example:**
def is_even(number):
return number % 2 == 0

def test_is_even():
assert is_even(4) == True
assert is_even(7) == False
print("All tests passed.")

test_is_even()

ii) Built-In Functions


 Python comes with a wide array of built-in functions that can be used
without importing any additional modules.
 These functions perform various operations, including mathematical
calculations, type conversions, string manipulations, and more.

Here are some common built-in functions with simple examples:

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 32


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

1. `print()`

Prints the given message to the console.

**Example:**

print("Hello, World!") # Output: Hello, World!

2. `len()`

Returns the length of an object (string, list, tuple, etc.).

**Example:**

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

3. `type()`

Returns the type of an object.

**Example:**

print(type(5)) # Output: <class 'int'>


print(type("Hello")) # Output: <class 'str'>

4. `int()`, `float()`, `str()`

Converts a value to an integer, float, or string.

**Example:**
print(int("10")) # Output: 10
print(float("10.5")) # Output: 10.5
print(str(10)) # Output: "10"

5. `sum()`

Returns the sum of all elements in an iterable.

**Example:**

numbers = [1, 2, 3, 4, 5]
print(sum(numbers)) # Output: 15
6. `max()`, `min()`

Returns the maximum or minimum value in an iterable.

**Example:**
numbers = [1, 2, 3, 4, 5]
print(max(numbers)) # Output: 5
print(min(numbers)) # Output: 1

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 33


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

7. `abs()`

Returns the absolute value of a number.

**Example:**

print(abs(-10)) # Output: 10
print(abs(10)) # Output: 10

8. `round()`

Rounds a number to a specified number of decimal places.

**Example:**

print(round(3.14159, 2)) # Output: 3.14


print(round(3.14159)) # Output: 3

9. `sorted()`

Returns a sorted list from the given iterable.

**Example:**

numbers = [3, 1, 4, 1, 5, 9]
print(sorted(numbers)) # Output: [1, 1, 3, 4, 5, 9]

10. `enumerate()`

Returns an enumerate object, which contains pairs of index and value from the
iterable.

**Example:**

fruits = ["apple", "banana", "cherry"]


for index, fruit in enumerate(fruits):
print(index, fruit)
# Output:
# 0 apple
# 1 banana
# 2 cherry

11. `zip()`

Combines multiple iterables into tuples.

**Example:**

names = ["Alice", "Bob", "Charlie"]


ages = [25, 30, 35]
zipped = zip(names, ages)
print(list(zipped)) # Output: [('Alice', 25), ('Bob', 30), ('Charlie', 35)]

12. `map()`

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 34


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

Applies a function to all items in an iterable.

**Example:**

def square(x):
return x * x

numbers = [1, 2, 3, 4, 5]
squared_numbers = map(square, numbers)
print(list(squared_numbers)) # Output: [1, 4, 9, 16, 25]

13. `filter()`

Filters items in an iterable based on a function.

**Example:**

def is_even(x):
return x % 2 == 0

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(is_even, numbers)
print(list(even_numbers)) # Output: [2, 4, 6]

14. `all()`, `any()`

Returns `True` if all or any elements of the iterable are true.

**Example:**

```python
numbers = [0, 1, 2, 3]
print(all(numbers)) # Output: False (because 0 is False)
print(any(numbers)) # Output: True (because at least one value is True)
```

15. `range()`

Generates a sequence of numbers.

**Example:**

for i in range(5):
print(i)

# Output:
# 0
# 1
# 2
# 3
# 4

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 35


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

iii) Commonly Used Modules in Python with Examples

 Python's standard library includes a variety of modules that provide


functions and classes for performing many tasks.
 Below are some commonly used modules along with examples to illustrate
their usage.

1. `math` Module

 The `math` module provides access to mathematical functions.

**Example:**

import math

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


print([Link](5)) # Output: 120
print([Link]) # Output: 3.141592653589793

2. `datetime` Module

 The `datetime` module supplies classes for manipulating dates and times.

**Example:**

import datetime

now = [Link]()
print(now) # Output: Current date and time

today = [Link]()
print(today) # Output: Current date

new_year = [Link](2024, 1, 1)
print(new_year) # Output: 2024-01-01

3. `random` Module

 The `random` module implements pseudo-random number generators.

**Example:**

import random

print([Link](1, 10)) # Output: Random integer between 1 and 10


print([Link](['a', 'b', 'c', 'd'])) # Output: Randomly chosen element from
list

numbers = [1, 2, 3, 4, 5]
[Link](numbers)
print(numbers) # Output: Shuffled list

4. `os` Module

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 36


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

The `os` module provides a way of using operating system-dependent


functionality.

**Example:**

import os

print([Link]) # Output: Name of the operating system (e.g., 'posix', 'nt')

current_directory = [Link]()
print(current_directory) # Output: Current working directory

[Link]('new_directory') # Creates a new directory named 'new_directory'

5. `sys` Module

 The `sys` module provides access to some variables used or maintained by


the interpreter and functions that interact strongly with the interpreter.

**Example:**

import sys

print([Link]) # Output: Python version

print([Link]) # Output: List of directories that the interpreter searches for


modules

[Link]() # Exits the program

iv) Function Definition and Calling the Function in Python

 Functions are defined using the `def` keyword, followed by the function
name and parentheses containing any parameters.
 After defining a function, you can call it by using its name followed by
parentheses, optionally including arguments.

Function Definition

The basic syntax for defining a function is as follows:

def function_name(parameters):
# Code block
return result

Calling a Function

To call a function, you use its name followed by parentheses:

function_name(arguments)

`return` Statement

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 37


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

 The `return` statement is used to exit a function and return a value.


 If the function does not have a `return` statement, it will return `None` by
default.

Example:

 Here's a simple example that demonstrates defining a function, calling it,


and using the `return` statement.

**Example:**
# Function Definition
def add_numbers(a, b):
result = a + b
return result

# Calling the Function


sum_result = add_numbers(3, 5)

# Printing the Result


print("The sum is:", sum_result)

**Explanation:**

1. **Function Definition:**
- `def add_numbers(a, b):` - This line defines a function named `add_numbers`
that takes two parameters `a` and `b`.
- `result = a + b` - This line calculates the sum of `a` and `b` and stores it in
the variable `result`.
- `return result` - This line returns the value of `result` to the caller.

2. **Calling the Function:**


- `sum_result = add_numbers(3, 5)` - This line calls the `add_numbers`
function with the arguments `3` and `5`, and stores the returned value in the
variable `sum_result`.

3. **Printing the Result:**


- `print("The sum is:", sum_result)` - This line prints the result stored in
`sum_result`.

**Output:**
The sum is: 8

Additional Examples

**Example 1: Function to Calculate the Square of a Number**

# Function Definition
def square(number):
return number * number

# Calling the Function


result = square(4)

# Printing the Result

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 38


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

print("The square of 4 is:", result)

**Output:**

The square of 4 is: 16

Example 2: Function to Greet a User**

# Function Definition
def greet(name):
return f"Hello, {name}!"

# Calling the Function


greeting = greet("Alice")

# Printing the Result


print(greeting)

**Output:**

Hello, Alice!

v) void function

 In Python, a void function is a function that does not return any value.
 Instead of returning a value, it performs some actions like printing to the
console, modifying a global variable, or altering the state of an object.

Defining a Void Function

 A void function in Python is defined the same way as any other function
but it does not include a `return` statement that returns a value.

Example: Void Function

Here's an example of a void function that prints a greeting message:

# Function Definition
def greet(name):
print(f"Hello, {name}!")

# Calling the Function


greet("Alice")

**Explanation:**

1. **Function Definition:**
 def greet(name): - This line defines a function named `greet` that takes
one parameter `name`.
 print(f"Hello, {name}!") - This line prints a greeting message to the console
using the value of `name`.

2. **Calling the Function:**

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 39


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

 greet("Alice") - This line calls the `greet` function with the argument
`"Alice"`, which results in the function printing the greeting message.

**Output:**
Hello, Alice!

Scope and Lifetime of Variables

 In Python, the scope of a variable refers to the region of the code where
the variable is accessible.
 The lifetime of a variable is the period during which the variable exists in
memory.
 Understanding these concepts is crucial for writing clear and bug-free
code.

Types of Scope

1. **Local Scope**
2. **Enclosing Scope**
3. **Global Scope**
4. **Built-in Scope**

1. Local Scope

 A variable defined inside a function is said to have a local scope. It is only


accessible within that function.

**Example:**
def my_function():
local_var = 10
print("Inside function:", local_var)

my_function()
# print(local_var) # This will raise an error because local_var is not accessible
outside the function.

**Output:**

Inside function: 10

2. Enclosing Scope (Nonlocal Scope)

 This scope comes into play when we have nested functions.


 The inner function can access variables from the outer (enclosing)
function.

**Example:**
def outer_function():
outer_var = "I am outside!"

def inner_function():
print("Inside inner function:", outer_var)

inner_function()

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 40


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

outer_function()

**Output:**
Inside inner function: I am outside!

3. Global Scope

A variable defined at the top level of a script or module has a global scope. It is
accessible throughout the module.

**Example:**
global_var = "I am global!"

def my_function():
print("Inside function:", global_var)

my_function()
print("Outside function:", global_var)

**Output:**
Inside function: I am global!
Outside function: I am global!

4. Built-in Scope

These are special variables and functions provided by Python, such as `print()`,
`len()`, etc. They are always available in any part of the code.

**Example:**
print("Hello, World!")
print(len("Hello"))

**Output:**
Hello, World!
5

Lifetime of Variables

 The lifetime of a variable refers to the period during which the variable
exists in memory.

**Local Variables:**
 Exist during the execution of the function in which they are defined.
**Global Variables:**
 Exist for the duration of the program.

**Example:**
def my_function():
local_var = "I am local"
print("Inside function:", local_var)

my_function()

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 41


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

# print(local_var) # This will raise an error because local_var's lifetime ends with
the function execution.

global_var = "I am global"


print("Outside function:", global_var)

**Output:**
Inside function: I am local
Outside function: I am global

Modifying Global Variables

 To modify a global variable inside a function, you need to use the `global`
keyword.

**Example:**

counter = 0

def increment_counter():
global counter
counter += 1

increment_counter()
increment_counter()
print("Counter:", counter)

**Output:**

Counter: 2

Nonlocal Variables

 The `nonlocal` keyword is used to work with variables inside nested


functions, where the variable should not belong to the inner function.

**Example:**

def outer_function():
outer_var = "I am outer"

def inner_function():
nonlocal outer_var
outer_var = "I have been changed"
print("Inside inner function:", outer_var)

inner_function()
print("Inside outer function:", outer_var)

outer_function()

**Output:**

Inside inner function: I have been changed

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 42


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

Inside outer function: I have been changed

vi) Default Parameters, Keyword Arguments, *args and **kwargs

Default Parameters

 Default parameters allow you to define default values for function


parameters.
 If no argument is provided for a parameter with a default value, the
default value is used.

**Example:**
def greet(name, message="Hello"):
print(f"{message}, {name}!")

# Calling the function with both arguments


greet("Alice", "Hi")

# Calling the function with only the name argument


greet("Bob")

**Output:**

Hi, Alice!
Hello, Bob!

Keyword Arguments

 Keyword arguments allow you to pass arguments to a function by


explicitly naming the parameter.
 This makes the function calls more readable and allows you to pass
arguments in any order.

**Example:**
def describe_pet(pet_name, animal_type):
print(f"I have a {animal_type} named {pet_name}.")

# Using keyword arguments


describe_pet(animal_type="dog", pet_name="Rex")
describe_pet(pet_name="Mittens", animal_type="cat")

**Output:**

I have a dog named Rex.


I have a cat named Mittens.

*args

 *args is used to pass a variable number of non-keyword arguments to a


function. Inside the function, `*args` is treated as a tuple.

**Example:**
def make_pizza(size, *toppings):

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 43


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

print(f"Making a {size}-inch pizza with the following toppings:")


for topping in toppings:
print(f"- {topping}")

# Calling the function with different numbers of arguments


make_pizza(12, "pepperoni", "mushrooms", "green peppers")
make_pizza(16, "extra cheese")

**Output:**

Making a 12-inch pizza with the following toppings:


- pepperoni
- mushrooms
- green peppers
Making a 16-inch pizza with the following toppings:
- extra cheese

**kwargs

 **kwargs is used to pass a variable number of keyword arguments to a


function.
 Inside the function, `**kwargs` is treated as a dictionary.

**Example:**
def build_profile(first, last, **user_info):
profile = {
'first_name': first,
'last_name': last,
}
for key, value in user_info.items():
profile[key] = value
return profile

# Calling the function with different keyword arguments


user_profile = build_profile('albert', 'einstein', location='princeton', field='physics')
print(user_profile)

**Output:**

{'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}

Combining `*args` and `**kwargs`

 You can use both `*args` and `**kwargs` in the same function to accept a
combination of positional and keyword arguments.

**Example:**
def show_details(name, age, *args, **kwargs):
print(f"Name: {name}, Age: {age}")
print("Additional positional arguments:", args)
print("Additional keyword arguments:", kwargs)

# Calling the function with various arguments

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 44


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

show_details("Alice", 30, "Engineer", "Single", city="New York", hobby="Reading")

**Output:**
Name: Alice, Age: 30
Additional positional arguments: ('Engineer', 'Single')
Additional keyword arguments: {'city': 'New York', 'hobby': 'Reading'}

vii) Command Line Arguments.

 In Python, command-line arguments can be passed to a script when it is


executed from the command line.
 These arguments are accessed using the `[Link]` list provided by the
`sys` module, or more conveniently using the `argparse` module for more
complex argument parsing.

Using `[Link]`

 [Link] is a list in Python that contains the command-line arguments


passed to the script.
 The first element (`[Link][0]`) is the script name itself.

**Example:**

 Create a Python script named `[Link]` with the following content:


import sys

# Display all command-line arguments


print("Total arguments:", len([Link]))
print("Script name:", [Link][0])

# Display all arguments passed (excluding the script name)


print("Arguments:", [Link][1:])

Now, run the script from the command line with different arguments:

>>python [Link] arg1 arg2 arg3

**Output:**

Total arguments: 4
Script name: [Link]
Arguments: ['arg1', 'arg2', 'arg3']

viii) Strings
In Python, strings are sequences of characters enclosed within either single
quotes (`'`) or double quotes (`"`). They are immutable, meaning once defined,
their content cannot be changed. Here are various ways to create and
manipulate strings in Python:

1. Creating Strings

Single Quotes and Double Quotes

```python

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 45


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

# Single quotes
single_quoted = 'Hello, World!'
print(single_quoted)

# Double quotes
double_quoted = "Python Programming"
print(double_quoted)
```

Triple Quotes for Multiline Strings


multiline_string = """This is a
multiline
string."""
print(multiline_string)

2. String Concatenation

Strings can be concatenated using the `+` operator:

str1 = "Hello"
str2 = "World"
concatenated_string = str1 + ", " + str2 + "!"
print(concatenated_string)

3. Accessing Characters in Strings

 Strings can be accessed like arrays using indexing:


message = "Python"
print(message[0]) # Output: 'P'
print(message[-1]) # Output: 'n'

4. String Slicing

 You can slice strings to extract substrings:

message = "Python Programming"


print(message[0:6]) # Output: 'Python'
print(message[7:]) # Output: 'Programming'

5. String Methods

 Python provides many built-in methods to manipulate strings:


sentence = "hello world"
print([Link]()) # Output: 'HELLO WORLD'
print([Link]()) # Output: 'Hello world'
print([Link]('h'))# Output: True
print([Link]()) # Output: ['hello', 'world']

6. Format Strings

 You can format strings using f-strings (formatted string literals):

name = "Alice"

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 46


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

age = 30
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)

7. Escape Characters

Python uses backslashes (`\`) to escape characters:

escaped_string = "This is a \"quoted\" string."


print(escaped_string)

8. Raw Strings

Raw strings treat backslashes (`\`) as literal characters:


raw_string = r'C:\Users\Username'
print(raw_string)

9. String Conversion

 You can convert other types to strings using `str()`:

number = 42
converted_string = str(number)
print(converted_string) # Output: '42'

10. Storing Strings

 Strings can be stored in variables or data structures like lists or


dictionaries:

string_variable = "Python"
list_of_strings = ["apple", "banana", "cherry"]
dictionary_of_strings = {"name": "Alice", "city": "Wonderland"}

ix)Basic string operations


 In Python, strings are sequences of characters that are immutable,
meaning once created, they cannot be changed.
 Here are some basic string operations and examples of how to use them:

1. String Concatenation

 You can concatenate strings using the `+` operator:


str1 = "Hello"
str2 = "World"
concatenated_string = str1 + ", " + str2 + "!"
print(concatenated_string)

**Output:**
Hello, World!

2. String Repetition

 Strings can be repeated using the `*` operator:

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 47


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

original_string = "Python"
repeated_string = original_string * 3
print(repeated_string)

**Output:**
PythonPythonPython

3. String Length

 You can find the length of a string using the `len()` function:
message = "Hello, World!"
length_of_string = len(message)
print(length_of_string)

**Output:**
13

4. Accessing Characters

 Strings can be accessed like arrays using indexing:


message = "Python"
print(message[0]) # Output: 'P'
print(message[-1]) # Output: 'n'

5. String Slicing

 You can slice strings to extract substrings:


message = "Python Programming"
print(message[0:6]) # Output: 'Python'
print(message[7:]) # Output: 'Programming'

6. String Methods

 Python provides many built-in methods to manipulate strings:


sentence = "hello world"
print([Link]()) # Output: 'HELLO WORLD'
print([Link]()) # Output: 'Hello world'
print([Link]('h')) # Output: True
print([Link]()) # Output: ['hello', 'world']

7. String Formatting

 You can format strings using various methods, including f-strings


(formatted string literals):

name = "Alice"
age = 30
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)

**Output:**
My name is Alice and I am 30 years old.

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 48


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

8. String Conversion

 You can convert other types to strings using `str()`:

number = 42
converted_string = str(number)
print(converted_string) # Output: '42'

9. Checking Substrings

 You can check if a substring exists within a string using the `in` keyword:
message = "Hello, World!"
print('Hello' in message) # Output: True
print('Python' in message) # Output: False

10. Removing Whitespace

 You can remove whitespace from the beginning and end of a string using
`strip()`, `lstrip()`, and `rstrip()` methods:

whitespace_string = " Python Programming "


print(whitespace_string.strip()) # Output: 'Python Programming'
print(whitespace_string.lstrip()) # Output: 'Python Programming '
print(whitespace_string.rstrip()) # Output: ' Python Programming'

x) Accessing Characters in String by Index Number


 In Python, you can access individual characters in a string using their
index positions. Here's how you can do it:

Accessing Characters by Index

 Strings in Python are indexed starting from 0.


 You can use positive or negative indices to access characters:

message = "Python"

# Accessing characters using positive indices


print(message[0]) # Output: 'P'
print(message[1]) # Output: 'y'
print(message[2]) # Output: 't'
print(message[3]) # Output: 'h'
print(message[4]) # Output: 'o'
print(message[5]) # Output: 'n'

# Accessing characters using negative indices


print(message[-1]) # Output: 'n' (last character)
print(message[-2]) # Output: 'o'
print(message[-3]) # Output: 'h'
print(message[-4]) # Output: 't'
print(message[-5]) # Output: 'y'
print(message[-6]) # Output: 'P' (first character)

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 49


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

Example: Accessing Characters in a Loop

 You can iterate over a string and access each character by its index:

message = "Python"

# Print each character and its index


for index in range(len(message)):
print(f"Character at index {index}: {message[index]}")

**Output:**

Character at index 0: P
Character at index 1: y
Character at index 2: t
Character at index 3: h
Character at index 4: o
Character at index 5: n

String Slicing and Joining


 String slicing and joining are fundamental operations in Python that allow
you to manipulate and concatenate parts of strings efficiently.
 Here’s how you can use string slicing and joining with examples:

String Slicing

 String slicing allows you to extract a substring from a string by


specifying a range of indices.

Basic Slicing

message = "Python Programming"

# Extracting a substring
substring = message[7:18] # Starts at index 7, ends at index 17
(exclusive)
print(substring) # Output: 'Programming'

Slicing with Negative Indices

 You can use negative indices to slice from the end of the string:

message = "Python Programming"

# Slicing from the end of the string


substring = message[-11:-1] # Starts 11 characters from the end, ends at
the last character
print(substring) # Output: 'Programmin'

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 50


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

Omitting Start or End Indices

 If you omit the start index, slicing starts from the beginning of the
string.
 If you omit the end index, slicing continues to the end of the
string:

message = "Python Programming"

# Slicing from the beginning


substring1 = message[:6] # Starts from the beginning, ends at index 5
print(substring1) # Output: 'Python'

# Slicing to the end


substring2 = message[7:] # Starts at index 7, ends at the end of the
string
print(substring2) # Output: 'Programming'

Slicing with a Step

 You can specify a step value to skip characters while slicing:


message = "Python Programming"

# Slicing with a step of 2


substring = message[::2] # Returns every second character
print(substring) # Output: 'Pto rgamn'

String Joining

 String joining allows you to concatenate multiple strings or iterate


through a sequence and concatenate its elements into a single
string.

Joining with `join()`

 You can use the `join()` method to concatenate elements of an


iterable into a single string:

words = ["Hello", "World", "Python"]


joined_string = " ".join(words)
print(joined_string) # Output: 'Hello World Python'

# Joining with a custom separator


csv_data = ["John", "Doe", "30"]
csv_line = ",".join(csv_data)
print(csv_line) # Output: 'John,Doe,30'

Joining with `+` Operator

 You can concatenate strings using the `+` operator:


greeting = "Hello"
name = "Alice"

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 51


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

message = greeting + ", " + name + "!"


print(message) # Output: 'Hello, Alice!'

xi) String Methods


 In Python, strings are objects that come with a variety of built-in
methods to manipulate and work with textual data.
 Here are some commonly used string methods along with
examples of their usage:

1. capitalize()

 Converts the first character of the string to uppercase and the rest to
lowercase.
message = "hello world"
capitalized_message = [Link]()
print(capitalized_message) # Output: 'Hello world'

2. upper() and lower()

 Converts all characters in the string to uppercase or lowercase,


respectively.
message = "Hello World"
uppercase_message = [Link]()
lowercase_message = [Link]()
print(uppercase_message) # Output: 'HELLO WORLD'
print(lowercase_message) # Output: 'hello world'

3. count(substring)

 Counts the occurrences of a substring within the string.


message = "Python is powerful and Python is easy to learn"
count_python = [Link]("Python")
print(count_python) # Output: 2

4. find(substring) and `index(substring)

 `find()` and `index()` both return the index of the first occurrence of
the substring in the string.
 The difference is that `find()` returns `-1` if the substring is not found,
while `index()` raises a `ValueError`.
message = "Python is powerful"
print([Link]("is")) # Output: 7
print([Link]("power"))# Output: 10

5. `replace(old, new)`

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 52


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

 Replaces all occurrences of `old` substring with `new` substring in the


string.
message = "Hello World"
new_message = [Link]("Hello", "Hi")
print(new_message) # Output: 'Hi World'

6. `split(delimiter)`

 Splits the string into a list of substrings based on the delimiter.


 If no delimiter is specified, it splits by whitespace.

message = "apple,banana,cherry"
fruits_list = [Link](",")
print(fruits_list) # Output: ['apple', 'banana', 'cherry']

7. `strip()`, `lstrip()`, `rstrip()`

 `strip()` removes leading and trailing whitespace (or specified


characters). `lstrip()` removes leading whitespace, and `rstrip()`
removes trailing whitespace.
message = " Hello World "
print([Link]()) # Output: 'Hello World'
print([Link]()) # Output: 'Hello World '
print([Link]()) # Output: ' Hello World'

8. `startswith(prefix)` and `endswith(suffix)`

 Checks if the string starts or ends with the specified prefix or suffix.

message = "Hello World"


print([Link]("Hello")) # Output: True
print([Link]("World")) # Output: True

9. `join(iterable)`

 Concatenates elements of an iterable (e.g., list) into a single string,


joining each element with the string.
words = ["Hello", "World"]
joined_string = "-".join(words)
print(joined_string) # Output: 'Hello-World'

10. `isdigit()` and `isalpha()`

 `isdigit()` checks if all characters in the string are digits. `isalpha()`


checks if all characters are alphabetic.

number = "12345"

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 53


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

word = "Python"
print([Link]()) # Output: True
print([Link]()) # Output: True

11. `format()`

 Formats the string with placeholders `{}`.


name = "Alice"
age = 30
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.'

xii) Formatting Strings


 In Python, string formatting allows you to create formatted strings by
inserting variables or expressions into placeholders within a string.
 There are several methods for string formatting, each serving different
needs. Here’s an overview of the main approaches with examples:

1. Using f-strings (Formatted String Literals)

 f-strings provide a concise and readable way to embed expressions


inside string literals. They were introduced in Python 3.6+.
name = "Alice"
age = 30
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)

**Output:**
My name is Alice and I am 30 years old.

You can also use expressions inside `{}`:


a=5
b = 10
formatted_string = f"The sum of {a} and {b} is {a + b}."
print(formatted_string)

**Output:**
The sum of 5 and 10 is 15.

2. Using `[Link]()`

 `[Link]()` method allows you to insert variables or expressions


into placeholders `{}` within a string:
name = "Bob"
age = 25
formatted_string = "My name is {} and I am {} years old.".format(name,
age)

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 54


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

print(formatted_string)

**Output:**
My name is Bob and I am 25 years old.

 You can specify the order of arguments and use field names:

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

**Output:**
My name is Carol and I am 35 years old.

3. Using `%` Formatting

 Old-style formatting using `%` is still supported but less


recommended compared to f-strings and `[Link]()`:
name = "David"
age = 40
formatted_string = "My name is %s and I am %d years old." % (name, age)
print(formatted_string)

**Output:**
My name is David and I am 40 years old.

4. Using `join()` method with Iterable

 You can concatenate strings from an iterable using the `join()`


method:

fruits = ["apple", "banana", "cherry"]


formatted_string = ", ".join(fruits)
print(formatted_string)

**Output:**
apple, banana, cherry

5. Aligning Text with `ljust()`, `rjust()`, and `center()`

 These methods align the text within a specified width by padding


with spaces:

text = "Hello"
print([Link](10)) # Output: 'Hello '

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 55


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

print([Link](10)) # Output: ' Hello'


print([Link](10)) # Output: ' Hello '

Lists:
xiii) Creating Lists, Basic List Operations, Indexing and Slicing in Lists,
Built-In Functions Used on Lists, List Methods

 In Python, lists are ordered collections of items, which can be of any data
type (such as integers, floats, strings, or even other lists).
 Lists are mutable, meaning you can change their contents after they are
created.
 Here’s how you can create and work with lists in Python:

1. Creating a List

 You can create a list by enclosing comma-separated values within square


brackets `[]`:
# Creating a list of integers
numbers = [1, 2, 3, 4, 5]
print(numbers) # Output: [1, 2, 3, 4, 5]

# Creating a list of strings


fruits = ["apple", "banana", "cherry"]
print(fruits) # Output: ['apple', 'banana', 'cherry']

# Creating a list of mixed data types


mixed_list = [1, "apple", 3.14, True]
print(mixed_list) # Output: [1, 'apple', 3.14, True]

# Creating an empty list


empty_list = []
print(empty_list) # Output: []

2. Nested Lists

Lists can contain other lists as elements, allowing for nested data structures:
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(nested_list) # Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

3. Accessing Elements

 You can access elements of a list using square brackets and the index of
the element (indexing starts at 0):

fruits = ["apple", "banana", "cherry"]


print(fruits[0]) # Output: 'apple'
print(fruits[1]) # Output: 'banana'
print(fruits[2]) # Output: 'cherry'

# Negative indexing
print(fruits[-1]) # Output: 'cherry' (last element)
```

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 56


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

4. Slicing Lists

 You can slice a list to extract a sublist using the syntax `[start:end]`.
Slicing doesn't modify the original list but returns a new list:
numbers = [1, 2, 3, 4, 5]
sublist = numbers[1:4]
print(sublist) # Output: [2, 3, 4]

# Omitting start or end index


print(numbers[:3]) # Output: [1, 2, 3] (from start to index 2)
print(numbers[2:]) # Output: [3, 4, 5] (from index 2 to end)

5. Modifying Lists

 Lists are mutable, so you can modify elements, append new elements, or
delete existing ones:

fruits = ["apple", "banana", "cherry"]


fruits[1] = "orange"
print(fruits) # Output: ['apple', 'orange', 'cherry']

[Link]("pear")
print(fruits) # Output: ['apple', 'orange', 'cherry', 'pear']

del fruits[0]
print(fruits) # Output: ['orange', 'cherry', 'pear']

6. List Methods

 Python provides several built-in methods to manipulate lists, such as


`append()`, `extend()`, `insert()`, `remove()`, `pop()`, `clear()`, `index()`,
`count()`, `sort()`, and `reverse()`. Here are a few examples:

numbers = [3, 1, 2, 5, 4]
[Link]()
print(numbers) # Output: [1, 2, 3, 4, 5]

[Link]()
print(numbers) # Output: [5, 4, 3, 2, 1]

[Link](6)
print(numbers) # Output: [5, 4, 3, 2, 1, 6]

[Link](3)
print(numbers) # Output: [5, 4, 2, 1, 6]

7. List Comprehensions

 List comprehensions provide a concise way to create lists. They can also
include conditions and nested loops:

# Creating a list of squares


squares = [x**2 for x in range(10)]
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 57


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

# Creating a list of even numbers


even_numbers = [x for x in range(20) if x % 2 == 0]
print(even_numbers) # Output: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

 Lists are versatile data structures in Python that allow you to store and
manipulate collections of items efficiently.
 Understanding how to create, access, and modify lists is fundamental for
Python programming.

xiv) del statement


 In Python, the `del` statement is used to remove an item or slice from a list,
or to delete a variable or object from memory.
 Here’s how the `del` statement works with examples:

1. Deleting Elements from a List

 You can use `del` to remove an element from a list by specifying its index:

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

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

del numbers[2] # Delete element at index 2

print(numbers) # Output: [1, 2, 4, 5]

2. Deleting Slices from a List

 You can also delete a slice from a list using `del`:

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

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

del numbers[1:3] # Delete elements from index 1 to 2 (exclusive)

print(numbers) # Output: [1, 4, 5]

3. Deleting Entire List

 To delete the entire list and free up memory, you can use `del` on the list
itself:

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

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

del numbers

print(numbers) # Raises NameError: name 'numbers' is not defined

4. Deleting Variables

You can use `del` to delete variables and free up their memory:

x = 10

print(x) # Output: 10

del x

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 58


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

print(x) # Raises NameError: name 'x' is not defined

Sample Experiments:

In Python, functions can return multiple values by packing them into a tuple, list,
or other data structures. Here’s an example of how to define a function that returns
multiple values:

[Link] a program to define a function with multiple return values.

def calculate_statistics(numbers):

# Calculate sum, average, and count of numbers

total_sum = sum(numbers)

average = total_sum / len(numbers)

count = len(numbers)

# Return multiple values as a tuple

return total_sum, average, count

# Example usage of the function

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

total, avg, count = calculate_statistics(numbers_list)

# Displaying the results

print(f"Total sum: {total}")

print(f"Average: {avg}")

print(f"Count of numbers: {count}")

[Link] a program to define a function using default arguments.


def greet(name, message="Hello,"):

print(f"{message} {name}!")

# Example usage of the function

greet("Alice") # Uses default message: Hello, Alice!

greet("Bob", "Hi") # Uses custom message: Hi Bob!

Output:

Hello, Alice!

Hi Bob!

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 59


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

3. Write a program to find the length of the string without using any
library functions.

def find_string_length(input_string):

length = 0

for char in input_string:

length += 1

return length

# Example usage

input_string = "Hello, World!"

length = find_string_length(input_string)

print(f"The length of the string '{input_string}' is: {length}")

**Output**:

The length of the string 'Hello, World!' is: 13

4. Write a program to check if the substring is present in a given string or


not.

def is_substring_present(main_string, substring):


main_len = len(main_string)
sub_len = len(substring)

for i in range(main_len - sub_len + 1):


if main_string[i:i + sub_len] == substring:
return True

return False

# Example usage
main_string = "Hello, World!"
substring1 = "World"
substring2 = "Python"

if is_substring_present(main_string, substring1):
print(f"'{substring1}' is present in '{main_string}'")
else:
print(f"'{substring1}' is not present in '{main_string}'")

if is_substring_present(main_string, substring2):
print(f"'{substring2}' is present in '{main_string}'")
else:

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 60


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

print(f"'{substring2}' is not present in '{main_string}'")

**Output**:
'World' is present in 'Hello, World!'
'Python' is not present in 'Hello, World!'
5. Write a program to perform the given operations on a list:
i. Addition ii. Insertion iii. slicing
# Define a list

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

# i. Addition operation

# Append an element to the end of the list

[Link](6)

print("List after addition:", numbers) # Output: [1, 2, 3, 4, 5, 6]

# ii. Insertion operation

# Insert an element at a specific position

[Link](2, 10) # Insert 10 at index 2

print("List after insertion:", numbers) # Output: [1, 2, 10, 3, 4, 5, 6]

# iii. Slicing operation

# Extract a sublist using slicing

sublist = numbers[1:4] # Slice from index 1 to 3 (exclusive)

print("Sublist:", sublist) # Output: [2, 10, 3]

# Modify an element using slicing

numbers[3:5] = [8, 9] # Replace elements at index 3 and 4

print("Modified list:", numbers) # Output: [1, 2, 10, 8, 9, 6]

Output:

List after addition: [1, 2, 3, 4, 5, 6]

List after insertion: [1, 2, 10, 3, 4, 5, 6]

Sublist: [2, 10, 3]

Modified list: [1, 2, 10, 8, 9, 6]

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 61


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

6. Write a program to perform any 5 built-in functions by taking any list.

# Define a sample list

numbers = [5, 2, 7, 1, 8, 3]

# 1. len() - Get the length of the list

length = len(numbers)

print(f"Length of the list: {length}") # Output: Length of the list: 6

# 2. max() - Find the maximum value in the list

max_value = max(numbers)

print(f"Maximum value in the list: {max_value}") # Output: Maximum value in the


list: 8

# 3. min() - Find the minimum value in the list

min_value = min(numbers)

print(f"Minimum value in the list: {min_value}") # Output: Minimum value in the


list: 1

# 4. sorted() - Sort the list (returns a new sorted list)

sorted_numbers = sorted(numbers)

print(f"Sorted list: {sorted_numbers}") # Output: Sorted list: [1, 2, 3, 5, 7, 8]

# 5. sum() - Calculate the sum of all elements in the list

total_sum = sum(numbers)

print(f"Sum of all elements in the list: {total_sum}") # Output: Sum of all elements
in the list: 26

Output:

Length of the list: 6

Maximum value in the list: 8

Minimum value in the list: 1

Sorted list: [1, 2, 3, 5, 7, 8]

Sum of all elements in the list: 26

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 62


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

UNIT-III

Dictionaries: Creating Dictionary, Accessing and Modifying key:value Pairs in


Dictionaries, Built-In Functions Used on Dictionaries, Dictionary Methods, del
Statement.
Tuples and Sets: Creating Tuples, Basic Tuple Operations, tuple () Function, Indexing
and Slicing in Tuples, Built-In Functions Used on Tuples, Relation between Tuples and
Lists, Relation between Tuples and Dictionaries, Using zip() Function, Sets, Set
Methods, Frozenset.

Sample Experiments:

1. Write a program to create tuples (name,age,address,college) fo atleast two members and


concatenate the tuples and print the concatenated tuples.
2. Write a program to count the number of vowels in a string (No controlflow allowed).
3. Write a program to check if a given key exists in a dictionary or not.
4. Write a program to add a new key-value pair to an existing dictionary.
5. Write a program to sum all the items in a given dictionary.

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 63


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

Dictionary
 It is a data structure in which we store values as a pair of key and value.
 Each key is separated from its value by a colon (:), and consecutive items are separated
by commas.
 The entire items in a dictionary are enclosed in curly brackets ({}).
Creating Dictionary:
Syntax:
dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3}
 If there are many keys and values in dictionaries, then we can also write just one key-
value pair on a line to make the code easier to read and [Link] is shown below.
dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3 , ….}
 Keys in the dictionary must be unique and be of any immutable data type (like Strings,
numbers, or tuples), there is no strict requirement for uniqueness and type of values.
 Values of a key can be of any type.
 Dictionaries are not Sequences, rather they are mappings.
 Mappings are collections of objects that are store objects by key instead of by relative
position.

Accessing
o In Dictionary, values are accessed through keys.

Example:
d={'Name': 'Arav', 'Course': '[Link]', 'roll_no': '18/001'}
print('d[Name]:',d['Name'])
print('d[course]:',d['Course'])
print('d[roll_no]:',d['roll_no'])
Output:
d[Name]: Arav
d[course]: [Link]
d[roll_no]: 18/001

Modifying an item
To modify an entry, just overwrite the existing value as shown in the following
Example:
d={'Name': 'Arav', 'Course': '[Link]', 'roll_no': '18/001'}
d['marks']=99 #new entry
print('d[Name]:',d['Name'])
print('d[course]:',d['Course'])
print('d[roll_no]:',d['roll_no'])
print('d[marks]:',d['marks'])
d[‘Course’]=’BCA’ #Updated entry
Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 64
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

print('d[course]:',d['Course'])

Output:
d[Name]: Arav
d[course]: [Link]
d[roll_no]: 18/001
d[marks]: 99
d[course]: BCA

Built-In Functions Used on Dictionaries:


[Link](dict1, dict2)
Compares elements of both dict.
[Link](dict)
Gives the total length of the dictionary. This would be equal to the number of items in the
dictionary.
[Link](dict)
Produces a printable string representation of a dictionary
[Link](variable)
Returns the type of the passed variable. If passed variable is dictionary, then it would return a
dictionary type.

Built-in Methods:

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 65


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 66


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

Del Statement:

Deleting
o We can delete one or more items using the del keyword.
o To delete or remove all the items in just one statement, use the clear () function.
o Finally, to remove an entire dictionary from the memory, we can gain use the del
statement as del Dict_name.
o The syntax to use the del statement can be given as,
deldictionary_variable[key]
Example:

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 67


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

Tuples and Sets:


Tuple:
 A tuple is a sequence of immutable objects. That is, you can change the value of one or
more items in a list; you cannot change the values in a tuple.
 Tuples use parenthesis to define its elements.

Creating Tuples:
[Link] = ("apple", "banana", "cherry")
print(thistuple)
output:
('apple', 'banana', 'cherry')
[Link] = ("a", "b", "c")
print(tuple)
output:
(‘a’,’b’,’c’)
Basic Tuple Operations :

Operation Expression Output

Length len((1,2,3,4,5,6)) 6

Concatenation (1,2,3)+(4,5,6) (1,2,3,4,5,6)

Repetition (‘Good..’)*3 ‘Good ..Good..Good’

Membership 5 in (1,2,3,4,5,6,7,8,9) True

Iteration for i in (1,2,3,4,5,6,7,8,9,10): 1,2,3,4,5,6,7,8,910

print(i,end=’ ‘)

Comparision(Use >,<,==) Tup1=(1,2,3,4,5) False

Tup2=(1,2,3,4,5)

print(Tup1>Tup2)

Maximum max(1,0,3,8,2,9) 9

Minimum min(1,0,3,8,2,9) 0

Convert to tuple(converts a tuple(“Hello”) (‘H’,’e’,’l’,’l’,’o’)


sequence into a tuple)
tuple([1,2,3,4,5]) (1,2,3,4,5)

Sorting(The sorted( ) function t=(4,67,9) [4, 9, 67]


takes elements in a tuple and
returns a new sorted list (does sorted(t)

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 68


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

not sort the tuple itself)).

tuple() Function :
The Python tuple() function is a built-in function in Python that can be used to create
a tuple. A tuple is an ordered and immutable sequence type.
('a', 'b', 'c'', 'c')
Example:
l = [1,2,3]
print(tuple(l))
Output:
(1,2,3)
Indexing and Slicing in Tuples :

Indexing Tuples :

In Python, every tuple with elements has a position or index. Each element of the tuple can
be accessed or manipulated by using the index number.

There are two types of indexing:

 Positive Indexing
 Negative Indexing

Positive Indexing

In positive the first element of the tuple is at an index of 0 and the following elements are at
+1 and as follows.

Ex:

tuple =(5,2,9,7,5,8,1,4,3)
print(tuple(3))

print(tuple(7))

Output:

7
4

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 69


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

Negative Indexing

In negative indexing, the indexing of elements starts from the end of the tuple. That is the last
element of the tuple is said to be at a position at -1 and the previous element at -2 and goes
on till the first element.
Ex:

tuple= (5,2,9,7,5,8,1,4,3)
print(tuple(-2))

print(tuple(-8))

Output

4
2

Slicing tuples

Tuple slicing is a frequent practice in Python, and it is the most prevalent technique used by
programmers to solve efficient problems. Consider a Python tuple. You must slice a tuple in
order to access a range of elements in it. One method is to utilize the colon as a simple slicing
operator (:).

Syntax

tuple[Start : Stop : Stride]

Example 1

tuple=('a','b','c','d','e','f','g','h','i','j')
print(tuple[0:6])
print(tuple[1:9:2])

print(tuple[-1:-5:-2])

Output

('a', 'b', 'c', 'd', 'e', 'f')


('b', 'd', 'f', 'h')
('j', 'h')

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 70


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

Built-In Functions Used on Tuples:


The len() Function :

This function returns the number of elements present in a tuple. Moreover, it is necessary to
provide a tuple to the len() function.

Ex:

>>>tup = (22, 45, 23, 78, 6.89)

>>> len(tup)

The count() Function :

This function will help us to fund the number of times an element is present in the tuple.
Furthermore, we have to mention the element whose count we need to find, inside the count
function.

For example,

>>>tup = (22, 45, 23, 78, 22, 22, 6.89)

>>> [Link](22)

>>> [Link](54)

The index() Function

The tuple index() method helps us to find the index or occurrence of an element in a tuple. This
function basically performs two functions:

 Giving the first occurrence of an element in the tuple.

 Raising an exception if the element mentioned is not found in the tuple.


For example,

Example 1: Finding the index of an element

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 71


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

>>> tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)

>>> print([Link](45))

>>> print([Link](890))

#prints the index of elements 45 and 890

7
Example 2:

>>> tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)

>>> print([Link](3.2))

# gives an error because the element is not present in the tuple.

ValueError: [Link](x): x not in tuple

The sorted() Function

This method takes a tuple as an input and returns a sorted list as an output. Moreover, it does not
make any changes to the original tuple.

EX:

>>> tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)

>>> sorted(tup)

[1, 2, 2.4, 3, 4, 22, 45, 56, 890]

The min(), max(), and sum() Tuple Functions

min(): gives the smallest element in the tuple as an output. Hence, the name is min().

For example,

>>> tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)

>>> min(tup)

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 72


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

max(): Gives the largest element in the tuple as an output. Hence, the name is max().

>>> tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)

>>> max(tup)

890
Sum:Gives the sum of the elements present in the tuple as an output.

>>> tup = (22, 3, 45, 4, 2, 56, 890, 1)

>>> sum(tup)

1023
Relation between Tuples and Lists:

 The key difference between the tuples and lists is that while the tuples are
immutable objects the lists are mutable. This means that tuples cannot be changed
while the lists can be modified.
 Tuples are more memory efficient than the lists.

import sys
a_list = []
a_tuple = ()
a_list = ["Geeks", "For", "Geeks"]
a_tuple = ("Geeks", "For", "Geeks")
print([Link](a_list))
print([Link](a_tuple))

Output
96
80

Relation between Tuples and Dictionaries:

Tuples are unordered. Dictionaries are ordered.

tuple = ('a',10,'b',0.4,True)

print("Tuple:", tuple)

dictionary = {'a':True,10:'Ten'}

print("Dictionary:", dictionary)

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 73


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

output:

('Tuple:', ('a', 10, 'b', 0.4, True))


('Dictionary:', {'a': True, 10: 'Ten'})

Using zip() Function :

The zip() function returns a zip object, which is an iterator of tuples where the first item in
each passed iterator is paired together, and then the second item in each passed iterator are
paired together etc.

If the passed iterables have different lengths, the iterable with the least items decides the
length of the new iterator.

Syntax

zip(iterator1, iterator2, iterator3 ...)

iterable1, iterable2, iterable3 ... Iterable objects that will be joined together

Example:

a = ("John", "Charles", "Mike")


b = ("Jenny", "Christy", "Monica")

x = zip(a, b)

output:

(('John', 'Jenny'), ('Charles', 'Christy'), ('Mike', 'Monica'))

Sets:

 Set is a mutable and unordered collection of items represented using curly brackets { }.
 Set does not allow duplicate values.
 Since sets are unordered, indexing cannot be done.
 Like mathematical sets, python sets are also a powerful tool that have the ability to
calculate union, differences and intersections between other sets.

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 74


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

add() Adds an element to the set

clear() Removes all the elements from the set

copy() Returns a copy of the set

difference() - Returns a set containing the difference between two


or more sets

difference_update() -= Removes the items in this set that are also included
in another, specified set

discard() Remove the specified item

intersection() & Returns a set, that is the intersection of two other


sets

intersection_update() &= Removes the items in this set that are not present in
other, specified set(s)

isdisjoint() Returns whether two sets have a intersection or not

issubset() <= Returns whether another set contains this set or not

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 75


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

< Returns whether all items in this set is present in


other, specified set(s)

issuperset() >= Returns whether this set contains another set or not

> Returns whether all items in other, specified set(s) is


present in this set

pop() Removes an element from the set

remove() Removes the specified element

symmetric_difference() ^ Returns a set with the symmetric differences of two


sets

symmetric_difference_update() ^= Inserts the symmetric differences from this set and


another

union() | Return a set containing the union of sets

update() |= Update the set with the union of this set and others

Frozenset:

The frozenset() function returns an unchangeable frozenset object (which is like


a set object, only unchangeable).

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 76


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

Syntax
frozenset(iterable)

iterable An iterable object, like list, set, tuple etc.

Example:

mylist = ['apple', 'banana', 'cherry']

x = frozenset(mylist)

print(x)

Output:

frozenset({'cherry', 'banana', 'apple'})

[Link] a program to create tuples (name,age,address,college) fo atleast two members and


concatenate the tuples and print the concatenated tuples.

def main():

# Creating tuples for two members

member1 = ("Alice", 25, "123 Street, CityA", "ABC College")

member2 = ("Bob", 28, "456 Avenue, CityB", "XYZ College")

# Concatenating the tuples

concatenated_tuple = member1 + member2

# Printing the concatenated tuple

print("Concatenated Tuple:")

print(concatenated_tuple)

if __name__ == "__main__":

main()
OUTPUT:

Concatenated Tuple:

('Alice', 25, '123 Street, CityA', 'ABC College', 'Bob', 28, '456 Avenue, CityB', 'XYZ College')

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 77


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

2. Write a program to count the number of vowels in a string (No controlflow allowed).

def count_vowels(s):
# Define the vowels in a set for quick lookup
vowels = {'a', 'e', 'i', 'o', 'u'}

# Count vowels using set intersection with the input string


num_vowels = sum(1 for char in s if [Link]() in vowels)

return num_vowels

def main():
# Input string for testing
input_string = "Hello World, How are you?"

# Count vowels in the input string


num_vowels = count_vowels(input_string)

# Print the result


print(f"Number of vowels in the string: {num_vowels}")

if __name__ == "__main__":
main()

Output:
Number of vowels in the string: 7

[Link] a program to check if a given key exists in a dictionary or not.

def check_key_in_dict(dictionary, key):


# Using the 'in' keyword to check if the key exists in the dictionary
if key in dictionary:
return True
else:
return False

def main():
# Example dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}

# Key to check
key_to_check = 'b'

# Check if key exists in the dictionary


if check_key_in_dict(my_dict, key_to_check):
print(f"The key '{key_to_check}' exists in the dictionary.")
else:
print(f"The key '{key_to_check}' does not exist in the dictionary.")

if __name__ == "__main__":
main()
Output: The key 'b' exists in the dictionary.
Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 78
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

[Link] a program to add a new key-value pair to an existing dictionary.

Def add_to_dictionary(dictionary, key, value):


# Adding a new key-value pair to the dictionary
dictionary[key] = value

def main():
# Existing dictionary
my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}

# Key-value pair to add


new_key = ‘d’
new_value = 4

# Adding new key-value pair to the dictionary


add_to_dictionary(my_dict, new_key, new_value)

# Printing the updated dictionary


print(“Updated Dictionary:”, my_dict)

if __name__ == “__main__”:
main()

Output:
Updated Dictionary: {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}

[Link] a program to sum all the items in a given dictionary.

def sum_dictionary_items(d):
total_sum = sum([Link]())
return total_sum

# Example usage
my_dict = {'a': 100, 'b': 200, 'c': 300}
print("Sum of all items in the dictionary:", sum_dictionary_items(my_dict))

OUTPUT:
Sum of all items in the dictionary: 600

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 79


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

UNIT-IV

Files: Types of Files, Creating and Reading Text Data, File Methods to Read and Write
Data, Reading and Writing Binary Files, Pickle Module, Reading and Writing CSV
Files, Python os and [Link] Modules.
Object-Oriented Programming: Classes and Objects, Creating Classes in Python,
Creating Objects in Python, Constructor Method, Classes with Multiple Objects, Class
Attributes Vs Data Attributes, Encapsulation, Inheritance, Polymorphism.

Sample Experiments
1. Write a program to sort words in a file and put them in another file. The output
file should have only lower-case words, so any upper-case words from source
must be lowered.
2. Python program to print each line of a file in reverse order.
3. Python program to compute the number of characters, words and lines in a file.
4. Write a program to create, display, append, insert and reverse the order of the
items in the array.
5. Write a program to add, transpose and multiply two matrices.
6. Write a Python program to create a class that represents a shape. Include methods to
calculate its area and perimeter. Implement subclasses for different shapes like
circle, triangle, and square.

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 80


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

Files:

File is a collection of records. Files are stored in Secondary memory called permanent
memory. Secondary memory devices are: Hard disk, memory card, CD/DVD, Pen drive.
Before saving the file, it is temporally stored in RAM random access memory (temporary
memory).

In Python, files are treated in two modes as text or binary. The file may be in the text or
binary format, and each line of a file is ended with the special character.

Types of Files:

Computers store every file as a collection of 0s and 1s i.e., in binary form. Therefore, every
file is basically just a series of bytes stored one after the other. There are mainly two types of
data files — text file and binary file. A text file consists of human readable characters, which
can be opened by any text editor. On the other hand, binary files are made up of non-human
readable characters and symbols, which require specific programs to access its contents.

Generally, there are 2 types of files.

1. Text files

2. Binary Files

[Link] Files: A text file can be understood as a sequence of characters consisting of


alphabets, numbers and other special symbols. Files with extensions like .txt, .py, .csv, etc.
are some examples of text files. When we open a text file using a text editor (e.g., Notepad),
we see several lines of text. However, the file contents are not stored in such a way internally.
Rather, they are stored in sequence of bytes consisting of 0s and 1s.

In ASCII, UNICODE or any other encoding scheme, the value of each character of the text
file is stored as bytes. So, while opening a text file, the text editor translates each ASCII value
and shows us the equivalent character that is readable by the human being. For example, the
ASCII value 65 (binary equivalent 1000001) will be displayed by a text editor as the letter
“A‟ since the number 65 in ASCII character set represents “A‟. Each line of a text file is
terminated by a special character, called the End of Line (EOL).

For example, the default EOL character in Python is the newline (\n). However, other
characters can be used to indicate EOL. When a text editor or a program interpreter
encounters the ASCII equivalent of the EOL character, it displays the remaining file contents
starting from a new line. Contents in a text file are usually separated by whitespace, but
comma (,) and tab (\t) are also commonly used to separate values in a text file.

[Link] Files: Binary files are also stored in terms of bytes (0s and 1s), but unlike text
files, these bytes do not represent the ASCII values of characters. Rather, they represent the
actual content such as image, audio, video, compressed versions of other files, executable
files, etc.

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 81


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

These files are not human readable. Thus, trying to open a binary file using a text editor will
show some garbage values. We need specific software to read or write the contents of a
binary file. Binary files are stored in a computer in a sequence of bytes. Even a single bit
change can corrupt the file and make it unreadable to the supporting application.

Also, it is difficult to remove any error which may occur in the binary file as the stored
contents are not human readable. We can read and write both text and binary files through
Python programs.

Creating and Reading Text Data

with open('[Link]', 'w') as file:

[Link]('Hello, world!\n')

[Link]('This is a new line.\n')

# Reading from a text file

with open('[Link]', 'r') as file:

content = [Link]()

print(content)

File Methods to Read and Write Data, Reading:

1) Open

2) Read/write

3) Close

1) open(): Python contains open() method to open a file. Syntax:

file_obj=open("filename","mode")

Ex: f=open('e:/[Link]','w')

List of file opening modes in Python:

1) r-read mode

2) w-write mode (overwrite mode)

3) a-append mode (appending at the end)

4) r+ - both read/write (it can‟t create file )

5) w+ - both read/write (file not exist it create file)

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 82


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

6) a+ - both read/write

7) rb -read binary

8) wb -write binary

9) ab - append binary

10) rb+ (r+b)

11) wb+ (w+b)

12) ab+ (a+b)

13) t text mode

14) x mode throws an error (if file does not exist)

2) Read/Write: After opening file user has to read or write data from file. For reading the
contents of file python contains the following methods:

[Link]()

[Link]()

[Link]()

For writing data into file python contains the following methods

1)write()

2)writelines()

3) close(): Last and final operation is closing, after finishing read/write, file has to close
by using „close()‟ method.

Syntax:

File_obj,close()

File Read Operations:

For reading data from file, Python contains the following methods:

1) read()

2) readline()

3) readlines()

1) read(): This method is used to read entire content from file.

Syntax:

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 83


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

[Link]()

OR

[Link](n) #n- is no. of characters to read

Program 1: (To read First ‘n’ characters from given input file)

file=input("Enter file name with extension:")

n=int(input("Enter no. of characters your want to read"))

try:

Input file:

f=open(file,'r')

print("First",n,"Characters are:",[Link](n)) except FileNotFoundError as e:

print("File or directory not exist")

[Link]()

Output:

2) readline():This function reads lines from that file and returns as a string. Syntax:

[Link]()

Program:

file=input("Enter file name with extension:")

try:

f=open(file,'r')

print("First line from given file is:",[Link]()) #It reads first line

except FileNotFoundError as e:

print("File or directory not exist") [Link]()

Output:

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 84


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

3) readlines():This function returns a list where each element is single line of that file.
(Including \n and spaces)

Syntax:

[Link]()

Program:

file=input("Enter file name with extension:")

try:

f=open(file,'r')

print("File content in the form of list :",[Link]())

except FileNotFoundError as e:

print("File or directory not exist") [Link]()

Output:

File Write Operations: For Writing information into file Python contains the following
methods.

1)write()

2)writelines()

1)write(): This function writes a fixed sequence of characters to a file.

Syntax:

[Link](“String information”)

Program

file=input("Enter file name with extension:")

name=input("Enter student name:")

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 85


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

no=input("Enter student number:")

try:

f=open(file,'a')

[Link]("Student name is:"+name)

[Link]("Student number is:"+no)

print("Data posted into file..")

[Link]()

except FileNotFoundError as e:

print("File or directory not exist")

Output:

Ms-word File is created with above information in ‘d:/[Link]” drive:

2)writelines():This function is also used to post some information into file but it writes data
int the form list of strings.

Syntax:

[Link](m) #m-is list of strings

Program:

file=input("Enter file name with extension:")

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 86


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

name=input("Enter student name:")

no=input("Enter student number:")

mail=input("Enter mail id:") student=[no,name,mail]

try:

f=open(file,'a') [Link]("Student data is:\n")

[Link](student)

print("Student Data posted into file..")

[Link]()

except FileNotFoundError as e:

print("File or directory not exist")

Output:

Above code automatically creates Ms-Excel file with the name „[Link]‟ in „D‟ Drive:

Reading and writing binary files

Reading and writing binary files in Python involves handling data in its raw byte format
rather than as text characters. This can be useful for working with non-text files such as
images, audio files, or any data that isn't meant to be interpreted as text.

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 87


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

Reading Binary Files

To read from a binary file, you typically use the `'rb'` mode when opening the file. Here’s
how you can read from a binary file:

def read_binary_file(input_file):

try:

with open(input_file, 'rb') as f:

# Read all bytes from the file

data = [Link]()

return data

except IOError:

print(f"Error reading from {input_file}")

return None

Ouput:

Writing Binary Files

To write to a binary file, you typically use the `'wb'` mode when opening the file. Here’s how
you can write to a binary file:

def write_binary_file(output_file, data):

try:

with open(output_file, 'wb') as f:

# Write data to the file

[Link](data)

print(f"Successfully wrote {len(data)} bytes to {output_file}")

except IOError:

print(f"Error writing to {output_file}")

# Write data to the binary file

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 88


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

write_binary_file(output_file, data)

Example for read and write

def copy_binary_file(input_file, output_file):

try:

with open(input_file, 'rb') as f_in:

with open(output_file, 'wb') as f_out:

# Read from input file and write to output file

data = f_in.read()

f_out.write(data)

print(f"Successfully copied {input_file} to {output_file}")

except IOError:

print(f"Error copying file from {input_file} to {output_file}")

Pickle module

The `pickle` module in Python is used for serializing and deserializing Python objects.
Serialization is the process of converting Python objects into a byte stream, and
deserialization is the process of converting the byte stream back into Python objects. This is
useful for saving Python objects to a file, sending them over a network, or storing them in a
database.

Basic Usage of `pickle`

Here's a simple example demonstrating how to use the `pickle` module to serialize and
deserialize Python objects:

import pickle

# Example object (a dictionary)

data = {'name': 'Alice', 'age': 30, 'city': 'Wonderland'}

# Pickle the object

with open('[Link]', 'wb') as f:

[Link](data, f)

print("Object pickled and saved to '[Link]'")

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 89


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

```

Deserializing (Unpickling) Python Objects

import pickle

# Unpickle the object

with open('[Link]', 'rb') as f:

loaded_data = [Link](f)

print("Object unpickled:", loaded_data)

Output:

Python Objects: `pickle` can handle most Python objects, including custom classes and
instances, nested data structures (lists, dictionaries), and more.

Security: Be cautious when unpickling data from untrusted sources, as `pickle` does not
provide secure deserialization and can execute arbitrary code.

Compatibility: Pickled files created with `pickle` in Python 2.x may not always be compatible
with Python 3.x due to differences in internal representation.

### Example with a Custom Class

You can also pickle and unpickle instances of custom classes:

import pickle

class Person:

def __init__(self, name, age):

[Link] = name

[Link] = age

# Create an instance of Person

person = Person('Bob', 25)

# Pickle the instance

with open('[Link]', 'wb') as f:

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 90


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

[Link](person, f)

print("Object pickled and saved to '[Link]'")

# Unpickle the instance

with open('[Link]', 'rb') as f:

loaded_person = [Link](f)

print("Object unpickled:", loaded_person.name, loaded_person.age)

Reading and writing CSV (Comma Separated Values) files:

Reading and writing CSV (Comma Separated Values) files in Python is a common task,
especially when dealing with tabular data. Python provides a built-in `csv` module that
simplifies the process of reading from and writing to CSV files.

Reading CSV Files

import csv

def read_csv_file(input_file):

data = []

with open(input_file, mode='r', newline='') as file:

reader = [Link](file)

for row in reader:

[Link](row)

return data

Output:

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 91


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

Writing CSV Files

import csv

def write_csv_file(output_file, data):

with open(output_file, mode='w', newline='') as file:

writer = [Link](file)

for row in data:

[Link](row)

OS Module

The `os` module provides a way of using operating system-dependent functionality, such as
reading or writing to the file system, creating or deleting directories, and more.

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 92


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

Methods

1. [Link]():- Returns the current working directory.

import os

print([Link]())

2. [Link](path):- Changes the current working directory to the specified path.

[Link]('/path/to/directory')

3. [Link](path): - Returns a list of entries in the specified directory.

print([Link]('.'))

4. [Link](path):- Creates a new directory at the specified path.

[Link]('new_directory')

5. [Link](path):- Removes the specified directory. The directory must be empty.

[Link]('new_directory')

6. [Link](path):- Removes the specified file.

[Link]('[Link]')

7. [Link](src, dst):- Renames a file or directory from `src` to `dst`.

[Link]('old_name.txt', 'new_name.txt')

8. [Link](command):- Executes a command in the system shell.

[Link]('ls -l')

[Link] Module

The `[Link]` module is a submodule of `os` and provides functions for interacting with the
file system pathnames.

Methods

1. [Link](path):- Returns the absolute path of the specified path.

print([Link]('[Link]'))

2. [Link](path):- Returns the base name of the pathname.

print([Link]('/path/to/[Link]')

3. [Link](path):- Returns the directory name of the pathname.

print([Link]('/path/to/[Link]'))

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 93


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

4. [Link](path): - Returns `True` if the specified path exists, `False` otherwise.

print([Link]('[Link]'))

5. [Link](path, *paths):- Joins one or more path components intelligently.

print([Link]('/path/to', 'directory', '[Link]'))

6. [Link](path):- Splits the pathname into a pair `(head, tail)` where `tail` is the last part
of the path and `head` is everything leading up to it.

print([Link]('/path/to/[Link]'))

7. [Link](path):- Splits the pathname into a pair `(root, ext)` where `ext` is the file
extension.

print([Link]('/path/to/[Link]'))

8. [Link](path):- Returns `True` if the specified path is an absolute path.

print([Link]('/path/to/[Link]'))

9. [Link](path): - Returns `True` if the specified path is a file.

print([Link]('[Link]'))

10. [Link](path):- Returns `True` if the specified path is a directory.

print([Link]('/path/to/directory'))

Object-Oriented Programming: Classes and Objects:

1) Object: Object is runtime entity or real world entity. Every object contains some
properties, those properties are called as data members, and operations performed on those
data members are called as methods or member functions.

Examples of Objects: Student, Book, Mobile, Car. Etc.

Object =data members+ methods Example: Student object contains

2)Class: class is a collection of object with similar features, and class is also called as
blueprint of an object, In Object oriented programming, object code is represented in the form
of classes. In python class is created with class keyword with the following syntax:

classclass_name:

var1=value var2=value

.........

defmethod_name(self): #instance method self.var1=value

self.var2=value

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 94


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

............

Body of the method defmethod_name(): #class method(without self)

body of the method

Ex:

class Student:

no=1200 #class variable

name='John' #class variable

defgetdata(self): #instance method

[Link]=1201 #instance variable

[Link]='Raj' #instance variable

def display(self):#instance method

print([Link],[Link])

def show(): #class method

print([Link],[Link])

[Link]() #class method directly access with class name

r=Student() #for instance method, definitely create object

[Link]()

[Link]()

Creating Classes in Python and Creating Objects in Python

Example Program (classes and objects)

class Student:

address=input('Enter student address')

def display(self):

print("Given student number is:",[Link])

print("Given Student name is:",[Link])

print("Given student address is:",[Link])

r=Student() #object creation

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 95


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

[Link]()

s=Student() #Object creation [Link]() [Link]()defgetdata(self):

[Link]=input('Enter student number')

[Link]=input('Enter student name')

[Link]

[Link]()

Output:

Example: 2 (addition of 2 numbers using classes and objects) class Addition:

def getData(self,a,b):

self.a=a

self.b=b

def add(self):

self.c=self.a+self.b

def display(self):

print('addition is',self.c)

r=Addition()

x=int(input('Enter first integer'))

y=int(input('Enter Second integer'))

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 96


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

[Link](x,y)

[Link]()

[Link]()

Output:

Constructor Methods in Python:

Constructor is a type of method used to initialize object members in a class. Generally there
are two types of constructors in Python. Constructor in Python is defined as init__(self)
method. ‘init(self)’ method prefix and suffix with two under scores. No separate calling for
constructors, they automatically called at the time of object creation.

Types of constructors:

• Default constructor.

• Parameterized constructor.

• Default Constructor: A constructor which do not take any parameter except „self‟ is
called as default constructor.

Syntax:

classclass_name:

def init (self): #default constructor body of the constructor

Example Program:

class Student:

def init (self): #default constructor

[Link]="John"

[Link]="Gudlavalleru"

[Link]='AP'

def display(self): #instancemethod print([Link],[Link],[Link])

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 97


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

r=Student() #this line directly calls the default constructor

[Link]()

Output:

John Gudlavalleru AP

Parameterized Constructor: A constructor which contains parameters additional to „self‟ is


called as parameterized constructor. Parameters for the constructor are passed at the time
of object creation.

Syntax:

classclass_name:

def init (self,arg1,arg2,…..):#parameterized constructor body of the constructor

Example program:

class Student:

def init (self,name,address,state):#parameterized constructor

[Link]=name

[Link]=address

[Link]=state

def display(self): #instancemethod print([Link],[Link],[Link])

r=Student('John','Gudlavalleru','AP') #this line calls the constructor

[Link]()

Classes with Multiple Objects:

# Creating multiple objects

car1 = Car('Toyota', 'Camry', 2020)

car2 = Car('Honda', 'Accord', 2021)

car3 = Car('Tesla', 'Model 3', 2022)

# Accessing attributes and methods of the objects

print([Link]()) # Output: 2020 Toyota Camry

print([Link]()) # Output: 2021 Honda Accord

print([Link]()) # Output: 2022 Tesla Model 3

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 98


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

print(car1.start_engine()) # Output: The engine of Toyota Camry is now running.

print(car2.start_engine()) # Output: The engine of Honda Accord is now running.

print(car3.start_engine()) # Output: The engine of Tesla Model 3 is now running.

Class Attributes

 Definition: Class attributes are attributes that are shared among all instances of a
class. They are defined within the class construction but outside any instance
methods.
 Scope: They are shared by all instances of the class. Changing the value of a class
attribute will affect all instances of the class.

Instance (Data) Attributes

 Definition: Instance attributes are attributes that are unique to each instance of a class.
They are defined within methods (usually __init__) and are prefixed with self.
 Scope: They are specific to each instance. Changing the value of an instance attribute
will only affect that particular instance.

Data encapsulation: Wrapping up of data and functions into single unit is called as data
encapsulation. Python classes contain both data and methods.

Inheritance: The process of deriving one class from already existing class is called as
inheritance or a class shares the properties of another class is called as inheritance.

Already existing class is called as base class or super class or parent class, and newly
derived class is called as sub class or derived class or child class. In python two classes are
combined with parenthesis symbols ( ) for inheritance.

Syntax:

Class derivedclassname(base classname):

body of the class

Python supports all types of inheritances including multiple, multipath and hybrid.

Types of inheritances:

A) Single or simple inheritance (1:1)

B) Multiple inheritance (N:1)

C) Hierarchical inheritance (1:N) --->Most commonly used inherintace

D) Multi-level inheritance (1:1:1:….)

E) Multipath Inheritance

F) Hybrid Inheritance.

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 99


II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

A) Single Inheritance: Single inheritance contains only one base class and only one child
class.

Example program:

class A: #base class

def display(self):

print('hai')

class B(A): #inheritance, B-derived class shares the properties of class A

def show(self):

print('hello')

r=B()

[Link]()

[Link]()

B) Multiple inheritance: Basically Java does not support multiple inheritance, Only C++ is
the language supports multiple inheritance, Python also supports multipleinheritance of
classes. In multiple inheritance More number of base classes are derived to sub class.

Example Program:

class A:

def display1(self):

print("I am class A")

class B:

def display2(self):

print("I am class B")

class C:

def display3(self):

print("I am class C")

class D(A,B,C): #multiple inheritance

def display4(self):

print("I am class D")

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 100
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

r=D()

r.display1()

r.display2()

r.display3()

r.display4()

Output:

C) Hierarchical Inheritance: It is most commonly used inheritance; most of the applications


are designed with the concept of Hierarchical inheritance. This inheritance contains only one
base class, more number of derived classes.

Example Program:

class A:

def display1(self):

print("I am class A")

class B(A):

def display2(self):

print("I am class B")

class C(A):

def display3(self):

print("I am class C")

class D(A):

def display4(self):

print("I am class D") r1=B()

r2=C()

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 101
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

r3=D()

r1.display1()

r1.display2()

r2.display3()

r3.display4()

Output:

D) Multi-Level Inheritance: It is an extension of single level inheritance, One base class


derived to one derived class, and that derived class further derived to another derived class
and so on.

Example Program:

class A:

def display1(self):

print("I am class A")

class B(A):

def display2(self):

print("I am class B")

class C(B):

def display3(self):

print("I am class C")

class D(C):

def display4(self):

print("I am class D") r1=D()

r1.display1()

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 102
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

r1.display2()

r1.display3()

r1.display4()

Output:

E) Multi-Path Inheritance: Multi-path inheritance is also supported in Python, A derived


class contains more than one path from grandparent class, and then it is called as Multi-
path inheritance. Cycles formed in Multipath inheritance.

Example Program:

class A:

def display1(self):

print("I am class A")

class B(A):

def display2(self):

print("I am class B")

class C(A):

def display3(self):

print("I am class C")

class D(B,C): #two paths from class A to D

def display4(self):

print("I am class D")

r1=D()

r1.display1()

r1.display2()

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 103
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

r1.display3()

r1.display4()

F) Hybrid Inheritance: Hybrid inheritance is supported in Python, It is a combination of


other inheritances.

Example Program:

class A:

def display1(self):

print("I am class A")

class B(A): #Single inheritance

def display2(self):

print("I am class B")

class C:

def display3(self):

print("I am class C")

class D(B,C): #multiple inheritance

def display4(self):

print("I am class D") r1=D()

r1.display1()

r1.display2()

r1.display3()

r1.display4()

Output:

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 104
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

Polymorphism: One name many forms is the concept of polymorphism. In Python


polymorphism is achieved with the following mechanisms.

1) Method Overloading (with Default arguments)

2) Operator Overloading.

3) Method Overriding

4) ABC (Abstract Base Classes)

1) Method Overloading: Python does not allow same function name with multiple times. So
direct method overloading is not supported in Python. By specifying default arguments in a
function, python achieves method overloading.

Example program:

class Addition:

def add(self,a=4,b=4,c=6): #default arguments

print('Addition is',a+b+c)

r=Addition()

[Link]() #add with no args.

[Link](10) #add with single arg

[Link](10,20) #add with 2 args

[Link](10,20,30) #add with 3 args

Output:

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 105
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

2) Operator Overloading: Generally, Operator overloading is supported in C++, Python


also contains Operator Overloading concept. With this operator overloading, Operators are
directly applied to Objects instead of variables. One Operator for more number of variables
(one name many forms), it is also a type of compile time polymorphism. Python contains
some magic functions or dunder functions for all python operators to achieve operator
overloading. A function which prefixes and suffixes with double underscores is called as
magic method or dunder method.

Following are the list of Magic methods available to perform arithmetic operators
overloading.

+ add (self, other)

– sub (self, other)

* mul (self, other)

/ truediv (self, other)

// floordiv (self, other)

% mod (self, other)

** pow (self, other)

Example program (to overload Arithmetic +):

class Addition:

defgetdata(self):

self.a=int(input('Enter a value'))

self.b=int(input('Enter b value'))

self.c=int(input('Enter c value'))

self.d=int(input('Enter d value'))

def add (self,x): #Operator overload with add () magic method x.a=self.a+x.a

x.b=self.b+x.b

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 106
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

x.c=self.c+x.c

x.d=self.d+x.d

return x

def display(self):

print(self.a,self.b,self.c,self.d)

r=Addition()

[Link]()

v=Addition()

[Link]()

x=Addition()

x=r+v # + goes to add (self) overload magic method

[Link]()

3) Method Overriding: It is runtime polymorphism mechanism, both derived class and base
class contains same method signature then that method is called as overriding method. In
such case derived class method overrides base class method.

Example program:

classAirtel:

defgetConnection(self):

print("Airtel connection established...")

classJio(Airtel):

defgetConnection(self): #overridden method

print("Jio connection established...") a=Jio()

[Link]() #this method overrides base class method Output:

Jio connection established...

Note: ‘@final’ annotation is used to prevent method overriding and class inheritance,

which is supported in python 3.8 and above versions only.

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 107
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

super()’ function in Python: „super()‟ function is used to access super class members into
derived class. Overridden methods and constructors are also accessed with „super()‟
function. Example program: (With Overridden methods)

class Airtel:

defgetConnection(self):

print("Airtel connection established...")

class Jio(Airtel):

defgetConnection(self): #overridden method

super().getConnection()

print("Jio connection established...") a=Jio()

[Link]()

Output:

Airtel connection established...

Jio connection established...

Note: Base class constructors are also accessed in derived class with „super()‟ function.

[Link] a program to sort words in a file and put them in another file. The output
file should have only lower-case words, so any upper-case words from source must
be lowered.

def sort_words(input_file, output_file):

# Read words from input file

with open(input_file, 'r') as f:

words = [Link]().split()

# Convert all words to lowercase

words = [[Link]() for word in words]

# Sort the words alphabetically

[Link]()

# Write sorted words to output file

with open(output_file, 'w') as f:

for word in words:

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 108
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

[Link](word + '\n')

print(f"Sorted words have been written to {output_file}")

# Example usage:

input_file = r'C:\Users\kotes\OneDrive\Desktop\[Link]' # Replace with your input file


name

output_file = r'C:\Users\kotes\OneDrive\Desktop\[Link]' # Replace with your desired


output file name

sort_words(input_file, output_file)

output:

[Link] program to print each line of a file in reverse order.


file=input("Enter file name with extension:")
try:
f=open(file,'r')
print("Reverse of each and every line from given file is:")
for i in [Link]():
print(i[::-1],end='')
[Link]()

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 109
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

except FileNotFoundError as e:
print("File or directory not exist")

3. Python program to compute the number of characters, words and lines in a file.

file=input("Enter file name with extension:")


v=w=c=0
try:
f=open(file,'r')
m=list([Link]())
for i in m:
if i=='\n':
v=v+1
if i==' ' or i=='\n':
w=w+1
if [Link]():
c=c+1
[Link]()
print("No. of characters: ",c)
print("No. of words: ",w+1)
print("No. of lines: ",v+1)
except FileNotFoundError as e:
print("File or directory not exist")

OR

file=input("Enter file name with extension:")


v=w=c=0
try:
f=open(file,'r')
m=[Link]()
for i in m:
v=v+1
for j in [Link]():
w=w+1
for k in j:
if [Link]():
c=c+1
[Link]()
print("No. of characters: ",c)
print("No. of words: ",w)
print("No. of lines: ",v)

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 110
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

except FileNotFoundError as e:
print("File or directory not exist")

[Link] a program to create, display, append, insert and reverse the order of the
items in the array.

def create_array():
return []

def display_array(arr):
print("Array:", arr)

def append_to_array(arr, item):


[Link](item)

def insert_to_array(arr, index, item):


[Link](index, item)

def reverse_array(arr):
return arr[::-1]

def main():
# Create array
arr = create_array()
display_array(arr)

# Append items to array


append_to_array(arr, 1)

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 111
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

append_to_array(arr, 2)
append_to_array(arr, 3)
display_array(arr)

# Insert item at specific position


insert_to_array(arr, 1, 4) # Insert 4 at index 1
display_array(arr)

# Reverse the array


arr = reverse_array(arr)
display_array(arr)

if __name__ == "__main__":
main()

Output:

5. Write a program to add, transpose and multiply two matrices.

import numpy as np
def add_matrices(matrix1, matrix2):
if [Link] != [Link]:
raise ValueError("Matrices must have the same dimensions to be added.")
return matrix1 + matrix2
def transpose_matrix(matrix):
return [Link](matrix)
def multiply_matrices(matrix1, matrix2):
if [Link][1] != [Link][0]:
raise ValueError("Number of columns in the first matrix must equal the
number of rows in the second matrix.")
return [Link](matrix1, matrix2)
def main():
# Define two matrices
matrix1 = [Link]([[1, 2, 3],
[4, 5, 6]])
matrix2 = [Link]([[7, 8, 9],
[10, 11, 12]])

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 112
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

print("Matrix 1:")
print(matrix1)
print("\nMatrix 2:")
print(matrix2)

# Add matrices
try:
sum_matrix = add_matrices(matrix1, matrix2)
print("\nSum of Matrix 1 and Matrix 2:")
print(sum_matrix)
except ValueError as e:
print(e)

# Transpose matrices
transpose_matrix1 = transpose_matrix(matrix1)
transpose_matrix2 = transpose_matrix(matrix2)
print("\nTranspose of Matrix 1:")
print(transpose_matrix1)
print("\nTranspose of Matrix 2:")
print(transpose_matrix2)
# Define two matrices for multiplication
matrix3 = [Link]([[1, 2],
[3, 4],
[5, 6]])
matrix4 = [Link]([[7, 8],
[9, 10]])

print("\nMatrix 3:")
print(matrix3)
print("\nMatrix 4:")
print(matrix4)

# Multiply matrices
try:
product_matrix = multiply_matrices(matrix3, matrix4)
print("\nProduct of Matrix 3 and Matrix 4:")
print(product_matrix)
except ValueError as e:
print(e)

if __name__ == "__main__":
main()

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 113
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

[Link] a Python program to create a class that represents a shape. Include


methods to calculate its area and perimeter. Implement subclasses for different
shapes like circle, triangle, and square.

import math

class Shape:

def area(self):

raise NotImplementedError("Subclass must implement this method")

def perimeter(self):

raise NotImplementedError("Subclass must implement this method")

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 114
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

class Circle(Shape):

def __init__(self, radius):

[Link] = radius

def area(self):

return [Link] * [Link] ** 2

def perimeter(self):

return 2 * [Link] * [Link]

class Square(Shape):

def __init__(self, side_length):

self.side_length = side_length

def area(self):

return self.side_length ** 2

def perimeter(self):

return 4 * self.side_length

class Triangle(Shape):

def __init__(self, a, b, c):

self.a = a

self.b = b

self.c = c

def area(self):

# Using Heron's formula

s = (self.a + self.b + self.c) / 2

return [Link](s * (s - self.a) * (s - self.b) * (s - self.c))

def perimeter(self):

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 115
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23

return self.a + self.b + self.c

def main():

shapes = [

Circle(5),

Square(4),

Triangle(3, 4, 5)

for shape in shapes:

print(f"{shape.__class__.__name__}:")

print(f" Area: {[Link]()}")

print(f" Perimeter: {[Link]()}\n")

if __name__ == "__main__":

main()

Output:

Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 116

You might also like