[Go to site: main page, start]

0% found this document useful (0 votes)
14 views28 pages

Python Programming Lab Manual

The Python Programming Lab Manual outlines the curriculum for learning Python, covering topics such as its history, installation of Anaconda and Jupyter Notebook, control flow statements, functions, data structures (lists, dictionaries, tuples, sets), file handling, and object-oriented programming. It includes sample experiments for practical application of concepts, as well as an introduction to data science and relevant libraries like NumPy and pandas. The manual serves as a comprehensive guide for students in the Computer Science and Engineering department at B V C College of Engineering.
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)
14 views28 pages

Python Programming Lab Manual

The Python Programming Lab Manual outlines the curriculum for learning Python, covering topics such as its history, installation of Anaconda and Jupyter Notebook, control flow statements, functions, data structures (lists, dictionaries, tuples, sets), file handling, and object-oriented programming. It includes sample experiments for practical application of concepts, as well as an introduction to data science and relevant libraries like NumPy and pandas. The manual serves as a comprehensive guide for students in the Computer Science and Engineering department at B V C College of Engineering.
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

B V C COLLEGE OF ENGINEERING

(An Autonomous Institution)


PALACHARLA, 533102
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING LAB MANUAL

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.
a) arithmetic operators
b) relational operators
c) assignment operators
d) logical operators
e) bit wise operators
f) ternary operator
g) membership operators
h) 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:

Prepared By: Mr. N N V Ramana, Asst Professor, Dept. of MCA


B V C COLLEGE OF ENGINEERING
(An Autonomous Institution)
PALACHARLA, 533102
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING LAB MANUAL

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:
a) Addition
b) insertion
c) slicing
6. Write a program to perform any 5 built-in-functions taken by any list.

UNIT-III: Dictionaries: Creating a dictionary, accessing and modifying a 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) for at least 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 control flow 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.

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.

Prepared By: Mr. N N V Ramana, Asst Professor, Dept. of MCA


B V C COLLEGE OF ENGINEERING
(An Autonomous Institution)
PALACHARLA, 533102
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING LAB MANUAL

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.

UNIT-V: introduction to data science: functional programming, json and xml in python,
numpy with python, pandas.

Sample experiments:

1. Python program to check whether a json string contains complex object or not.
2. Python program to demonstrate numpy arrays creation using array () function.
3. Python program to demonstrate use of ndim, shape, size, dtype.
4. Python program to demonstrate basic slicing, integer and boolean indexing.
5. Python program to find min, max, sum, cumulative sum of array
6. 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
7. 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 TextBooks

1. Gowrishankar s, veena a., introduction to python programming, crc Press.


2. Python programming, s sridhar, j indumathi, v m hariharan, 2ndedition, pearson, 2024
3. Introduction to programming using python, y. Daniel liang, pearson.

Online learning resources/virtual labs:

1. Https:/ /[Link]/learn/python-for-applied-data-science-ai
2. Https:/ /[Link]/learn/python?specialization=python#syllabus
3. Https://[Link]/user/authentication/login

Note: case studies are being implemented for students in each laboratory

Prepared By: Mr. N N V Ramana, Asst Professor, Dept. of MCA


B V C COLLEGE OF ENGINEERING
(An Autonomous Institution)
PALACHARLA, 533102
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING LAB MANUAL

UNIT-I

UNIT-I: INTRODUCTION TO PYTHON PROGRAMMING

1. History of Python Programming Language

Python was developed by Guido van Rossum in the late 1980s and released in 1991. The
language was designed to emphasize code readability and simplicity, making it accessible to
beginners and powerful enough for experts. It is named after the British comedy group Monty
Python, reflecting its creator’s sense of humor. Python supports multiple programming
paradigms including procedural, object-oriented, and functional programming, making it very
versatile. Over time, Python evolved with major versions Python 2 and Python 3, where
Python 3 is the current and actively maintained version. Its large standard library and active
open-source community have contributed to its adoption in many fields like web
development, scientific computing, and AI. Python’s easy syntax helps beginners quickly
grasp programming concepts, while its powerful features serve professionals for large-scale
projects.

2. Thrust Areas of Python

Python is widely adopted in several key areas that drive its popularity. In web development,
frameworks like Django and Flask enable rapid prototyping and production-ready
applications. In data science and analytics, libraries like NumPy, pandas, and matplotlib
provide tools for data manipulation and visualization. Machine learning and AI leverage
libraries such as TensorFlow and scikit-learn to build predictive models. Python is used in
automation and scripting to automate repetitive tasks, saving time and reducing errors.
Scientific computing benefits from Python’s powerful mathematical libraries and integration
with other scientific tools. Additionally, Python’s presence in game development through
Pygame and Internet of Things (IoT) projects highlights its flexibility. Its ability to interface
with other languages and tools makes it a one-stop language for many domains.

3. Installing Anaconda Python Distribution

Anaconda is a popular distribution of Python that bundles Python with many scientific
libraries and tools for data science and machine learning. It simplifies environment
management and package installation through the Conda package manager. Anaconda
supports cross-platform installation on Windows, macOS, and Linux. It includes Jupyter
Notebook, Spyder IDE, and other utilities for interactive computing. Users typically
download the installer from the official website, run it, and get a ready-to-use Python
environment. Managing packages with Conda helps avoid compatibility problems often faced
with manual installations. Anaconda is widely recommended for beginners and professionals
who want a hassle-free setup, especially for data-related projects.

4. Installing and Using Jupyter Notebook

Prepared By: Mr. N N V Ramana, Asst Professor, Dept. of MCA


B V C COLLEGE OF ENGINEERING
(An Autonomous Institution)
PALACHARLA, 533102
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING LAB MANUAL

Jupyter Notebook is an interactive environment for running and sharing live Python code,
text, and visualizations. It is especially popular in data science for exploratory analysis and
reporting. Jupyter allows code execution in cells, which can be run independently in any
order, making debugging and iterative development easier. It supports markdown cells for
formatted text, equations, and images, which help create rich documents. You can install it
using Anaconda or via pip, and launch it from the command line. Notebooks are saved as
.ipynb files, which can be shared or converted to other formats like HTML or PDF. It
integrates well with libraries such as matplotlib and seaborn for inline plots.

5. Parts of Python Programming Language

This is a core foundational topic. Python programs are constructed using identifiers, which
name variables, functions, and classes, following rules like starting with a letter or underscore
and no reserved keywords. Keywords are special reserved words (like if, for, def) that form
the syntax and structure of programs. Statements are executable instructions such as
assignments, loops, and function calls, while expressions combine values and operators to
compute results. Variables store data and can be dynamically typed, meaning the data type
can change. Python has several types of operators including arithmetic, relational, logical,
and bitwise, with defined precedence (which operators evaluate first) and associativity (how
operators of the same precedence group). Python’s strict indentation replaces braces to
define blocks of code, making formatting essential. Comments starting with # help annotate
code but are ignored during execution.

6. Data Types in Python

Understanding Python’s data types is essential as they govern how data is stored and
manipulated. Python supports several built-in types:

 Numeric types include int (integers), float (decimal numbers), and complex (numbers
with real and imaginary parts).
 str is used for textual data and supports operations like concatenation and slicing.
 bool represents Boolean logic values True or False.
 Compound data types include lists (ordered, mutable collections), tuples (ordered,
immutable collections), sets (unordered collections of unique items), and dictionaries
(key-value pairs).
Python is dynamically typed, so variables do not need explicit type declarations. The
type() function lets you check the data type, and type conversion functions (int(), str(),
etc.) allow explicit conversions. Python’s strong typing ensures operations between
incompatible types raise errors, preventing silent bugs.

7. Indentation and Comments

Python’s syntax relies heavily on indentation to define blocks of code instead of using curly
braces or keywords. Proper indentation is mandatory; inconsistent indentation causes syntax

Prepared By: Mr. N N V Ramana, Asst Professor, Dept. of MCA


B V C COLLEGE OF ENGINEERING
(An Autonomous Institution)
PALACHARLA, 533102
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING LAB MANUAL

errors. Each block of code following constructs like if, for, while, or function definitions must
be indented consistently, typically by 4 spaces. This feature improves code readability and
reduces clutter. Python supports two types of comments: single-line comments start with #
and extend to the end of the line; multi-line comments can be created using triple quotes (''' or
"""). Comments are essential for documenting code logic and making it understandable to
others or your future self.

8. Reading Input and Printing Output

User input is read using the built-in input() function, which always returns data as a string. To
process numeric input, conversion functions like int() or float() are used. The print() function
outputs data to the console and can print multiple values separated by commas or formatted
strings using f-strings or .format(). Both functions are essential for interactive programs.

9. Type Conversion, the type() Function, and is Operator

Type conversion functions (int(), float(), str()) convert values explicitly from one data type to
another. The type() function returns the type of an object, useful for debugging or conditional
logic. The is operator checks identity (whether two references point to the same object in
memory), which is different from equality (==) that checks if values are equivalent.

10. Dynamic and Strongly Typed Language

Python is dynamically typed, meaning variable types are determined at runtime, not in
advance. This allows for flexible and rapid development but requires care to avoid type
errors. Python is also strongly typed, which means it enforces type compatibility and does
not perform implicit type coercion (unlike some other languages). For example, you cannot
add a string and an integer directly without explicit conversion.

SAMPLE EXPERIMENTS:

1. Find the largest element among three numbers

a = 10
b = 25
c = 15

if a >= b and a >= c:


largest = a
elif b >= a and b >= c:
largest = b
else:

Prepared By: Mr. N N V Ramana, Asst Professor, Dept. of MCA


B V C COLLEGE OF ENGINEERING
(An Autonomous Institution)
PALACHARLA, 533102
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING LAB MANUAL

largest = c

print("The largest number is:", largest)

Output:

The largest number is: 25

2. Display all prime numbers within an interval

start = 10
end = 30

for num in range(start, end + 1):


if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num, end=" ")

Output:

11 13 17 19 23 29

3. Swap two numbers without using a temporary variable

x=5
y = 10

x=x+y
y=x-y
x=x-y

print("After swapping:")
print("x =", x)
print("y =", y)

Output:

After swapping:
x = 10

Prepared By: Mr. N N V Ramana, Asst Professor, Dept. of MCA


B V C COLLEGE OF ENGINEERING
(An Autonomous Institution)
PALACHARLA, 533102
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING LAB MANUAL

y=5

4. Demonstrate operators with examples

a) Arithmetic Operators

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

b) Relational Operators

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


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

c) Assignment Operators

a=5
a += 3
print("a after += 3:", a)
a *= 2
print("a after *= 2:", a)

d) Logical Operators

x = True
y = False
print("x and y:", x and y)
print("x or y:", x or y)
print("not x:", not x)

e) Bitwise Operators

a = 4 # 0100
b = 5 # 0101
print("a & b:", a & b)

Prepared By: Mr. N N V Ramana, Asst Professor, Dept. of MCA


B V C COLLEGE OF ENGINEERING
(An Autonomous Institution)
PALACHARLA, 533102
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING LAB MANUAL

print("a | b:", a | b)
print("a ^ b:", a ^ b)
print("~a:", ~a)
print("a << 1:", a << 1)
print("a >> 1:", a >> 1)

f) Ternary Operator

a = 10
b = 20
max_val = a if a > b else b
print("Maximum is:", max_val)

g) Membership Operators

lst = [1, 2, 3, 4]
print("2 in list:", 2 in lst)
print("5 not in list:", 5 not in lst)

h) Identity Operators

x=5
y=5
z = [1, 2]
w = [1, 2]
print("x is y:", x is y)
print("z is w:", z is w)

5. Add and Multiply Complex Numbers

a = 2 + 3j
b = 1 + 4j

add_result = a + b
mul_result = a * b

print("Addition:", add_result)
print("Multiplication:", mul_result)

Output:

Addition: (3+7j)
Multiplication: (-10+11j)

Prepared By: Mr. N N V Ramana, Asst Professor, Dept. of MCA


B V C COLLEGE OF ENGINEERING
(An Autonomous Institution)
PALACHARLA, 533102
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING LAB MANUAL

6. Print multiplication table of a given number

num = 7

for i in range(1, 11):


print(num, "x", i, "=", num * i)

Output:

7x1=7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

UNIT-II

UNIT-II: FUNCTIONS, STRINGS & LISTS

1. Functions

Functions are reusable blocks of code that perform specific tasks and can accept parameters.
Python has many built-in functions (len(), print(), etc.) and supports custom function
definitions using the def keyword. Functions can return values using the return statement, or
be void (no return). Understanding scope is vital: variables defined inside a function are
local, while those outside are global. Python supports default parameters to provide default
values if arguments are omitted, keyword arguments to call functions with named
parameters, and special parameters like *args for arbitrary positional arguments and
**kwargs for arbitrary keyword arguments. Python also allows command line arguments
accessible via [Link][]. Mastering functions improves modularity and readability.

2. Strings

Strings in Python are sequences of characters enclosed in single, double, or triple quotes.
They support indexing and slicing to access substrings. Basic operations include

Prepared By: Mr. N N V Ramana, Asst Professor, Dept. of MCA


B V C COLLEGE OF ENGINEERING
(An Autonomous Institution)
PALACHARLA, 533102
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING LAB MANUAL

concatenation (+), repetition (*), and membership checks (in). Python strings are immutable,
meaning they cannot be changed after creation. There are many built-in string methods such
as .lower(), .upper(), .find(), .replace(), .split(), and .join(). Formatting strings can be done
with f-strings (f"Hello {name}"), .format(), or older % formatting. Efficient string handling is
crucial for many applications like data parsing and user interfaces.

3. Lists

Lists are mutable ordered collections that can hold items of different types. Lists support
indexing and slicing to access and modify elements. Common operations include adding
elements (append(), insert()), removing elements (pop(), remove()), sorting, reversing, and
concatenation. Built-in functions such as len(), min(), and max() operate on lists. Lists can be
nested and used to represent complex data structures. The del statement can delete elements
or entire lists. Lists are widely used for data storage and manipulation due to their flexibility.

SAMPLE EXPERIMENTS:

1. Program to define a function with multiple return values

def calculate(a, b):


sum_val = a + b
diff = a - b
product = a * b
return sum_val, diff, product

x, y, z = calculate(10, 5)
print("Sum:", x)
print("Difference:", y)
print("Product:", z)

Output:

Sum: 15
Difference: 5
Product: 50

2. Program to define a function using default arguments

def greet(name="SAI"):
print("Hello,", name)

greet("YASH")
greet()

Prepared By: Mr. N N V Ramana, Asst Professor, Dept. of MCA


B V C COLLEGE OF ENGINEERING
(An Autonomous Institution)
PALACHARLA, 533102
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING LAB MANUAL

Output:

Hello, SAI
Hello, YASH

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

string = "Hello World"


count = 0

for char in string:


count += 1

print("Length of the string is:", count)

Output:

Length of the string is: 11

4. Program to check if the substring is present in a given string or not

string = "Python programming is fun"


substring = "programming"

found = False

for i in range(len(string) - len(substring) + 1):


if string[i:i+len(substring)] == substring:
found = True
break

if found:
print("Substring is present.")
else:
print("Substring is not present.")

Output:

Substring is present.

5. Program to perform list operations

Prepared By: Mr. N N V Ramana, Asst Professor, Dept. of MCA


B V C COLLEGE OF ENGINEERING
(An Autonomous Institution)
PALACHARLA, 533102
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING LAB MANUAL

lst = [10, 20, 30]

# a) Addition (concatenation)
lst = lst + [40, 50]
print("After addition:", lst)

# b) Insertion
[Link](2, 25)
print("After insertion at index 2:", lst)

# c) Slicing
print("Slicing [1:4]:", lst[1:4])

Output:

After addition: [10, 20, 30, 40, 50]


After insertion at index 2: [10, 20, 25, 30, 40, 50]
Slicing [1:4]: [20, 25, 30]

6. Program to perform 5 built-in list functions

numbers = [5, 3, 8, 6, 1]

print("Original list:", numbers)

# 1. append()
[Link](9)
print("After append(9):", numbers)

# 2. sort()
[Link]()
print("After sort():", numbers)

# 3. reverse()
[Link]()
print("After reverse():", numbers)

# 4. pop()
removed = [Link]()
print("After pop():", numbers, "Removed:", removed)

# 5. index()
idx = [Link](5)

Prepared By: Mr. N N V Ramana, Asst Professor, Dept. of MCA


B V C COLLEGE OF ENGINEERING
(An Autonomous Institution)
PALACHARLA, 533102
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING LAB MANUAL

print("Index of 5:", idx)

Output:

Original list: [5, 3, 8, 6, 1]


After append(9): [5, 3, 8, 6, 1, 9]
After sort(): [1, 3, 5, 6, 8, 9]
After reverse(): [9, 8, 6, 5, 3, 1]
After pop(): [9, 8, 6, 5, 3] Removed: 1
Index of 5: 3

UNIT-III

UNIT-III: DICTIONARIES, TUPLES, SETS

1. Dictionaries: Creating, Accessing, Modifying, Built-in Functions, Methods, Del


Statement

Dictionaries in Python are unordered collections of key-value pairs. They provide a fast way
to retrieve values when you know the key. Keys must be immutable types (strings, numbers,
tuples), while values can be any type. You create dictionaries using curly braces {} with key:
value pairs, or the dict() constructor. Accessing values uses keys (dict[key]), and values can
be modified by assigning new values to existing keys. Common dictionary methods include
.keys() (returns all keys), .values() (returns all values), .items() (returns key-value pairs as
tuples), .get() (returns value with a default if key not found), .pop() (removes and returns a
key’s value), and .update() (merges another dictionary). The del statement removes specific
keys or the whole dictionary. Dictionaries are powerful for data structures such as JSON
objects, frequency counting, and mappings.

2. Tuples: Creating, Basic Operations, tuple() Function, Indexing and Slicing, Built-in
Functions, Relation with Lists and Dictionaries, zip() Function

Tuples are immutable ordered collections defined with parentheses () or the tuple()
function. Unlike lists, tuples cannot be changed once created, which makes them useful for
fixed data and keys in dictionaries. Tuples support indexing and slicing just like lists. Built-in
functions like len(), max(), min(), and count() work on tuples. Tuples can be converted to
lists and vice versa for flexibility. The zip() function is a useful tool that combines elements
from multiple iterables (like lists or tuples) into tuples, enabling parallel iteration and data
pairing. Tuples are often used for returning multiple values from functions and representing
records.

Prepared By: Mr. N N V Ramana, Asst Professor, Dept. of MCA


B V C COLLEGE OF ENGINEERING
(An Autonomous Institution)
PALACHARLA, 533102
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING LAB MANUAL

3. Sets and frozenset: Creating Sets, Set Methods

Sets are unordered collections of unique elements created using curly braces {} or the set()
function. Sets are mutable, meaning you can add or remove elements. Common set methods
include .add(), .remove(), .discard(), .union(), .intersection(), .difference(), and
.symmetric_difference(). Sets are great for membership testing, eliminating duplicates, and
mathematical operations on data. frozenset is an immutable variant of set, which means once
created, its elements cannot be changed. frozenset can be used as keys in dictionaries or
elements of other sets. Understanding sets is important for efficient data handling and
algorithm design.

SAMPLE EXPERIMENTS:

1. Create tuples and concatenate them

member1 = ("sai", 21, "123 Street, City", "ABC College")


member2 = ("yash", 22, "456 Avenue, Town", "XYZ University")

combined = member1 + member2


print("Concatenated tuple:", combined)

Output:

Concatenated tuple: ('sai', 21, '123 Street, City', 'ABC College', 'yash', 22, '456
Avenue, Town', 'XYZ University')

2. Count number of vowels in a string (No control flow)

string = "Hello World"


vowels = "aeiouAEIOU"

count =sum(map([Link], vowels))


print("Number of vowels:", count)

Output:

Number of vowels: 3

3. Check if a given key exists in a dictionary

student = {"name": "yash", "age": 20, "grade": "A"}

Prepared By: Mr. N N V Ramana, Asst Professor, Dept. of MCA


B V C COLLEGE OF ENGINEERING
(An Autonomous Institution)
PALACHARLA, 533102
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING LAB MANUAL

key_to_check = "age"

if key_to_check in student:
print("Key exists.")
else:
print("Key does not exist.")

Output:

Key exists.

4. Add a new key-value pair to an existing dictionary

student = {"name": "yash", "age": 20}

student["grade"] = "A"
print("Updated dictionary:", student)

Output:

Updated dictionary: {'name': 'yash', 'age': 20, 'grade': 'A'}

5. Sum all the items in a given dictionary

data = {"a": 10, "b": 20, "c": 30}


total=0
for i in [Link]:
total+=total+i
print("Sum of all items:", total)

Output:

Sum of all items: 60

UNIT-IV

UNIT-IV: FILES AND OBJECT-ORIENTED PROGRAMMING

1. Files: Types, Creating and Reading Text Data, File Methods to Read and Write Data

Prepared By: Mr. N N V Ramana, Asst Professor, Dept. of MCA


B V C COLLEGE OF ENGINEERING
(An Autonomous Institution)
PALACHARLA, 533102
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING LAB MANUAL

Files are used to store data persistently outside of program memory. Python supports
different file types: text files (human-readable) and binary files (non-readable). You open
files using the open() function with modes such as 'r' (read), 'w' (write), 'a' (append), and 'b'
(binary). Reading from files can be done with .read(), .readline(), or .readlines() methods.
Writing uses .write() or .writelines(). It’s important to close files after operations using
.close() or preferably use with statement (context manager) for automatic closing. Proper file
handling prevents data loss and ensures resource management.

2. Reading and Writing Binary Files, Pickle Module, Reading and Writing CSV Files

Binary files store data in binary format and require binary mode ('rb' or 'wb') to read/write.
The pickle module serializes and deserializes Python objects to/from binary files, allowing
complex data like objects and lists to be saved and loaded. CSV files (Comma Separated
Values) store tabular data; Python’s csv module provides functions to read and write CSVs
easily, handling commas, newlines, and quotes properly. These file operations are vital in
real-world applications like data storage, sharing, and interoperability with other programs.

3. Python os and [Link] Modules

The os module provides portable ways to interact with the operating system, such as reading
environment variables, creating/deleting directories, and running system commands. The
[Link] submodule handles file path manipulations like joining, splitting, checking existence,
and getting file metadata. These modules are essential for writing robust, OS-independent
Python scripts that interact with the filesystem.

4. Object-Oriented Programming (OOP): Classes and Objects

OOP is a programming paradigm based on the concept of objects, which encapsulate data
and behavior. In Python, classes define blueprints for objects. A class contains attributes
(variables) and methods (functions). Objects are instances of classes created by calling the
class name like a function. The __init__ method is a constructor that initializes new objects.
Understanding classes and objects is fundamental for designing modular, reusable, and
maintainable code. OOP helps model real-world entities and relationships naturally.

5. Classes with Multiple Objects, Class Attributes vs Data Attributes

Multiple objects can be created from a single class, each maintaining its own state through
instance variables. Class attributes are shared by all instances, whereas data attributes
(instance variables) belong to individual objects. Differentiating between them is crucial for
proper data handling in OOP. Class methods and static methods operate differently regarding
access to instance or class-level data.

6. Encapsulation, Inheritance, Polymorphism

Prepared By: Mr. N N V Ramana, Asst Professor, Dept. of MCA


B V C COLLEGE OF ENGINEERING
(An Autonomous Institution)
PALACHARLA, 533102
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING LAB MANUAL

 Encapsulation hides object data by using private variables (conventionally prefixed


with underscores) and exposes interfaces via methods, promoting data integrity and
security.
 Inheritance allows a new class (child) to inherit properties and methods from an
existing class (parent), facilitating code reuse and hierarchical organization.
 Polymorphism enables methods to work with objects of different classes, typically
through method overriding or duck typing, increasing flexibility. These OOP
principles are key for advanced design and building complex applications.

SAMPLE EXPERIMENTS:

1. Sort words in a file and write to another file (lowercased)

# Writing sample data to input file


with open("[Link]", "w") as f:
[Link]("Banana Apple orange Mango kiwi")

# Reading, processing, and writing to output file


with open("[Link]", "r") as f:
words = [Link]().lower().split()
[Link]()

with open("[Link]", "w") as f:


for word in words:
[Link](word + "\n")

# Output: Words sorted and written in lower-case to [Link]

2. Print each line of a file in reverse order

with open("[Link]", "w") as f:


[Link]("Hello world\nPython is fun\nOpenAI GPT")

with open("[Link]", "r") as f:


lines = [Link]()
for line in lines:
print([Link]()[::-1])

Output:

dlrow olleH
nuf si nohtyP
TPG IAnepO

Prepared By: Mr. N N V Ramana, Asst Professor, Dept. of MCA


B V C COLLEGE OF ENGINEERING
(An Autonomous Institution)
PALACHARLA, 533102
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING LAB MANUAL

3. Compute number of characters, words, and lines in a file

with open("[Link]", "r") as f:


lines = [Link]()
num_lines = len(lines)
num_words = sum(len([Link]()) for line in lines)
num_chars = sum(len(line) for line in lines)

print("Lines:", num_lines)
print("Words:", num_words)
print("Characters:", num_chars)

Output:
assume the [Link] is
Hello world.
This is a test file.
Python is great!

Lines: 3
Words: 10
Characters: 54

4. Create, display, append, insert, and reverse an array

import array

arr = [Link]('i', [10, 20, 30])

# Display
print("Original array:", arr)

# Append
[Link](40)
print("After append:", arr)

# Insert at position
[Link](1, 15)
print("After insert at index 1:", arr)

# Reverse
[Link]()
print("Reversed array:", arr)

Prepared By: Mr. N N V Ramana, Asst Professor, Dept. of MCA


B V C COLLEGE OF ENGINEERING
(An Autonomous Institution)
PALACHARLA, 533102
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING LAB MANUAL

Output:

Original array: array('i', [10, 20, 30])


After append: array('i', [10, 20, 30, 40])
After insert at index 1: array('i', [10, 15, 20, 30, 40])
Reversed array: array('i', [40, 30, 20, 15, 10])

5. Add, transpose, and multiply two matrices

import numpy as np

A = [Link]([[1, 2], [3, 4]])


B = [Link]([[5, 6], [7, 8]])

# Addition
add = A + B
print("Addition:\n", add)

# Transpose
print("Transpose of A:\n", A.T)

# Multiplication
multiply = A @ B
print("Multiplication:\n", multiply)

Output:

Addition:
[[ 6 8]
[10 12]]
Transpose of A:
[[1 3]
[2 4]]
Multiplication:
[[19 22]
[43 50]]

6. Class representing shapes with subclasses

import math

Prepared By: Mr. N N V Ramana, Asst Professor, Dept. of MCA


B V C COLLEGE OF ENGINEERING
(An Autonomous Institution)
PALACHARLA, 533102
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING LAB MANUAL

class Shape:
def area(self):
pass

def perimeter(self):
pass

class Circle(Shape):
def __init__(self, radius):
[Link] = radius

def area(self):
return [Link] * [Link]**2

def perimeter(self):
return 2 * [Link] * [Link]

class Triangle(Shape):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c

def perimeter(self):
return self.a + self.b + self.c

def area(self):
s = [Link]() / 2
return [Link](s*(s-self.a)*(s-self.b)*(s-self.c))

class Square(Shape):
def __init__(self, side):
[Link] = side

def area(self):
return [Link]**2

def perimeter(self):
return 4 * [Link]

# Example usage
circle = Circle(5)
print("Circle - Area:", [Link](), "Perimeter:", [Link]())

Prepared By: Mr. N N V Ramana, Asst Professor, Dept. of MCA


B V C COLLEGE OF ENGINEERING
(An Autonomous Institution)
PALACHARLA, 533102
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING LAB MANUAL

triangle = Triangle(3, 4, 5)
print("Triangle - Area:", [Link](), "Perimeter:", [Link]())

square = Square(4)
print("Square - Area:", [Link](), "Perimeter:", [Link]())

Output:

Circle - Area: 78.53981633974483 Perimeter: 31.41592653589793

Triangle - Area: 6.0 Perimeter: 12

Square - Area: 16 Perimeter: 16

UNIT-V:

INTRODUCTION TO DATA SCIENCE AND FUNCTIONAL PROGRAMMING

1. Functional Programming (Moderate weight)

Functional programming is a paradigm that treats computation as evaluation of mathematical


functions without changing state or data. Python supports functional concepts such as first-
class functions, higher-order functions (functions taking functions as arguments), and
anonymous functions (lambda). Functions like map(), filter(), and reduce() are functional
tools for transforming data collections efficiently. This paradigm helps write concise,
readable, and bug-resistant code.

2. JSON and XML in Python (Moderate weight)

JSON (JavaScript Object Notation) and XML (eXtensible Markup Language) are widely
used formats for data interchange. Python’s json module allows encoding Python objects into
JSON strings and decoding JSON into Python data types, facilitating API interaction and
configuration management. The [Link] module handles XML parsing and
generation. Knowledge of these formats is essential for modern applications that
communicate over the web or exchange structured data.

3. NumPy with Python (High weight)

NumPy is the fundamental package for scientific computing in Python, providing support for
large, multi-dimensional arrays and matrices, along with a vast collection of high-level
mathematical functions. It allows vectorized operations which improve performance over
standard Python loops. NumPy arrays consume less memory and provide efficient storage

Prepared By: Mr. N N V Ramana, Asst Professor, Dept. of MCA


B V C COLLEGE OF ENGINEERING
(An Autonomous Institution)
PALACHARLA, 533102
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING LAB MANUAL

and computation. NumPy is foundational for data science, machine learning, and numerical
analysis workflows.

4. Pandas (High weight)

Pandas is a powerful data manipulation and analysis library built on top of NumPy. It
provides two main data structures: Series (one-dimensional) and DataFrame (two-
dimensional table). Pandas simplifies handling missing data, merging/joining datasets,
filtering, aggregation, and time series analysis. It integrates with visualization libraries and is
widely used in data science projects. Mastery of pandas is essential for anyone serious about
data analysis in Python.

SAMPLE EXPERIMENTS:

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

import json
import re

def contains_complex(json_str):
# Load JSON string into Python object
try:
obj = [Link](json_str)
except [Link]:
print("Invalid JSON string")
return False

# Function to check recursively for complex numbers represented as {"real": x,


"imag": y}
def check_complex(o):
if isinstance(o, dict):
# Check if dict represents a complex number (common JSON way)
if set([Link]()) == {"real", "imag"} and all(isinstance(v, (int, float)) for v in
[Link]()):
return True
# Else, check recursively inside dict values
return any(check_complex(v) for v in [Link]())
elif isinstance(o, list):
return any(check_complex(i) for i in o)
else:
return False

return check_complex(obj)

Prepared By: Mr. N N V Ramana, Asst Professor, Dept. of MCA


B V C COLLEGE OF ENGINEERING
(An Autonomous Institution)
PALACHARLA, 533102
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING LAB MANUAL

# Example JSON string containing complex number


json_str = '{"value1": 10, "value2": {"real": 3, "imag": 4}}'
print("Contains complex number?", contains_complex(json_str))

Output:

Contains complex number? True

2. Python program to demonstrate numpy arrays creation using array() function

import numpy as np

# Create numpy arrays from lists


arr1 = [Link]([1, 2, 3, 4, 5])
arr2 = [Link]([[1, 2, 3], [4, 5, 6]])

print("1D array:\n", arr1)


print("2D array:\n", arr2)

Output:

1D array:
[1 2 3 4 5]
2D array:
[[1 2 3]
[4 5 6]]

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

import numpy as np

arr = [Link]([[1, 2, 3], [4, 5, 6]])

print("Number of dimensions (ndim):", [Link])


print("Shape of array:", [Link])
print("Total number of elements (size):", [Link])
print("Data type of elements (dtype):", [Link])

Output:

Number of dimensions (ndim): 2


Shape of array: (2, 3)

Prepared By: Mr. N N V Ramana, Asst Professor, Dept. of MCA


B V C COLLEGE OF ENGINEERING
(An Autonomous Institution)
PALACHARLA, 533102
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING LAB MANUAL

Total number of elements (size): 6


Data type of elements (dtype): int64

4. Python program to demonstrate basic slicing, integer and boolean indexing

import numpy as np

arr = [Link]([10, 20, 30, 40, 50, 60])

# Basic slicing
print("Slicing [1:4]:", arr[1:4])

# Integer indexing
indices = [0, 2, 4]
print("Integer indexing:", arr[indices])

# Boolean indexing (select elements > 30)


bool_idx = arr > 30
print("Boolean indexing:", arr[bool_idx])

Output:

Slicing [1:4]: [20 30 40]


Integer indexing: [10 30 50]
Boolean indexing: [40 50 60]

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

import numpy as np

arr = [Link]([1, 3, 5, 7, 9])

print("Minimum:", [Link]())
print("Maximum:", [Link]())
print("Sum:", [Link]())
print("Cumulative sum:", [Link]())

Output:

Minimum: 1
Maximum: 9
Sum: 25

Prepared By: Mr. N N V Ramana, Asst Professor, Dept. of MCA


B V C COLLEGE OF ENGINEERING
(An Autonomous Institution)
PALACHARLA, 533102
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING LAB MANUAL

Cumulative sum: [ 1 4 9 16 25]

6. Create dictionary with lists and convert to pandas DataFrame, explore data

import pandas as pd
import numpy as np

data = {
'A': list(range(10)),
'B': list([Link](0, 50, 10)),
'C': list([Link](['X', 'Y', 'Z'], 10)),
'D': list([Link](10)),
'E': list([Link](1.5, 15.5, 10))
}

df = [Link](data)

print("DataFrame head():\n", [Link]())

# Data selection examples


print("\nSelect column A:\n", df['A'])
print("\nSelect rows where B > 25:\n", df[df['B'] > 25])
print("\nSelect rows and columns (iloc):\n", [Link][0:3, 1:4])

Sample Output:

DataFrame head():
A B C D E
0 0 27 Z 0.465112 1.50
1 1 43 Y 0.891228 3.00
2 2 4 Y 0.123455 4.99
3 3 38 Y 1.234987 6.49
4 4 20 Z 1.672299 7.99

Select column A:
0 0
1 1
2 2
3 3
4 4
5 5

Prepared By: Mr. N N V Ramana, Asst Professor, Dept. of MCA


B V C COLLEGE OF ENGINEERING
(An Autonomous Institution)
PALACHARLA, 533102
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING LAB MANUAL

6 6
7 7
8 8
9 9
Name: A, dtype: int64

Select rows where B > 25:

A B C D E
0 0 27 Z 0.465112 1.50
1 1 43 Y 0.891228 3.00
3 3 38 Y 1.234987 6.49
7 7 31 Z 0.231234 12.49

Select-rows-and-columns-(iloc):
B C D
0 27 Z 0.465112
1 43 Y 0.891228
2 4 Y 0.123455

7. Scatter and plot of two columns from the above DataFrame using matplotlib
import [Link] as plt
import pandas as pd
import numpy as np
data = {
'A': list(range(10)),
'B': list([Link](0, 50, 10)),
'C': list([Link](['X', 'Y', 'Z'], 10)),
'D': list([Link](10)),
'E': list([Link](1.5, 15.5, 10))
}

df = [Link](data)
# Select columns A and B
x = df['A']
y = df['B']

# Scatter plot
[Link](x, y, color='blue')

Prepared By: Mr. N N V Ramana, Asst Professor, Dept. of MCA


B V C COLLEGE OF ENGINEERING
(An Autonomous Institution)
PALACHARLA, 533102
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING LAB MANUAL

[Link]('Scatter Plot of A vs B')


[Link]('A')
[Link]('B')
[Link]()

# Line plot
[Link](x, y, color='red', marker='o')
[Link]('Line Plot of A vs B')
[Link]('A')
[Link]('B')
[Link]()

Output:

Prepared By: Mr. N N V Ramana, Asst Professor, Dept. of MCA

Common questions

Powered by AI

Python is dynamically typed, meaning variables do not need to have a type specified when declared; type checking is done at runtime. It is strongly typed, meaning operations will not be implicitly dispatched on incompatible types without explicit conversion, unlike weakly typed languages which allow more implicit type casting. This combination allows for flexibility and error reduction as it avoids unintended automatic type casts, ensuring operations use explicitly the correct types .

Python's control flow statements, such as conditional statements (if, if-else, nested if) and loops (for, while), allow the developer to dictate the flow of execution in a program clearly and logically. These structures align closely with human logical processes, making the code easier to understand and maintain . They enable complex decision-making processes and repetition tasks to be implemented succinctly without extensive lines of code, promoting clear and maintainable code .

Tuples in Python are immutable ordered collections defined with parentheses, while lists are mutable and defined with square brackets . Tuples are used when the data should not change throughout the lifetime of a program, such as fixed data sets or dictionary keys, whereas lists are preferred for data that will change or need ordering operations like appending or popping . Tuples may also be used where memory optimization is crucial, as they are more memory-efficient than lists .

NumPy's vectorized operations are beneficial because they allow batch operations on data without the need for explicit loops, which can significantly enhance performance . These operations eliminate the overhead of loop constructs in Python and utilize low-level optimizations in NumPy's internal C implementations, making them faster and consuming less memory . This is crucial for tasks like operations on large datasets commonly encountered in scientific computing and data analysis .

Python's 'try' and 'except' statements allow developers to manage runtime errors gracefully, preventing program crashes by catching exceptions associated with errors . This capability is crucial for building robust applications, as it ensures smoother user experiences and facilitates error logging and debugging . By handling exceptions, a program can continue to run or recover from errors, thus enhancing reliability and user trust in the software .

Python's built-in list functions such as append(), pop(), and remove() support dynamic data manipulation by allowing easy addition, removal, and modification of elements . Functions like len(), min(), max(), and sum() facilitate basic data analysis directly on lists . Their role in indexing, slicing, and concatenation allows sophisticated data organization and restructuring, making lists versatile tools for handling diverse datasets in Python .

The Python json module provides functions for encoding Python objects into JSON strings and decoding JSON strings back into Python data types . This functionality is crucial in modern software development for API interactions, configuration management, and data serialization, allowing seamless data interchange between different systems, including non-Python-based ones . JSON's human-readability and widespread adoption in web technologies make it essential for integrating systems across diverse platforms and languages, enabling interoperability and flexibility .

Python's zip() function is used to combine elements from multiple iterables into tuples, enabling parallel iteration over separate data sets . This facilitates the alignment and paired processing of related data elements, streamlining operations like pairwise computations or merging lists for data analysis . The zip() function simplifies the handling of synchronously iterated data, enhancing code clarity and reducing the likelihood of errors associated with parallel list processing .

Understanding function scope and lifetime is crucial because it determines where variables can be accessed in a program and how long they persist in memory . Variables within a function are local, existing only during the function's execution, while global variables can be accessed throughout the module and persist longer . Mismanaging scope can lead to logic errors, unintended variable modifications, or memory bloat due to unnecessarily persistent global variables . Proper management enhances code reliability and efficiency.

A frozenset is an immutable variant of a set, which cannot be changed after its creation, unlike a regular set . This immutability is beneficial when an immutable collection is required, such as using sets as elements in other sets or as keys in dictionaries. Choosing frozensets helps ensure data integrity by preventing accidental modifications . However, this choice means forfeiting the ability to add or remove elements from the collection, necessitating a trade-off between flexibility and safety .

You might also like