PRACTICAL - V: PYTHON PROGRAMMING
EXERCISES: 1 Demonstrate the different ways of creating list objects which operate on
following functions with suitable examples. i) list( ) ii) len( ) iii) count( ) iv) index ( ) v) append(
) vi) insert( ) vii) extend() viii) remove( )ix) pop( ) x) reverse( ) xi) sort( ) xii) copy( ) xiii) clear(
)
# Different Ways of Creating List Objects
# Method 1: Empty list
list1 = []
print("Empty List:", list1)
# Method 2: Using list()
list2 = list((10, 20, 30))
print("Using list():", list2)
# Method 3: Directly using square brackets
list3 = [1, 2, 3, 4, 5]
print("Using []:", list3)
print("List Functions Demonstration")
# Sample list
numbers = [10, 20, 30, 20, 40, 50]
print("Original List:", numbers)
# i) list()
new_list = list((100, 200, 300))
print("\n list() =", new_list)
# ii) len()
print(" len() =", len(numbers))
# iii) count()
print("count(20) =", [Link](20))
# iv) index()
print("index(30) =", [Link](30))
# v) append()
[Link](60)
print("append(60) =", numbers)
# vi) insert()
[Link](2, 25)
print("insert(2,25) =", numbers)
# vii) extend()
[Link]([70, 80])
print("extend([70,80]) =", numbers)
# viii) remove()
[Link](20)
print(" remove(20) =", numbers)
# ix) pop()
removed = [Link]()
print(" pop() removed =", removed)
print("List after pop() =", numbers)
# x) reverse()
[Link]()
print("reverse() =", numbers)
# xi) sort()
[Link]()
print("sort() =", numbers)
# xii) copy()
copy_list = [Link]()
print("copy() =", copy_list)
# xiii) clear()
copy_list.clear()
print("clear() =", copy_list)
EXERCISES: 2 Demonstrate the different ways of creating tuple objects which operate on
following functions with suitable examples. i) len( ) ii) count( ) iii) index( ) iv) sorted( ) v) min( )
vi)max( ) vii) cmp( ) viii) reversed( )
# Different ways of creating tuple objects
# Method 1: Empty tuple
t1 = ()
print("Empty Tuple:", t1)
# Method 2: Tuple with integers
t2 = (10, 20, 30, 40, 20)
print("Integer Tuple:", t2)
# Method 3: Mixed data type tuple
t3 = (1, "Python", 3.14, True)
print("Mixed Tuple:", t3)
# Method 4: Using tuple() constructor
t4 = tuple([5, 10, 15, 20])
print("Tuple using tuple() constructor:", t4)
print("\n--- Tuple Functions ---")
# i) len()
print("1. Length of t2 =", len(t2))
# ii) count()
print("2. Count of 20 in t2 =", [Link](20))
# iii) index()
print("3. Index of 30 in t2 =", [Link](30))
# iv) sorted()
print("4. Sorted tuple =", sorted(t2))
# v) min()
print("5. Minimum value =", min(t2))
# vi) max()
print("6. Maximum value =", max(t2))
# vii) cmp() (Not available in Python 3)
a = (1, 2, 3)
b = (1, 2, 4)
print("7. cmp() is not available in Python 3")
print(" a == b :", a == b)
print(" a < b :", a < b)
print(" a > b :", a > b)
# viii) reversed()
print("8. Reversed tuple =", tuple(reversed(t2)))
EXERCISES: 3 Demonstrate the different ways of creating set objects which operate on
following functions with suitable examples. i) add( ) ii) update( ) iii) copy( ) iv) pop( ) v)
remove( ) vi)discard( ) vii) clear( ) viii) union()ix) intersection( ) x) difference( )
# Different ways of creating set objects
# Method 1: Empty set
s1 = set()
print("Empty Set:", s1)
# Method 2: Set with values
s2 = {10, 20, 30, 40}
print("Set with values:", s2)
# Method 3: Using set() constructor
s3 = set([1, 2, 3, 4, 5])
print("Set using set() constructor:", s3)
print("\n--- Set Functions ---")
# i) add()
[Link](50)
print("1. After add(50):", s2)
# ii) update()
[Link]([60, 70])
print("2. After update([60, 70]):", s2)
# iii) copy()
s4 = [Link]()
print("3. Copied Set:", s4)
# iv) pop()
removed = [Link]()
print("4. Popped element:", removed)
print(" Set after pop():", s2)
# v) remove()
[Link](30)
print("5. After remove(30):", s2)
# vi) discard()
[Link](100) # No error if element is absent
print("6. After discard(100):", s2)
# vii) clear()
temp = [Link]()
[Link]()
print("7. After clear():", temp)
# viii) union()
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print("8. Union:", [Link](B))
# ix) intersection()
print(“ Intersection:", [Link](B))
# x) difference()
print("10. Difference (A - B):", [Link](B))
EXERCISES: 4 Demonstrate the different ways of creating set objects which operate on
following functions with suitable examples.
i) dict( ) ii) len( ) iii) clear( ) iv) get( ) v) pop( ) vi)popitem( ) vii) keys( ) viii)
values()ix) items( ) x) copy( ) xi) update( )
# Different ways of creating dictionary objects
# Method 1: Using {}
dict1 = {"Name": "Alice", "Age": 20, "Course": "Python"}
# Method 2: Using dict() constructor
dict2 = dict(Name="Bob", Age=22, Course="Java")
# Method 3: Using list of tuples
dict3 = dict([("City", "Chennai"), ("State", "Tamil Nadu")])
print("Dictionary 1:", dict1)
print("Dictionary 2:", dict2)
print("Dictionary 3:", dict3)
# i) dict()
new_dict = dict([(1, "One"), (2, "Two"), (3, "Three")])
print(“ dict() function:", new_dict)
# ii) len()
print(" Length of Dictionary:", len(dict1))
# iii) clear()
temp = [Link]()
[Link]()
print(" After clear():", temp)
# iv) get()
print("get('Name'):", [Link]("Name"))
print("get('Marks', 'Not Found'):", [Link]("Marks", "Not Found"))
# v) pop()
age = [Link]("Age")
print(" pop('Age'):", age)
print("Dictionary after pop():", dict1)
# vi) popitem()
item = [Link]()
print("popitem():", item)
print("Dictionary after popitem():", dict2)
# vii) keys()
print("keys():", [Link]())
# viii) values()
print(“ values():", [Link]())
# ix) items()
print(" items():", [Link]())
# x) copy()
copy_dict = [Link]()
print(" copy():", copy_dict)
# xi) update()
[Link]({"Country": "India", "Pincode": 600001})
print(" update():", dict3)
EXERCISES: 5 Write a Regular Expression to represent all 10-digit mobile numbers, to check
whether the given number is a valid mobile number or not following the rules?
Rules:
a) Every number should contain exactly 10 digits.
b) The first digit should be 7 or 8 or 9.
mobile = input("Enter Mobile Number: ")
pattern = r'^[789][0-9]{9}$'
if [Link](pattern, mobile):
print("Valid Mobile Number")
else:
print("Invalid Mobile Number")
EXERCISES: 6 Write a Python program to demonstrate usage of Local and Global variables.
# Global variable
x = 100
def display():
# Local variable
y = 50
print("Inside Function")
print("Global Variable x =", x)
print("Local Variable y =", y)
# Function call
display()
print("\nOutside Function")
print("Global Variable x =", x)
EXERCISES: 7 Demonstrate lambda functions in Python with suitable example programs.
a) # Lambda function to find square
square = lambda x: x * x
num = int(input("Enter a number: "))
print("Square =", square(num))
b) # Lambda function to find maximum
maximum = lambda a, b: a if a > b else b
print("Maximum =", maximum(15, 25))
c) # Filter even numbers using lambda
numbers = [10, 15, 20, 25, 30, 35]
even = list(filter(lambda x: x % 2 == 0, numbers))
print("Even Numbers:", even)
EXERCISES: 8 Demonstrate the following in-built functions to use Regular Expressions very
easily in our applications.
i) compile( ) ii) finditer( ) iii) match( ) iv) fullmatch( ) v) search( ) vi) findall()
vii) sub( ) viii) subn( ) ix) split( )
Function Purpose
compile() Compiles a regular expression into a pattern object.
finditer() Returns an iterator of all match objects.
match() Checks for a match only at the beginning of the string.
fullmatch() Checks if the entire string matches the pattern.
search() Searches for the first occurrence anywhere in the string.
findall() Returns a list of all matches.
sub() Replaces all matches with another string.
subn() Replaces matches and returns the replacement count.
split() Splits a string using the given regular expression pattern.
# Python Program to Demonstrate Regular Expression Functions
import re
text = "Python is easy. Python is powerful. Python123"
# i) compile()
print("1. compile()")
pattern = [Link](r'Python')
print(pattern)
# ii) finditer()
print("\n2. finditer()")
for match in [Link](text):
print("Found at position:", [Link](), "-", [Link]())
# iii) match()
print("\n3. match()")
result = [Link](r'Python', text)
if result:
print("Matched:", [Link]())
else:
print("No Match")
# iv) fullmatch()
print("\n fullmatch()")
result = [Link](r'Python', text)
if result:
print("Full Match")
else:
print("No Full Match")
# v) search()
print("\n search()")
result = [Link](r'powerful', text)
if result:
print("Found:", [Link]())
else:
print("Not Found")
# vi) findall()
print("\n findall()")
result = [Link](r'Python', text)
print(result)
# vii) sub()
print("\n sub()")
result = [Link](r'Python', 'Java', text)
print(result)
# viii) subn()
print("\n subn()")
result = [Link](r'Python', 'Java', text)
print(result)
# ix) split()
print("\n split()")
result = [Link](r'\s', text)
print(result)
EXERCISES: 9. a) Python program to perform read and write operations on a file.
b) Python program to copy the contents of a file to another file.
a) # Writing data to a file
file = open("[Link]", "w")
[Link]("Name: Bharath\n")
[Link]("Department: CSE\n")
[Link]("Course: Python Programming")
[Link]()
print("Data written successfully.")
# Reading data from the file
file = open("[Link]", "r")
content = [Link]()
print("\nContents of the File:")
print(content)
[Link]()
b) # Python Program to Copy Contents from One File to Another
# Open source file in read mode
source = open("[Link]", "r")
# Read data from source file
data = [Link]()
# Open destination file in write mode
destination = open("[Link]", "w")
# Write data into destination file
[Link](data)
# Close both files
[Link]()
[Link]()
print("File copied successfully.")
# Display the contents of the copied file
destination = open("[Link]", "r")
print("\nContents of the Copied File:")
print([Link]())
[Link]()
EXERCISES: 10 Demonstrate the following functions/methods which operates on strings in
Python with suitable examples:
i) len( ) ii) strip( ) iii) rstrip( ) iv) lstrip( ) v) find( ) vi) rfind( ) vii) index( )
viii) rindex()ix) count( ) x) replace( ) xi) split( ) xii) join( ) xiii) upper( )
xiv) lower( ) xv) swapcase( )xvi) title( ) xvii) capitalize( ) xviii) startswith()
xix) endswith()
# Python Program to Demonstrate String Functions
str1 = " Python Programming Language "
print("Original String:", str1)
# i) len()
print("\n len()")
print("Length =", len(str1))
# ii) strip()
print("\n strip()")
print([Link]())
# iii) rstrip()
print("\n rstrip()")
print([Link]())
# iv) lstrip()
print("\n lstrip()")
print([Link]())
# v) find()
print("\n find()")
print([Link]("Programming"))
# vi) rfind()
print("\n rfind()")
print([Link]("a"))
# vii) index()
print("\n7. index()")
print([Link]("Python"))
# viii) rindex()
print("\n rindex()")
print([Link]("a"))
# ix) count()
print("\n count()")
print([Link]("a"))
# x) replace()
print("\n1 replace()")
print([Link]("Python", "Java"))
# xi) split()
print("\n split()")
print([Link]())
# xii) join()
print("\n join()")
words = ["Python", "is", "Easy"]
print("-".join(words))
# xiii) upper()
print("\n upper()")
print([Link]())
# xiv) lower()
print("\n lower()")
print([Link]())
# xv) swapcase()
print("\n swapcase()")
print([Link]())
# xvi) title()
print("\n title()")
print([Link]())
# xvii) capitalize()
print("\n capitalize()")
print([Link]())
# xviii) startswith()
print("\n startswith()")
print([Link]().startswith("Python"))
# xix) endswith()
print("\n endswith()")
print([Link]().endswith("Language"))