Python Lab
Python Lab
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:
1. Write a program to define a function with multiple return values.
2. Write a program to define a function using default arguments.
3. Write a program to find the length of the string without using any library functions.
4. Write a program to check if the substring is present in a given string or not.
5. Write a program to perform the given operations on a list:
i. addition ii. Insertion iii. slicing
6. Write a program to perform any 5 built-in functions by taking any list.
UNIT-III:
Dictionaries: Creating Dictionary, Accessing and Modifying key:value Pairs in Dictionaries, Built-In
Functions Used on Dictionaries, Dictionary Methods, del Statement. Tuples and Sets: Creating Tuples, Basic
Tuple Operations, tuple() Function, Indexing and Slicing in Tuples, Built-In Functions Used on Tuples,
Relation between Tuples and Lists, Relation between Tuples and Dictionaries, Using zip() Function, Sets, Set
Methods, Frozenset.
Sample Experiments:
1. Write a program to create tuples (name, age, address, college) for at least two members and
concatenate the tuples and print the concatenated tuples.
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
[Link] a program to count the number of vowels in a string (No control flow allowed).
[Link] a program to check if a given key exists in a dictionary or not.
[Link] a program to add a new key-value pair to an existing dictionary.
[Link] 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.
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 find areas.
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
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
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 Operatorsv
iii) Identity Operators
5) Write a program to add and multiply complex numbers
6) Write a program to print multiplication table of a given number.
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.
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.
18) 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.
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
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
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
EXP1. Write a program to find the largest element among three Numbers.
# Program to find the largest among three numbers
# Taking input from the user
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
EXP3: Write a program to swap two numbers without using a temporary variable.
# Input from user
a = int(input("Enter first number (a): "))
b = int(input("Enter second number (b): "))
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
print(f"Before swapping: a = {a}, b = {b}")
V) Bitwise Operators
a & b: 1
a | b: 7
a ^ b: 6
~a: -6
a << 1: 10
a >> 1: 2
OUTPUT:
Enter a number to print its multiplication table: 7
Multiplication Table of 7:
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
EXP-9:Write a program to find the length of the string without using any library functions.
# Input string from the user
text = input("Enter a string: ")
# Initialize counter
count = 0
# i. Addition (concatenation)
add_list = [60, 70]
my_list += add_list
print("After addition:", my_list)
# ii. Insertion
my_list.insert(2, 25) # Insert 25 at index 2
print("After insertion at index 2:", my_list)
# iii. Slicing
sliced_list = my_list[2:6] # Get elements from index 2 to 5
print("Sliced list (index 2 to 5):", sliced_list)
OUTPUT:
Original list: [10, 20, 30, 40, 50]
After addition: [10, 20, 30, 40, 50, 60, 70]
After insertion at index 2: [10, 20, 25, 30, 40, 50, 60, 70]
Sliced list (index 2 to 5): [25, 30, 40, 50]
EXP-14:Write a program to count the number of vowels in a string (No control flow allowed).
# Input string from user
text = input("Enter a string: ")
# Count vowels using sum and comprehension (no if, for, or while loops)
vowel_count = sum(map(lower_text.count, "aeiou"))
EXP-18: 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.
# Read from source file
with open('[Link]', 'r') as source_file:
text = source_file.read()
EXP-20: Python program to compute the number of characters, words and lines in a file.
# Open the file in read mode
with open('[Link]', 'r') as file:
text = [Link]()
# Count lines
with open('[Link]', 'r') as file:
lines = [Link]()
num_lines = len(lines)
num_words = len([Link]())
num_characters = len(text)
# Display results
print("Number of lines:", num_lines)
print("Number of words:", num_words)
print("Number of characters:", num_characters)
OUTPUT:
If [Link] contains:
Hello World
Python is fun
THEN OUTPUT WILL BE:
Number of lines: 2
Number of words: 5
Number of characters: 26
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
EXP-21: Write a program to create, display, append, insert and reverse the order of the items in the
array.
import array
# 1. Create an array of integers
arr = [Link]('i', [10, 20, 30, 40, 50])
print("Original array:", arr)
# 2. Append an item
[Link](60)
print("After appending 60:", arr)
B = [[5, 6],
[7, 8]]
# 1. Matrix Addition
def add_matrices(A, B):
result = [[A[i][j] + B[i][j] for j in range(len(A[0]))] for i in range(len(A))]
return result
# 2. Matrix Transpose
def transpose_matrix(M):
result = [[M[j][i] for j in range(len(M))] for i in range(len(M[0]))]
return result
# 3. Matrix Multiplication
def multiply_matrices(A, B):
result = []
for i in range(len(A)):
row = []
for j in range(len(B[0])):
sum_product = 0
for k in range(len(B)):
sum_product += A[i][k] * B[k][j]
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
[Link](sum_product)
[Link](row)
return result
# Perform operations
add_result = add_matrices(A, B)
transpose_A = transpose_matrix(A)
multiply_result = multiply_matrices(A, B)
# Display results
print("Matrix A:")
for row in A:
print(row)
print("\nMatrix B:")
for row in B:
print(row)
print("\nAddition (A + B):")
for row in add_result:
print(row)
print("\nTranspose of A:")
for row in transpose_A:
print(row)
print("\nMultiplication (A x B):")
for row in multiply_result:
print(row)
OUTPUT:
Matrix A:
[1, 2]
[3, 4]
Matrix B:
[5, 6]
[7, 8]
Addition (A + B):
[6, 8]
[10, 12]
Transpose of A:
[1, 3]
[2, 4]
Multiplication (A x B):
[19, 22]
[43, 50]
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
EXP-23:Write a Python program to create a class that represents a shape. Include methods to
import math
# Base class
class Shape:
def __init__(self, name="Shape"):
[Link] = name
def area(self):
return 0
def perimeter(self):
return 0
def display(self):
print(f"{[Link]}:")
print(f" Area: {[Link]()}")
print(f" Perimeter: {[Link]()}\n")
def area(self):
return [Link] * [Link]
def perimeter(self):
return 2 * ([Link] + [Link])
def area(self):
return [Link] * [Link] ** 2
def perimeter(self):
return 2 * [Link] * [Link]
# Example usage
rect = Rectangle(5, 3)
circle = Circle(4)
[Link]()
[Link]()
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
OUTPUT:
Rectangle:
Area: 15
Perimeter: 16
Circle:
Area: 50.26548245743669
Perimeter: 25.132741228718345
EXP-24:Python program to check whether a JSON string contains complex object or not.
What is a “complex object” in JSON?
We usually refer to nested dictionaries, lists, or a dictionary inside a dictionary/list as complex. Simple
values would be just strings, numbers, booleans, etc.
import json
def is_complex(value):
"""Recursively checks if the value contains complex structures."""
if isinstance(value, dict):
# If any value in the dict is dict or list, it's complex
return any(isinstance(v, (dict, list)) or is_complex(v) for v in [Link]())
elif isinstance(value, list):
# If any item in list is dict or list, it's complex
return any(isinstance(item, (dict, list)) or is_complex(item) for item in value)
return False
EXP-25: Python Program to demonstrate NumPy arrays creation using array () function
✅ Note: Make sure NumPy is installed. You can install it using:
import numpy as np
# 1. Create a 1D array
array1 = [Link]([10, 20, 30, 40])
print("1D Array:")
print(array1)
# 2. Create a 2D array
array2 = [Link]([[1, 2, 3], [4, 5, 6]])
print("\n2D Array:")
print(array2)
# 3. Create a 3D array
array3 = [Link]([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print("\n3D Array:")
print(array3)
# 4. Create array with mixed data types (NumPy will upcast to a common type)
array4 = [Link]([1, 2.5, 3])
print("\nArray with mixed data types:")
print(array4)
OUTPUT:
1D Array:
[10 20 30 40]
2D Array:
[[1 2 3]
[4 5 6]]
3D Array:
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
# Number of dimensions
print("\nNumber of dimensions (ndim):", [Link])
EXP-27: Python program to demonstrate basic slicing, integer and Boolean indexing.
import numpy as np
# Create a 1D array
arr = [Link]([10, 20, 30, 40, 50, 60])
print("Original Array:")
print(arr)
# 1. Basic Slicing
print("\nBasic Slicing (arr[1:4]):")
print(arr[1:4]) # Output: [20, 30, 40]
# 2. Integer Indexing
indices = [0, 2, 4]
print("\nInteger Indexing (arr[[0, 2, 4]]):")
print(arr[indices]) # Output: [10, 30, 50]
# 3. Boolean Indexing
bool_index = arr > 30
print("\nBoolean Indexing (arr > 30):")
print("Boolean mask:", bool_index)
print("Filtered values:", arr[bool_index]) # Output: [40, 50, 60]
OUTPUT:
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
Original Array:
[10 20 30 40 50 60]
EXP-28: Python program to find min, max, sum, cumulative sum of array
import numpy as np
# Create a NumPy array
arr = [Link]([5, 10, 15, 20, 25])
print("Array:")
print(arr)
# Minimum value
print("\nMinimum value:", [Link](arr))
# Maximum value
print("Maximum value:", [Link](arr))
# Cumulative sum
print("Cumulative sum:", [Link](arr))
OUTPUT:
Array:
[ 5 10 15 20 25]
Minimum value: 5
Maximum value: 25
Sum of array: 75
Cumulative sum: [ 5 15 30 50 75]
EXP-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
# Step 1: Create a dictionary with lists
data = {
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
"Name": ["Althaf", "Ravi", "Priya", "John", "Sara", "Meena", "Ajay", "Nina", "Vijay", "Kiran"],
"Age": [21, 22, 20, 23, 24, 22, 21, 23, 25, 20],
"Department": ["CSE", "ECE", "EEE", "MECH", "CSE", "IT", "CSE", "IT", "ECE", "EEE"],
"Marks": [85, 78, 92, 70, 88, 90, 76, 84, 69, 95],
"City": ["Hyderabad", "Delhi", "Mumbai", "Chennai", "Bangalore", "Hyderabad", "Delhi", "Mumbai",
"Chennai", "Bangalore"]
}
EXP-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 [Link] as plt
df = [Link](data)
# SCATTER PLOT
[Link](figsize=(10, 4))
[Link](1, 2, 1)
[Link](ages, marks, color='blue', marker='o')
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
[Link]("Scatter Plot: Age vs Marks")
[Link]("Age")
[Link]("Marks")
[Link](True)
# LINE PLOT
[Link](1, 2, 2)
[Link](ages, marks, color='green', marker='s', linestyle='-')
[Link]("Line Plot: Age vs Marks")
[Link]("Age")
[Link]("Marks")
[Link](True)
# Show plots
plt.tight_layout()
[Link]()
OUTPUT:
WHAT YOU WILL SEE :
· Scatter Plot: Shows how each student’s marks vary by age, as individual points.
· · Line Plot: Connects the age vs marks data to observe trends or patterns.