100% found this document useful (1 vote)
91 views80 pages

2-1 Python Manual

Uploaded by

CH NARAYANARAO
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
100% found this document useful (1 vote)
91 views80 pages

2-1 Python Manual

Uploaded by

CH NARAYANARAO
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

BEHARA COLLEGE OF

ENGINEERING & TECHNOLOGY


88th ward, G.V.M.C, NARAVA,
VISAKHAPATNAM

PYTHON PROGRAMMING
(Skill Enhancement Course)
LABORATORY MANUAL
SCHEME:R23

ACADEMIC YEAR: 2025-26


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
88th ward, G.V.M.C, NARAVA, VISAKHAPATNAM
VISION

To Excel in the emerging areas of Computer Science and Engineering by


imparting quality education , relevant practices and inculcating human values
to transform the students as potential resources to contribute innovatively to
meet industrial needs and social expectations.

MISSION

M1: To provide strong fundamentals and value - based technical education for
Computer Science applications through effective teaching learning
methodologies.

M2: To transform lives of the students by nurturing ethical values, creativity


and novelty to become Entrepreneurs and establish start-ups.

M3: To Impart high quality experiential learning to get expertise in modern


software tools and to cater to the real time requirements of the industry

M4: To provide a conducive environment for faculty to engage in and train


students in progressive and convergent research themes through
collaborative linkages with industry and academia by establishing
Centres of Excellence.

M5: To inculcate problem solving and team building skills and promote
lifelong learning with a sense of societal and ethical responsibilities.
PROGRAM OUTCOMES (POS)
Engineering Graduates will be able to:
PO1.ENGINEERING KNOWLEDGE: Apply the knowledge of mathematics, science,
engineering fundamentals, and an engineering specialization to the solution of complex
engineering problems.

PO2.PROBLEM ANALYSIS: Identify, formulate, review research literature, and analyze


complex engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.

PO3.DESIGN/DEVELOPMENT OF SOLUTIONS: Design solutions for complex engineering


problems and design system components or processes that meet the specified needs with
appropriate consideration for the public health and safety, and the cultural, societal, and
environmental considerations.

PO4.CONDUCT INVESTIGATIONS OF COMPLEX PROBLEMS: Use research-based


knowledge and research methods including design of experiments, analysis and
interpretation of data, and synthesis of the information to provide valid conclusions.

PO5.MODERN TOOL USAGE: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modelling to complex engineering
activities with an understanding of the limitations.

PO6. THE ENGINEER AND SOCIETY: Apply reasoning informed by the contextual
knowledge to assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
PO7.ENVIRONMENT AND SUSTAINABILITY: Understand the impact of the professional
engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.

PO8.ETHICS: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.

PO9.INDIVIDUAL AND TEAM WORK: Function effectively as an individual, and as a


member or leader in diverse teams, and in multidisciplinary settings.

PO10.COMMUNICATION: Communicate effectively on complex engineering activities with


the engineering community and with society at large, such as, being able to comprehend
and write effective reports and design documentation, make effective presentations, and
give and receive clear instructions.

PO11.PROJECT MANAGEMENT AND FINANCE: Demonstrate knowledge and


understanding of the engineering and management principles and apply these to one’s own
work, as a member and leader in a team, to manage projects and in multidisciplinary
environments.

PO12.LIFE-LONG LEARNING: Recognize the need for, and have the preparation and ability
to engage in independent and life-long learning in the broadest context of technological
change.
Program Specific Outcomes (PSOs)
The Computer Science & Engineering graduate will
The Computer Engineering Graduates are able to understand,
analyze and develop computer programs in the areas related to
PSO-1 Professional Skills: algorithms, system software, multimedia, web design, big data
analytics and networking for efficient design of computer based
systems of varying complexity.
The Computer Engineering Graduates are able to employ modern
Successful Career computer languages, environments, and platforms in creating
PSO-2 and innovative career paths to be an entrepreneur and enthusiastic
Entrepreneurship: for higher studies/employability in the field of Computer Science
& Engineering.

Program Educational Objectives (PEOs)


The Programme Educational Objectives of the B.Tech in Computer Science & Engineering
programme are given below and are numbered from PEO1 to PEO4.
To provide the graduates with solid foundation in computer science and engineering
along with fundamentals of Mathematics and Sciences in formulating, analyzing,
PEO-1
designing, modelling, programming and implementation with global competence
and helps the graduates for life-long learning.
To Promote collaborative learning and team work spirit through multi -disciplinary
projects and diverse professional activities and prepare graduates with recent
technological developments related to core subjects like programming, databases,
PEO-2
design of compilers and Network Security aspects and future technologies so as to
contribute effectively for Research & Development by participating in professional
activities like publishing and seeking copy rights.
To train graduates to choose a decent career option either in high degree of
employability /Entrepreneur or, in higher education by empowering students with
PEO-3
sustainable progress, ability to handle critical situations and training to excel in
competitive examinations.

To exhibit professionalism, ethical attitude, communication, managerial skills,


PEO-4 teamwork, and social responsibility in their profession and adapt to current
trends by engaging in continuous learning.
GENERAL INSTRUCTIONS

Do’s
1. Please leave footwear outside the laboratory at the designated place.
2. Please keep your belongings such as bags in the designated place.
3. Students must present a valid ID card before entering the computer lab.
4. Maintain Discipline in the laboratory.
5. Work on the designated computers only.
6. Do keep your computer and workspace clean and organized.
7. Do save your work frequently to avoid data loss.
8. Do follow ethical guidelines and respect copyright when using digital resources.
9. Students must inform the in-charge Lecturer of any observed hardware or software
failures.
10. Turn off the respective systems and arrange the chairs before you leaving the laboratory.

Don’ts
1. Don’t touch the computer with a pen or pencil.
2. Don’t eat or drink near your computer.
3. Don’t touch wires or cables when the computer is on.
4. Do not install, uninstall or alter any software on the computer.
5. Students are not allowed to use personal Pen Drives, CDs, DVDs etc., in a Computer
Lab. Only prescribed official Pen Drives, CDs, DVDs etc. will be used in the Computer
Lab to avoid VIRUS in Computers.
6. The use of cell phones is prohibited in the computer lab.
7. Don’t forget to turn off your computer before leaving.
II Year B.Tech. CSE- I Sem

Course Objectives:
The main objectives of the course are to
• Introduce core programming concepts of Python programming language.
• Demonstrate about Python data structures like Lists, Tuples, Sets and dictionaries
• Implement Functions, Modules and Regular Expressions in Python Programming and to
create practical and contemporary applications using these

Course Outcomes:
After completion of the course, students will be able to
1. showcase adept command of Python syntax, deftly utilizing variables, data types, control
structures, functions, modules, and exception handling to engineer robust and efficient
code solutions. (L4)
2. apply Python programming concepts to solve a variety of computational problems (L3)
3. understand the principles of object-oriented programming (OOP) in Python, including
classes, objects, inheritance, polymorphism, and encapsulation, and apply them to design
and implement Python programs (L3)
4. become proficient in using commonly used Python libraries and frameworks such as
JSON, XML, NumPy, pandas (L2)
5. exhibit competence in implementing and manipulating fundamental data structures such
as lists, tuples, sets, dictionaries (L3)

UNTI-I:
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.

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 Strings.
Lists: Creating Lists, Basic List Operations, Indexing and Slicing in Lists, Built-In Functions
Used on Lists, List Methods, del Statement.
Sample Experiments:
7. Write a program to define a function with multiple return values.
8. Write a program to define a function using default arguments.
9. Write a program to find the length of the string without using any library functions.
10. Write a program to check if the substring is present in a given string or not.
11. Write a program to perform the given operations on a list:
i. Addition ii. Insertion iii. slicing
12. Write a program to perform any 5 built-in functions by taking any list.

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:
13. Write a program to create tuples (name, age, address, college) for at least two members
and concatenate the tuples and print the concatenated tuples.
14. Write a program to count the number of vowels in a string (No control flow allowed).
15. Write a program to check if a given key exists in a dictionary or not.
16. Write a program to add a new key-value pair to an existing dictionary.
17. Write a program to sum all the items in a given dictionary.

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 os.path 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:
18. Write a program to sort words in a file and put them in another file. The output files
should have only lower-case words, so any upper-case words from source must be
lowered.
19. Python program to print each line of a file in reverse order.
20. Python program to compute the number of characters, words and lines in a file.
21. Write a program to create, display, append, insert and reverse the order of the items in
the array.
22. Write a program to add, transpose and multiply two matrices.
23. 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.

UNIT-V:
Introduction to Data Science: Functional Programming, JSON and XML in Python, NumPy
with Python, Pandas.
Sample Experiments:
24. Python program to check whether a JSON string contains complex object or not.
25. Python Program to demonstrate NumPy arrays creation using array () function.
26. Python program to demonstrate use of ndim, shape, size, dtype.
27. Python program to demonstrate basic slicing, integer and Boolean indexing.
28. Python program to find min, max, sum, cumulative sum of array
29. Create a dictionary with at least five keys and each key represent value as a list where
this list contains at least ten values and convert this dictionary as a pandas data frame
and explore the data through the data frame as follows:
a) Apply head () function to the pandas data frame
b) Perform various data selection operations on Data Frame
30. Select any two columns from the above data frame, and observe the change in one
attribute with respect to other attribute with scatter and plot operations in matplotlib

Reference Books:
1. Gowri shankar S, Veena A., Introduction to Python Programming, CRC Press.
2. Python Programming, S Sridhar, J Indumathi, V M Hariharan, 2nd Edition, Pearson,
2024
3. Introduction to Programming Using Python, Y. Daniel Liang, Pearson.

Online Learning Resources/Virtual Labs:


1. https://www.coursera.org/learn/python-for-applied-data-science-ai
2. https://www.coursera.org/learn/python?specialization=python#syllabusOBJECT
PYTHON PROGRAMMING INDEX
TABLE OF CONTENTS

EXP NAME OF THE PAGE


NO: EXPERIMENT: NO:
INTRODUCTION 1-21

UNIT– 1:
1. Write a program to find the largest element among three Numbers.
1 2. Write a Program to display all prime numbers within an interval 22-27
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.
UNIT- 2
7. Write a program to define a function with multiple return values.
2 8. Write a program to define a function using default arguments.
9. Write a program to find the length of the string without using 28-31
any library functions.
10. Write a program to check if the substring is present in a given
string or not.
11. Write a program to perform the given operations on a list:
i. Addition ii. Insertion iii. slicing
12. Write a program to perform any 5 built-in functions by taking
any list.
3 UNIT- 3
32-36
13. Write a program to create tuples (name, age, address, college)
for at least two members and concatenate the tuples and print the
concatenated tuples.
14. Write a program to count the number of vowels in a string (No
control flow allowed).
15. Write a program to check if a given key exists in a dictionary
or not.
16. Write a program to add a new key-value pair to an existing
dictionary.
17. Write a program to sum all the items in a given dictionary.
UNIT - 4 37-49
4 18. Write a program to sort words in a file and put them in another
file. The output files should have only lower-case words, so any
upper-case words from source must be lowered.
19. Python program to print each line of a file in reverse order.
20. Python program to compute the number of characters, words
and lines in a file.
21. Write a program to create, display, append, insert and reverse
the order of the items in the array.
22. Write a program to add, transpose and multiply two matrices.
23. 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.

5 UNIT- 5 50-66
24. Python program to check whether a JSON string contains
complex object or not.
25. Python Program to demonstrate NumPy arrays creation using
array () function.
26. Python program to demonstrate use of ndim, shape, size, dtype.
27. Python program to demonstrate basic slicing, integer and
Boolean indexing.
28. Python program to find min, max, sum, cumulative sum of
array
29. Create a dictionary with at least five keys and each key
represent value as a list where this list contains at least ten values
and convert this dictionary as a pandas data frame and explore the
data through the data frame as follows:
a) Apply head () function to the pandas data frame
b) Perform various data selection operations on Data Frame
30. Select any two columns from the above data frame, and observe
the change in one attribute with respect to other attribute with
scatter and plot operations in matplotlib
UNTI-I: 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.

History of Python Programming Language:

Python is a widely used general-purpose, high-level programming language. It was initially


designed by Guido van Rossum in 1991 and developed by Python Software Foundation. It
was mainly developed for emphasis on code readability, and its syntax allows programmers to
express concepts in fewer lines of code.

o Python laid its foundation in the late 1980s.


o The implementation of Python was started in December 1989 by Guido Van Rossum at
CWI in Netherland.
o In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to
alt.sources.
o In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce.
o Python 2.0 added new features such as list comprehensions, garbage collection systems.
o On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to
rectify the fundamental flaw of the language.
o ABC programming language is said to be the predecessor of Python language, which was
capable of Exception Handling and interfacing with the Amoeba Operating System.
o The following programming languages influence Python:
o ABC language.
o Modula-3

Why the Name Python?

There is a fact behind choosing the name Python. Guido van Rossum was reading the script of a
popular BBC comedy series "Monty Python's Flying Circus". It was late on-air 1970s.

Van Rossum wanted to select a name which unique, sort, and little-bit mysterious. So he decided
to select naming Python after the "Monty Python's Flying Circus" for their newly created
programming language.

1
The comedy series was creative and well random. It talks about everything. Thus it is slow and
unpredictable, which made it very interesting.

• Python is also versatile and widely used in every technical field, such as Machine
Learning, Artificial Intelligence, Web Development, Mobile Application, Desktop Application,
Scientific Calculation, etc.
• Thrust Areas of Python
• Web Development. The programming language is used in back-end logic of web applications. ...
• Data Science. Data is the new oil and companies around the world have acknowledged it. ...
• Artificial intelligence and machine learning. ...
• Embedded applications. ...

• Game development. Python is open source: The Python implementation is under an


open source license that makes it freely usable and distributable, even for commercial
use.
• Python is interpreted: Python is a high level language which is interpreted by a Python
interpreter.
• Python is cross platform compatible: Python can be executed on all major platforms
like Windows, Linux/Unix, OS/2, Mac and others.
• Python is Object-Oriented: In Python, we encapsulate data within the objects as it
supports the object-oriented style of programming.
• Python is a great choice for new learners: Python is easy to learn and follows a simple
syntax, so it is a good choice for beginner programmers. Python also supports wide range
of application development.
• Python is extensible: Python has a wide range of libraries and built-in functions which
helps in easy and rapid development of applications.
• Python is interactive: Python users are provided a command prompt where
they can interact directly with the interpreter to write programs.
• Database connectivity: Python provides interfaces required to connect to all major
databases like Oracle, MySQL, PostgreSQL and others.

Identifiers:

In Python, variables, functions, classes, modules and objects are identified using a name
known as an identifier. An identifier can start with an uppercase or lowercase character or
an underscore (_) followed by any number of underscores, letters and digits. All
identifiers in Python are case sensitive.
Example: weight=10
In the above example, weight is an identifier.

2
Keywords:

Keywords are the reserved words in Python. So keywords cannot be used as identifiers
or to name variables and functions. Few of the keywords are listed below.

Example: if, else, elif, for, where, break, continue

Declaring a variable:

Syntax: var_name = literal_value

where var_name is the name given to the container holding the value specified as literal_value in
the syntax above.

Example: weight=10

In the above example, weight is the container holding the value 10 which can change during the
execution of the program.

Python may have data belonging to different types. Common data types used in programming are
listed below:

Category Datatype Example


int 123
Numeric
long 1237126381763817
float 123.45
Numeric with decimal point
double 123123.32345324
char A
Alphanumeric
string Hello
Boolean boolean True, False

Python is a dynamically typed language!

In the above example, no datatype was mentioned at the time of declaring variable. In Python,
the datatype of a variable is decided automatically at the time of execution based on the
value assigned to it. This is called as dynamic typing.

3
num=65 #line 1

num="A" #line 2

In line 1, variable num is assigned a value 65 which is an integer, so the data type
of num variable is integer in line 1.

In line 2, variable num is assigned a value “A” which is a string, so the data type of
the num variable is string in line 1.

Note: To check the datatype of the variable we can use type(var_name) which in turn returns
the datatype of the variable.

Example:

1. num=65
2. print(num,type(num))
3. num="A"

4. print(num,type(num))

Output:

65<class'int'>
A <class 'str'>

The input() function:

Python provides the input() built-in function to read an input from the user using the standard
input device (i.e. keyboard). The input() function always returns string data irrespective of
the type of data entered through the keyboard.

Syntax: var_name = input([“interactive statement”])

where,

var_name is the variable assigned with the string value which is read using input method.

Interactive statement is the statement displayed to the user expecting the response from them.

Example:

4
1. input_var=input("please enter the value")

2. print(input_var)

sample output:

please enter the value100


100

The print() function:

Python provides the print() built-in function to display the output onto the standard output
device (i.e. Monitor)

Syntax: print(“var_name1, var_name2)

where,

var_name1, var_name2 are the variable names or the literals you want to print or output

Statements and Expressions:

Statements

A statement is an instruction that the Python interpreter can execute. There are various types of
statements in Python, including:

1. Assignment Statement:

Example: x = 5 name = "Alice"

2. Control Flow Statements:

if x > 0:

print("x is positive")

elif x == 0:

5
print("x is zero")

else:

print("x is negative")

Loops:

• For Loop:

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

While Loop:

while x > 0:
print(x)
x -= 1

• Function Definition:

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

• Class Definition:

class Dog:
def __init__(self, name):
self.name = name

def bark(self):
return "Woof!"

• Import Statement:

import math
from datetime import datetime

• Exception Handling:

try:
result = 10 / 0
except ZeroDivisionError:

6
print("Cannot divide by zero")

Expressions

An expression is a combination of values, variables, operators, and calls to functions that the
interpreter evaluates and produces another value. Expressions can be used wherever Python
expects a value

1. Arithmetic Expressions:

2 + 3 * 4 - 5 #
Results in 9

2. Boolean Expressions:

5 > 3 # True
x == 10 # Evaluates to True or False depending on the value of x

3. String Expressions:

"Hello, " + "world!" # Results in "Hello, world!"

4. Function Calls:

len("Python") # Results in 6

5. List Comprehensions:

[x * 2 for x in range(5)] # Results in [0, 2, 4, 6, 8]

6. Lambda Expressions:

(lambda x: x + 1)(5) # Results in 6

Combining Statements and Expressions

Statements can contain expressions, and expressions can appear within statements.

For example:

x = 10 Assignment statement
y = x * 2 Assignment statement with an expression

7
if y > 15: Conditional statement with an expression
print("y is greater than 15") # Print statement

Understanding the difference between statements and expressions is crucial for writing efficient
and readable Python code. Statements control the flow of the program, while expressions
compute values

Variables:

In Python, variables are used to store data values. A variable is essentially a name that refers to a
value. Python is dynamically typed, which means that you don't have to declare the type of a
variable when you create one. The type of the variable is determined by the value assigned to it.
Here's a detailed overview of variables in Python:

Creating and Assigning Variables

To create a variable, you simply assign a value to a name using the = operator.

Example:

x = 5
name = "Alice"
is_active = True

Naming Rules and Conventions

1. Names can contain letters, digits, and underscores (_).

user_name = "Alice"
user1 = "Bob"

2. Names must start with a letter or an underscore.

_private_variable = "secret"

3. Names cannot start with a digit.

1user = "Alice" # This will cause a syntax error

4. Names are case-sensitive.

name = "Alice"
Name = "Bob"

8
5. Avoid using Python reserved keywords as variable names.

for = 5 # This will cause a syntax error

Types of Variables

Python variables can hold different types of values, and the type is determined at runtime. Here
are some common types:

1. Integer:

age = 30

2. Float:

price = 19.99

3. String:

name = "Alice"

4. Boolean:

is_active = True

5. List:

colors = ["red", "green", "blue"]

6. Tuple:

point = (10, 20)

7. Dictionary:

person = {"name": "Alice", "age": 30}

8. Set:

unique_numbers = {1, 2, 3, 4, 5}

Variable Scope

The scope of a variable determines where in the code a variable can be accessed.

9
1. Local Scope: Variables created inside a function belong to the local scope of that
function and can only be used inside that function.

def my_function():
x = 10 # Local scope
print(x)

my_function()
print(x) # This will cause an error because x is not defined outside
the function

2. Global Scope: Variables created outside of all functions are in the global scope and can
be used anywhere in the code.

y = 20 # Global scope

def my_function():
print(y)

my_function()
print(y)

3. Global Keyword: To modify a global variable inside a function, you can use the global
keyword.

z = 30

def my_function():
global z
z = 40

my_function()
print(z) # This will print 40

Variable Type Casting

Sometimes, you may need to convert a variable from one type to another.

1. Integer to String:

x = 10
y = str(x) # y is now "10"

2. String to Integer:

a = "5"

10
b = int(a) # b is now 5

3. String to Float:

c = "3.14"
d = float(c) # d is now 3.14

4. Integer to Float:

e = 7
f = float(e) # f is now 7.0

Understanding variables and how to use them effectively is fundamental to programming in


Python. They allow you to store, manipulate, and retrieve data in your programs.

Operators:

In Python, operators are special symbols or keywords that are used to perform operations on
variables and values. Python provides a variety of operators that can be categorized into several
groups based on their functionality:

1. Arithmetic Operators

These operators are used to perform mathematical operations.

• Addition (+)

x = 5
y = 3
print(x + y) # Output: 8

• Subtraction (-)

print(x - y) # Output: 2

• Multiplication (*)

print(x * y) # Output: 15

• Division (/)

print(x / y) # Output: 1.6666666666666667

• Floor Division (//)

11
print(x // y) # Output: 1

• Modulus (%)

print(x % y) # Output: 2

• Exponentiation (**)

print(x ** y) # Output: 125

2. Comparison Operators

These operators are used to compare two values and return a Boolean result (True or False).

• Equal to (==)

print(x == y) # Output: False

• Not equal to (!=)

print(x != y) # Output: True

• Greater than (>)

print(x > y) # Output: True

• Less than (<)

print(x < y) # Output: False

• Greater than or equal to (>=)

print(x >= y) # Output: True

• Less than or equal to (<=)

print(x <= y) # Output: False

3. Logical Operators

These operators are used to combine conditional statements.

• AND (and)

print(x > 0 and y > 0) # Output: True

12
• OR (or)

print(x > 0 or y < 0) # Output: True

• NOT (not)

print(not(x > 0)) # Output: False

4. Assignment Operators

These operators are used to assign values to variables.

• Assignment (=)

z = 10

• Add and assign (+=)

z += 5 # z is now 15

• Subtract and assign (-=)

z -= 3 # z is now 12

• Multiply and assign (*=)

z *= 2 # z is now 24

• Divide and assign (/=)

z /= 4 # z is now 6.0

• Floor divide and assign (//=)

z //= 2 # z is now 3.0

• Modulus and assign (%=)

z %= 2 # z is now 1.0

• Exponent and assign (**=)

z **= 3 # z is now 1.0

13
5. Bitwise Operators

These operators are used to perform operations on binary numbers.

• AND (&)

print(5 & 3) # Output: 1 (binary: 101 & 011 = 001)

• OR (|)

print(5 | 3) # Output: 7 (binary: 101 | 011 = 111)

• XOR (^)

print(5 ^ 3) # Output: 6 (binary: 101 ^ 011 = 110)

• NOT (~)

print(~5) # Output: -6 (binary: ~101 = -110)

• Left Shift (<<)

print(5 << 1) # Output: 10 (binary: 101 << 1 = 1010)

• Right Shift (>>)

print(5 >> 1) # Output: 2 (binary: 101 >> 1 = 10)

6. Membership Operators

These operators are used to test if a sequence is present in an object.

• IN (in)

list = [1, 2, 3, 4, 5]
print(3 in list) # Output: True

• NOT IN (not in)

print(6 not in list) # Output: True

7. Identity Operators

These operators are used to compare the memory locations of two objects.

14
• IS (is)

a = [1, 2, 3]
b = a
print(a is b) # Output: True

• IS NOT (is not)

c = [1, 2, 3]
print(a is not c) # Output: True

Understanding and using these operators effectively is crucial for performing various operations
and manipulating data in Python.

Precedence and Associativity:

In Python, operator precedence and associativity determine the order in which operators are
evaluated in expressions.

Precedence

Operator precedence determines which operator is evaluated first in an expression with multiple
operators. Operators with higher precedence are evaluated before operators with lower
precedence.

Here's a list of Python operators, grouped by precedence from highest to lowest:

1. Exponentiation: **
2. Unary plus, unary minus, and bitwise NOT: +, -, ~
3. Multiplication, division, floor division, and modulus: *, /, //, %
4. Addition and subtraction: +, -
5. Bitwise shift operators: <<, >>
6. Bitwise AND: &
7. Bitwise XOR: ^
8. Bitwise OR: |
9. Comparisons, including membership and identity tests: ==, !=, >, <, >=, <=, is, is not, in,
not in
10. Boolean NOT: not
11. Boolean AND: and
12. Boolean OR: or

15
Associativity

Associativity determines the order in which operators of the same precedence are evaluated.
Most operators in Python are left-associative, meaning they are evaluated from left to right. The
exponentiation operator (**) is right-associative, meaning it is evaluated from right to left.

Left-Associative Operators (evaluated from left to right)

• Multiplication, division, floor division, and modulus (*, /, //, %)


• Addition and subtraction (+, -)
• Bitwise shift operators (<<, >>)
• Bitwise AND (&)
• Bitwise XOR (^)
• Bitwise OR (|)
• Comparisons (==, !=, >, <, >=, <=, is, is not, in, not in)
• Boolean AND (and)
• Boolean OR (or)

Right-Associative Operators (evaluated from right to left)

• Exponentiation (**)
• Unary plus, unary minus, and bitwise NOT (+, -, ~)
• Boolean NOT (not)

Examples

Example 1: Operator Precedence

x = 2 + 3 * 4
print(x) # Output: 14

In this example, multiplication (*) has higher precedence than addition (+), so 3 * 4 is evaluated
first, resulting in 12, and then 2 + 12 gives 14.

Example 2: Using Parentheses to Override Precedence

x = (2 + 3) * 4
print(x) # Output: 20

Parentheses have the highest precedence, so 2 + 3 is evaluated first, resulting in 5, and then 5 *
4 gives 20.

16
Example 3: Associativity

x = 2 ** 3 ** 2
print(x) # Output: 512

Exponentiation is right-associative, so 3 ** 2 is evaluated first, resulting in 9, and then 2 ** 9


gives 512.

Example 4: Mixed Associativity

x = 5 - 3 + 2
print(x) # Output: 4

Both subtraction and addition are left-associative and have the same precedence. So, 5 - 3 is
evaluated first, resulting in 2, and then 2 + 2 gives 4.

Understanding operator precedence and associativity is crucial for writing clear and correct
Python code, especially in complex expressions. When in doubt, using parentheses to explicitly
define the evaluation order can help ensure your code behaves as expected.

In Python, data types specify the type of value a variable holds. Python has several built-in data
types that are used to handle different kinds of data. Here's a comprehensive overview of the
most common data types in Python:

Basic Data Types

1. Integer (int):
o Whole numbers, positive or negative, without decimals.
o Example:

python
Copy code
x = 10
y = -5

2. Float (float):
o Numbers, positive or negative, containing one or more decimals.
o Example:

python
Copy code
pi = 3.14
gravity = 9.81

17
3. String (str):
o Sequence of characters enclosed in single, double, or triple quotes.
o Example:

python
Copy code
name = "Alice"
greeting = 'Hello, world!'
paragraph = """This is a paragraph
that spans multiple lines."""

4. Boolean (bool):
o Represents one of two values: True or False.
o Example:

python
Copy code
is_active = True
has_passed = False

Collection Data Types

1. List (list):
o Ordered collection of items which can be of different types. Lists are mutable.
o Example:

python
Copy code
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed_list = [1, "apple", 3.14, True]

2. Tuple (tuple):
o Ordered collection of items which can be of different types. Tuples are immutable.
o Example:

python
Copy code
point = (10, 20)
colors = ("red", "green", "blue")

3. Set (set):
o Unordered collection of unique items.
o Example:

18
python
Copy code
unique_numbers = {1, 2, 3, 4, 5}
letters = {"a", "b", "c"}

4. Dictionary (dict):
o Unordered collection of key-value pairs.
o Example:

person = {"name": "Alice", "age": 30, "city": "New York"}


scores = {"math": 95, "science": 90}

Special Data Types

1. NoneType (None):
o Represents the absence of a value or a null value.
o Example:

x = None

2. Range (range):
o Represents an immutable sequence of numbers, commonly used for looping a specific
number of times in for loops.
o Example:

numbers = range(10) # Creates a range object from 0 to 9

Type Conversion

Python allows you to convert values from one data type to another using type conversion
functions.

1. Integer to String:

x = 10
y = str(x) # y is now "10"

2. String to Integer:

a = "5"
b = int(a) # b is now 5

3. String to Float:

c = "3.14"

19
d = float(c) # d is now 3.14

4. Float to Integer:

e = 7.89
f = int(e) # f is now 7

5. List to Tuple:

list_example = [1, 2, 3]
tuple_example = tuple(list_example) # tuple_example is now (1, 2, 3)

6. Tuple to List:

tuple_example = (1, 2, 3)
list_example = list(tuple_example) # list_example is now [1, 2, 3]

7. List to Set:

list_example = [1, 2, 2, 3]
set_example = set(list_example) # set_example is now {1, 2, 3}

Understanding and effectively using these data types is fundamental to programming in Python.
Each data type has its own properties and is suited for different kinds of tasks.

Indentation: Indentation refers to the spaces or tabs used at the beginning of a line of code to
indicate that it is a part of a block of code. It is a crucial aspect of programming, especially in
languages like Python where indentation is used to define the structure and flow of the program.

Importance of Indentation

1. Readability: Proper indentation makes code easier to read and understand.


2. Structure: In languages like Python, indentation defines blocks of code such as loops,
conditionals, and functions.
3. Debugging: Well-indented code is easier to debug and maintain.

Comments: In Python, comments are used to explain code and make it more readable. They are
ignored by the Python interpreter and do not affect the execution of the program. There are two
main types of comments in Python: single-line comments and multi-line comments.

Single-Line Comments

Single-line comments start with the hash character (#) and extend to the end of the line.

20
This is a single-line comment

print("Hello, World!")

# This comment is at the end of a line of code

Multi-Line Comments

While Python does not have a specific syntax for multi-line comments, you can use multiple
single-line comments or triple-quoted strings (which are generally used for docstrings) to achieve
the same effect.

Multi-Line Comments

While Python does not have a specific syntax for multi-line comments, you can use multiple
single-line comments or triple-quoted strings (which are generally used for docstrings) to achieve
the same effect.

Example using multiple single-line comments:

# This is a multi-line comment

# that spans multiple lines

print("Hello, World!")

Example using triple-quoted strings:

"""

This is a multi-line comment

using triple-quoted strings.

It can span multiple lines.

"""

print("Hello, World!")

Docstrings

21
Docstrings are a special type of comment used to document modules, classes, functions, and
methods. They are written using triple quotes and are the first statement in the object being
documented.

def greet(name):

""" This function greets a person with the given name.

Parameters:.

name (str): The name of the person to greet.

Returns:

None

"""

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

greet("Alice")

READING INPUT

Reading input in Python can be done using the built-in input() function. This function reads a
line from the standard input (usually from the keyboard) and returns it as a string.

Basic Usage

The input() function can be used to prompt the user for input.

Example:
name = input("Enter your name: ")
print(f"Hello, {name}!")

22
23
UNIT-1
Program 01: Write a program to find the largest element among three Numbers
Source Code:
num1 = 10
• num2 = 14
• num3 = 12

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

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

• print("The largest number is", largest)
• Output:
The Largest number is 14
Program 2: Write a Program to display all prime numbers within an interval

Source code:

lower = 900

upper = 1000

print("Prime numbers between", lower, "and", upper, "are:")

for num in range(lower, upper + 1):

# all prime numbers are greater than 1

if num > 1:

for i in range(2, num):

if (num % i) == 0:

24
break

else:

print(num)

Output:

Prime numbers between 900 and 1000 are:

907

911

919

929

937

941

947

953

967

971

977

983

991

997

Program 03

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

Source code:

x=5
y = 10

# To take inputs from the user


#x = input('Enter value of x: ')

25
#y = input('Enter value of y: ')

# create a temporary variable and swap the values


temp = x
x=y
y = temp

print('The value of x after swapping: {}'.format(x))


print('The value of y after swapping: {}'.format(y))

Output:

The value of x after swapping: 10

The value of y after swapping: 5

Program 04

Demonstrate the following Operators in Python with suitable examples. i) Arithmetic


Operators

ii) Relational Operators iii) Assignment Operators

Source code:

i) Arithmetic Operators

a = 21
b = 10
# Addition
print ("a + b : ", a + b)
# Subtraction
print ("a - b : ", a - b)
# Multiplication
print ("a * b : ", a * b)
# Division
print ("a / b : ", a / b)
# Modulus
print ("a % b : ", a % b)
# Exponent
print ("a ** b : ", a ** b)
# Floor Division
print ("a // b : ", a // b)

26
Output

a + b : 31

a - b : 11

a * b : 210

a / b : 2.1

a%b: 1

a ** b : 16679880978201

a // b : 2

Relational Operators:

Source code:

a=4
b=5
# Equal
print ("a == b : ", a == b)
# Not Equal
print ("a != b : ", a != b)
# Greater Than
print ("a > b : ", a > b)
# Less Than
print ("a < b : ", a < b)
# Greater Than or Equal to
print ("a >= b : ", a >= b)
# Less Than or Equal to
print ("a <= b : ", a <= b)
Output:
a == b : False
a != b : True
a > b : False
a < b : True
a >= b : False
a <= b : True

27
iii)Assignment Operators

# Assignment Operator
a = 10
# Addition Assignment
a += 5
print ("a += 5 : ", a)
# Subtraction Assignment
a -= 5
print ("a -= 5 : ", a)
# Multiplication Assignment
a *= 5
print ("a *= 5 : ", a)
# Division Assignment
a /= 5
print ("a /= 5 : ",a)
# Remainder Assignment
a %= 3
print ("a %= 3 : ", a)
# Exponent Assignment
a **= 2
print ("a **= 2 : ", a)
# Floor Division Assignment
a //= 3
print ("a //= 3 : ", a)

Output:

a += 5 : 15
a -= 5 : 10
a *= 5 : 50
a /= 5 : 10.0
a %= 3 : 1.0
a **= 2 : 1.0
a //= 3 : 0.0

Program 5:

Write a program to add and multiply complex numbers


Source Code:

28
print("Addition of two complex numbers : ",(4+3j)+(3-7j))
print("Subtraction of two complex numbers : ",(4+3j)-(3-7j))
print("Multiplication of two complex numbers : ",(4+3j)*(3-7j))
print("Division of two complex numbers : ",(4+3j)/(3-7j))

Output:
Addition of two complex numbers : (7-4j)
Subtraction of two complex numbers : (1+10j)
Multiplication of two complex numbers : (33-19j)
Division of two complex numbers : (-0.15517241379310348+0.6379310344827587j)

Program 06:
Write a program to print multiplication table of a given number.

# Multiplication table (from 1 to 10) in Python

num = 9

# To take input from the user


# num = int(input("Display multiplication table of? "))

# Iterate 10 times from i = 1 to 10


for i in range(1, 11):
print(num, 'x', i, '=', num*i)

Output:
9x1=9
9 x 2 = 18
9 x 3 = 27
9 x 4 = 36
9 x 5 = 45
9 x 6 = 54
9 x 7 = 63
9 x 8 = 72
9 x 9 = 81
9 x 10 = 90

29
UNIT-2
Program no.7
Write a program to define a function with multiple return values.
def name():
return "John","Armin"

# print the tuple with the returned values


print(name())

# get the individual items


name_1, name_2 = name()
print(name_1, name_2)
Output:
('John', 'Armin')
John Armin

Program no. 8:

Write a program to define a function using default arguments

def add_numbers(a, b):

sum = a + b

print('Sum:', sum)

add numbers(2, 3)

Output: Sum: 5

Program 9: Write a program to find the length of the string without using any library
functions.

string = 'Hello'

count = 0

for i in string:

count+=1

print(count)

30
Output:

Program 10:

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

Source code:

string="helllo world python"

substring="python"

print("Does ",substring," exist in ",string,"?")

if substring in string:

print("Yes")

else:

print("False")

Output:

Does python exist in helllo world python ?

Yes

Program 11:

Write a program to perform the given operations on a list:

i.Addition ii. Insertion iii. slicing

def main():

# Create an initial list

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

print("Initial list:", my_list)

# Addition: Append an element to the list

my_list.append(6)

31
print("After addition (append 6):", my_list)

# Insertion: Insert an element at a specific index

my_list.insert(2, 10) # Insert 10 at index 2

print("After insertion (insert 10 at index 2):", my_list)

# Slicing: Get a subset of the list

sliced_list = my_list[1:4] # Slice from index 1 to 3 (4 is exclusive)

print("Sliced list (from index 1 to 3):", sliced_list)

if __name__ == "__main__":

main()

Output:

Initial list: [1, 2, 3, 4, 5]

After addition (append 6): [1, 2, 3, 4, 5, 6]

After insertion (insert 10 at index 2): [1, 2, 10, 3, 4, 5, 6]

Sliced list (from index 1 to 3): [2, 10, 3]

Program no.12

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

def main():

# Example list

my_list = [3, 1, 7, 2, 5]

# 1. len() - Length of the list

print("Length of the list:", len(my_list))

32
# 2. max() - Maximum element in the list

print("Maximum element in the list:", max(my_list))

# 3. min() - Minimum element in the list

print("Minimum element in the list:", min(my_list))

# 4. sum() - Sum of all elements in the list

print("Sum of all elements in the list:", sum(my_list))

# 5. sorted() - Sorted version of the list

sorted_list = sorted(my_list)

print("Sorted list:", sorted_list)

if __name__ == "__main__":

main()

Output:

Length of the list: 5

Maximum element in the list: 7

Minimum element in the list: 1

Sum of all elements in the list: 18

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

33
UNIT-3
Program 13:

Write a program to create tuples (name, age, address, college) for at least two members and
concatenate the tuples and print the concatenated tuples.

def main():

# Creating tuples for two members

member1 = ('Alice', 25, '123 Main St, City A', 'ABC University')

member2 = ('Bob', 22, '456 Elm St, City B', 'XYZ College')

# Concatenating 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 Main St, City A', 'ABC University', 'Bob', 22, '456 Elm St, City B', 'XYZ
College')

Program 14:

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

Source code:

def count_vowels(s):

34
# Define vowels as a set

vowels = {'a', 'e', 'i', 'o', 'u'}

# Use filter to extract vowels and count them

vowel_count = sum(map(s.lower().count, vowels))

return vowel_count

def main():

# Input string

input_string = "Hello, World!"

# Count vowels in the string

num_vowels = count_vowels(input_string)

# Print the result

print("Number of vowels in the string:", num_vowels)

if __name__ == "__main__":

main()

Output:

Number of vowels in the string: 3

Program 15:

Write a program to check if a given key exists in a dictionary or not

Source code:

35
def check_key(dictionary, key):

if key in dictionary:

print(f"Key '{key}' exists in the dictionary.")

else:

print(f"Key '{key}' does not exist in the dictionary.")

# Example usage:

my_dict = {'a': 1, 'b': 2, 'c': 3}

check_key(my_dict, 'b') .

check_key(my_dict, 'd')

Output:

Key 'b' exists in the dictionary.

Key 'd' does not exist in the dictionary..

Program 16:

Write a program to add a new key-value pair to an existing dictionary

# Function to add a new key-value pair to a dictionary

def add_key_value_pair(dictionary, key, value):

dictionary[key] = value

return dictionary

# Example dictionary

my_dict = {

"name": "Alice",

"age": 30,

"city": "New York"

36
# New key-value pair to add

new_key = "occupation"

new_value = "Engineer"

# Add the new key-value pair

updated_dict = add_key_value_pair(my_dict, new_key, new_value)

# Print the updated dictionary

print(updated_dict)

Output: {'name': 'Alice', 'age': 30, 'city': 'New York', 'occupation': 'Engineer'}

Program 17:

Write a program to sum all the items in a given dictionary

# Function to sum all the items in a dictionary

def sum_dictionary_items(dictionary):

return sum(dictionary.values())

# Example dictionary with numeric values

my_dict = {

"item1": 10,

"item2": 20,

"item3": 30,

"item4": 40

# Calculate the sum of all items

37
total_sum = sum_dictionary_items(my_dict)

# Print the sum

print(f"The sum of all items in the dictionary is: {total_sum}")

Output:

The sum of all items in the dictionary is: 100

38
UNIT-4
Program 18:

Write a program to sort words in a file and put them in another file. The output files
should have only lower-case words, so any upper-case words from source must be lowered.

def sort_words_in_file(source_file, destination_file):

try:

# Open the source file and read its content

with open(source_file, 'r') as src:

text = src.read()

# Split the text into words, convert to lowercase, and sort

words = text.split()

lower_words = [word.lower() for word in words]

sorted_words = sorted(lower_words)

# Write sorted words to the destination file

with open(destination_file, 'w') as dest:

for word in sorted_words:

dest.write(word + '\n')

print(f"Words sorted and written to '{destination_file}' successfully.")

except FileNotFoundError:

print(f"Error: The file '{source_file}' does not exist.")

except Exception as e:

print(f"An error occurred: {e}")

39
# Example usage

source_file = 'input.txt'

destination_file = 'output.txt'

sort_words_in_file(source_file, destination_file)

Output

apple

apple

banana

banana

grape

mango

orange

Program 19:

Python program to print each line of a file in reverse order.

def print_lines_in_reverse(filename):

try:

with open(filename, 'r') as file:

for line in file:

# Strip newline and reverse the line content

reversed_line = line.rstrip('\n')[::-1]

print(reversed_line)

except FileNotFoundError:

print(f"Error: File '{filename}' not found.")

40
except Exception as e:

print(f"An error occurred: {e}")

# Example usage

filename = 'input.txt'

print_lines_in_reverse(filename)

Output

Hello World

Python Programming

File Handling

dlroW olleH

gnimmargorP nohtyP

gnildnaH eliF

Program 20:

Python program to compute the number of characters, words and lines in a file.

def count_file_stats(filename):

try:

with open(filename, 'r') as file:

lines = file.readlines()

num_lines = len(lines)

num_words = 0

num_chars = 0

41
for line in lines:

num_chars += len(line)

num_words += len(line.split())

print(f"Lines : {num_lines}")

print(f"Words : {num_words}")

print(f"Characters : {num_chars}")

except FileNotFoundError:

print(f"Error: File '{filename}' not found.")

except Exception as e:

print(f"An error occurred: {e}")

# Example usage

filename = 'input.txt'

count_file_stats(filename)

Output

Python is fun.

We are learning file handling.

Lines :2

Words :8

Characters : 52

Program 21:

42
Write a program to create, display, append, insert and reverse the order of the items in the
array.

from array import array

# 1. Create an array of integers

arr = array('i', [10, 20, 30, 40, 50])

# Display the array

print("Original Array:")

print(arr.tolist())

# 2. Append an element to the array

arr.append(60)

print("\nAfter appending 60:")

print(arr.tolist())

# 3. Insert an element at a specific position

arr.insert(2, 25) # Insert 25 at index 2

print("\nAfter inserting 25 at index 2:")

print(arr.tolist())

# 4. Reverse the array

arr.reverse()

print("\nAfter reversing the array:")

print(arr.tolist())

43
Output

Original Array:

[10, 20, 30, 40, 50]

After appending 60:

[10, 20, 30, 40, 50, 60]

After inserting 25 at index 2:

[10, 20, 25, 30, 40, 50, 60]

After reversing the array:

[60, 50, 40, 30, 25, 20, 10]

Program 22:

Write a program to add, transpose and multiply two matrices.

# Define two matrices

A=[

[1, 2, 3],

[4, 5, 6]

B=[

[7, 8, 9],

[10, 11, 12]

44
# Function to add two matrices

def add_matrices(X, Y):

result = []

for i in range(len(X)):

row = []

for j in range(len(X[0])):

row.append(X[i][j] + Y[i][j])

result.append(row)

return result

# Function to transpose a matrix

def transpose_matrix(M):

rows = len(M)

cols = len(M[0])

return [[M[j][i] for j in range(rows)] for i in range(cols)]

# Function to multiply two matrices

def multiply_matrices(X, Y):

result = []

for i in range(len(X)):

row = []

for j in range(len(Y[0])):

val = 0

for k in range(len(Y)):

val += X[i][k] * Y[k][j]

45
row.append(val)

result.append(row)

return result

# Transpose matrices

transpose_A = transpose_matrix(A)

transpose_B = transpose_matrix(B)

# Multiply A and transpose_B (dimensions compatible)

# A: 2x3, transpose_B: 3x2 => result: 2x2

product = multiply_matrices(A, transpose_B)

# Display results

print("Matrix A:")

for row in A:

print(row)

print("\nMatrix B:")

for row in B:

print(row)

print("\nA + B:")

for row in add_matrices(A, B):

print(row)

46
print("\nTranspose of A:")

for row in transpose_A:

print(row)

print("\nTranspose of B:")

for row in transpose_B:

print(row)

print("\nA * Transpose(B):")

for row in product:

print(row)

Output

Matrix A:

[1, 2, 3]

[4, 5, 6]

Matrix B:

[7, 8, 9]

[10, 11, 12]

A + B:

[8, 10, 12]

[14, 16, 18]

47
Transpose of A:

[1, 4]

[2, 5]

[3, 6]

Transpose of B:

[7, 10]

[8, 11]

[9, 12]

A * Transpose(B):

[50, 68]

[122, 167]

Program 23:

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.

import math

# Base class

class Shape:

def area(self):

return 0

def perimeter(self):

return 0

48
# Subclass for Circle

class Circle(Shape):

def __init__(self, radius):

self.radius = radius

def area(self):

return math.pi * self.radius ** 2

def perimeter(self):

return 2 * math.pi * self.radius

# Subclass for Square

class Square(Shape):

def __init__(self, side):

self.side = side

def area(self):

return self.side ** 2

def perimeter(self):

return 4 * self.side

# Subclass for Triangle (Assuming a simple triangle with three sides given)

class Triangle(Shape):

49
def __init__(self, a, b, c): # a, b, c are sides of the triangle

self.a = a

self.b = b

self.c = c

def perimeter(self):

return self.a + self.b + self.c

def area(self):

# Heron's formula

s = self.perimeter() / 2

return math.sqrt(s * (s - self.a) * (s - self.b) * (s - self.c))

# Example usage

circle = Circle(5)

square = Square(4)

triangle = Triangle(3, 4, 5)

print("Circle:")

print("Area:", round(circle.area(), 2))

print("Perimeter:", round(circle.perimeter(), 2))

print("\nSquare:")

print("Area:", square.area())

print("Perimeter:", square.perimeter())

50
print("\nTriangle:")

print("Area:", round(triangle.area(), 2))

print("Perimeter:", triangle.perimeter())

Output

Circle:

Area: 78.54

Perimeter: 31.42

Square:

Area: 16

Perimeter: 16

Triangle:

Area: 6.0

Perimeter: 12

51
UNIT-5
Program 24:

Python program to check whether a JSON string contains complex object or not.

import json

def contains_complex_object(json_str):

try:

data = json.loads(json_str)

def is_complex(obj):

if isinstance(obj, (dict, list)):

return True

elif isinstance(obj, (str, int, float, bool)) or obj is None:

return False

return False

# Recursive check for nested structures

def check_recursive(obj):

if is_complex(obj):

if isinstance(obj, dict):

for value in obj.values():

if check_recursive(value):

return True

elif isinstance(obj, list):

for item in obj:

52
if check_recursive(item):

return True

return True

return False

return check_recursive(data)

except json.JSONDecodeError:

print("Invalid JSON string.")

return False

# Test Examples

json_simple = '"hello"' # string only

json_array = '[1, 2, 3]' # list of numbers

json_complex = '{"name": "Alice", "address": {"city": "NY", "zip": 12345}}'

json_flat_object = '{"name": "Bob", "age": 30}'

print("Example 1 (Simple String):", contains_complex_object(json_simple)) # False

print("Example 2 (List):", contains_complex_object(json_array)) # True

print("Example 3 (Nested Dict):", contains_complex_object(json_complex)) # True

print("Example 4 (Flat Dict):", contains_complex_object(json_flat_object)) # True

Output

Example 1 (Simple String): False

Example 2 (List): True

53
Example 3 (Nested Dict): True

Example 4 (Flat Dict): True

Program 25:

Python Program to demonstrate NumPy arrays creation using array () function.

import numpy as np

# 1. Create a 1D array

arr1 = np.array([1, 2, 3, 4, 5])

print("1D Array:")

print(arr1)

# 2. Create a 2D array (matrix)

arr2 = np.array([[1, 2, 3], [4, 5, 6]])

print("\n2D Array:")

print(arr2)

# 3. Create a 3D array

arr3 = np.array([

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

[[5, 6], [7, 8]]

])

print("\n3D Array:")

print(arr3)

54
# 4. Array with specified data type

arr4 = np.array([1.5, 2.5, 3.5], dtype=int)

print("\nArray with specified data type (int):")

print(arr4)

Output

1D Array:

[1 2 3 4 5]

2D Array:

[[1 2 3]

[4 5 6]]

3D Array:

[[[1 2]

[3 4]]

[[5 6]

[7 8]]]

Array with specified data type (int):

[1 2 3]

Program 26:

Python program to demonstrate use of ndim, shape, size, dtype.

import numpy as np

55
# Create a 2D array (matrix)

arr = np.array([[1, 2, 3], [4, 5, 6]])

# Demonstrate the use of ndim, shape, size, dtype

print("Array:")

print(arr)

# 1. ndim - Number of dimensions

print("\nNumber of dimensions (ndim):", arr.ndim)

# 2. shape - Dimensions of the array

print("Shape of the array:", arr.shape)

# 3. size - Total number of elements in the array

print("Total number of elements (size):", arr.size)

# 4. dtype - Data type of the elements in the array

print("Data type of elements (dtype):", arr.dtype)

Output

Array:

[[1 2 3]

[4 5 6]]

56
Number of dimensions (ndim): 2

Shape of the array: (2, 3)

Total number of elements (size): 6

Data type of elements (dtype): int64

Program 27:

Python program to demonstrate basic slicing, integer and Boolean indexing.

import numpy as np

# Create a 2D array (matrix)

arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])

# Basic slicing (extract a sub-array)

print("Original Array:")

print(arr)

# 1. Basic Slicing - Extract a sub-array from rows 0 and 1, columns 1 to 3

sliced_arr = arr[0:2, 1:4]

print("\nBasic Slicing - rows 0-1, columns 1-3:")

print(sliced_arr)

# 2. Integer Indexing - Accessing specific elements using an index array

int_indexed_arr = arr[[0, 1], [2, 3]] # elements at (0,2) and (1,3)

print("\nInteger Indexing - elements at (0,2) and (1,3):")

print(int_indexed_arr)

57
# 3. Boolean Indexing - Extract elements greater than 5

bool_mask = arr > 5

bool_indexed_arr = arr[bool_mask]

print("\nBoolean Indexing - elements greater than 5:")

print(bool_indexed_arr)

Output

Original Array:

[[ 1 2 3 4]

[ 5 6 7 8]

[ 9 10 11 12]]

Basic Slicing - rows 0-1, columns 1-3:

[[2 3 4]

[6 7 8]]

Integer Indexing - elements at (0,2) and (1,3):

[3 8]

Boolean Indexing - elements greater than 5:

[ 6 7 8 9 10 11 12]

Program 28:

Python program to find min, max, sum, cumulative sum of array

import numpy as np

# Create a NumPy array

58
arr = np.array([1, 2, 3, 4, 5, 6])

# Find the minimum value in the array

min_val = np.min(arr)

# Find the maximum value in the array

max_val = np.max(arr)

# Find the sum of the array

sum_val = np.sum(arr)

# Find the cumulative sum of the array

cumulative_sum = np.cumsum(arr)

# Display the results

print("Array:", arr)

print("Minimum value:", min_val)

print("Maximum value:", max_val)

print("Sum of array:", sum_val)

print("Cumulative sum of array:", cumulative_sum)

Output

Array: [1 2 3 4 5 6]

Minimum value: 1

Maximum value: 6

59
Sum of array: 21

Cumulative sum of array: [ 1 3 6 10 15 21]

Program 29:

Create a dictionary with at least five keys and each key represent value as a list where this
list contains at least ten values and convert this dictionary as a pandas data frame and
explore the data through the data frame as follows:

a) Apply head () function to the pandas data frame

b) Perform various data selection operations on Data Frame

import pandas as pd

# Creating a dictionary with keys and values as lists

data = {

'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva', 'Frank', 'Grace', 'Hannah', 'Isaac', 'Jack'],

'Age': [23, 34, 45, 23, 22, 34, 25, 28, 29, 30],

'City': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix', 'San Antonio', 'San Diego',
'Dallas', 'Austin', 'Jacksonville'],

'Salary': [50000, 60000, 70000, 80000, 90000, 100000, 110000, 120000, 130000, 140000],

'Department': ['HR', 'IT', 'Sales', 'Marketing', 'Finance', 'IT', 'HR', 'Sales', 'Marketing', 'Finance']

# Convert dictionary to Pandas DataFrame

df = pd.DataFrame(data)

# a) Apply head() function to show first 5 rows

print("First 5 rows of the DataFrame:")

print(df.head())

60
# b) Data selection operations

# Select a single column (e.g., 'Name')

print("\n'Name' column:")

print(df['Name'])

# Select multiple columns (e.g., 'Name' and 'Age')

print("\n'Name' and 'Age' columns:")

print(df[['Name', 'Age']])

# Select a single row by index (e.g., row with index 2)

print("\nRow with index 2:")

print(df.iloc[2])

# Select a specific value (e.g., value in the 'City' column for row with index 5)

print("\nCity of the person at index 5:")

print(df.at[5, 'City'])

# Filter the data (e.g., select rows where 'Age' is greater than 30)

print("\nPeople with Age greater than 30:")

print(df[df['Age'] > 30])

# Select a specific row and column using .loc (e.g., Age of person named 'Alice')

print("\nAge of Alice:")

61
print(df.loc[df['Name'] == 'Alice', 'Age'])

Output

First 5 rows of the DataFrame:

Name Age City Salary Department

0 Alice 23 New York 50000 HR

1 Bob 34 Los Angeles 60000 IT

2 Charlie 45 Chicago 70000 Sales

3 David 23 Houston 80000 Marketing

4 Eva 22 Phoenix 90000 Finance

'Name' column:

0 Alice

1 Bob

2 Charlie

3 David

4 Eva

5 Frank

6 Grace

7 Hannah

8 Isaac

9 Jack

Name: Name, dtype: object

'Name' and 'Age' columns:

Name Age

62
0 Alice 23

1 Bob 34

2 Charlie 45

3 David 23

4 Eva 22

5 Frank 34

6 Grace 25

7 Hannah 28

8 Isaac 29

9 Jack 30

Row with index 2:

Name Charlie

Age 45

City Chicago

Salary 70000

Department Sales

Name: 2, dtype: object

City of the person at index 5:

San Antonio

People with Age greater than 30:

Name Age City Salary Department

1 Bob 34 Los Angeles 60000 IT

63
2 Charlie 45 Chicago 70000 Sales

3 David 23 Houston 80000 Marketing

5 Frank 34 San Antonio 100000 IT

6 Grace 25 San Diego 110000 HR

7 Hannah 28 Dallas 120000 Sales

8 Isaac 29 Austin 130000 Marketing

9 Jack 30 Jacksonville 140000 Finance

Age of Alice:

0 23

Name: Age, dtype: int64

Program 30:

Select any two columns from the above data frame, and observe the change in one attribute
with respect to other attribute with scatter and plot operations in matplotlib

import pandas as pd

import matplotlib.pyplot as plt

# Creating a dictionary with keys and values as lists

data = {

'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva', 'Frank', 'Grace', 'Hannah', 'Isaac', 'Jack'],

'Age': [23, 34, 45, 23, 22, 34, 25, 28, 29, 30],

'City': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix', 'San Antonio', 'San Diego',
'Dallas', 'Austin', 'Jacksonville'],

'Salary': [50000, 60000, 70000, 80000, 90000, 100000, 110000, 120000, 130000, 140000],

'Department': ['HR', 'IT', 'Sales', 'Marketing', 'Finance', 'IT', 'HR', 'Sales', 'Marketing', 'Finance']

64
# Convert dictionary to Pandas DataFrame

df = pd.DataFrame(data)

# Select 'Age' and 'Salary' columns

age = df['Age']

salary = df['Salary']

# Scatter plot to observe the relationship between 'Age' and 'Salary'

plt.figure(figsize=(10, 5))

# Scatter plot

plt.subplot(1, 2, 1) # 1 row, 2 columns, plot 1

plt.scatter(age, salary, color='blue', label='Age vs Salary')

plt.title('Scatter Plot: Age vs Salary')

plt.xlabel('Age')

plt.ylabel('Salary')

plt.grid(True)

# Line plot (connecting points with a line)

plt.subplot(1, 2, 2) # 1 row, 2 columns, plot 2

plt.plot(age, salary, marker='o', color='red', label='Age vs Salary')

plt.title('Line Plot: Age vs Salary')

plt.xlabel('Age')

plt.ylabel('Salary')

65
plt.grid(True)

# Show both plots

plt.tight_layout()

plt.show()

66

You might also like