0% found this document useful (0 votes)
3 views8 pages

Python Programming Lab2

Uploaded by

MS.KIRUTHIKA V
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views8 pages

Python Programming Lab2

Uploaded by

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

1.

Flow Controls, Functions, and String Manipulation


Python
# Flow control
def check_age(age):
if age >= 18:
return "You are eligible to vote"
else:
return "You are not eligible to vote"

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

# String manipulation
def reverse_string(s):
return s[::-1]

print(check_age(20)) # Output: You are eligible to vote


print(greet("John")) # Output: Hello, John!
print(reverse_string("hello")) # Output: olleh
2. Operations on Tuples and Lists
Python
# Tuple operations
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[0]) # Output: 1
print(my_tuple[-1]) # Output: 5

# List operations
my_list = [1, 2, 3, 4, 5]
my_list.append(6)
print(my_list) # Output: [1, 2, 3, 4, 5, 6]
my_list.insert(2, 10)
print(my_list) # Output: [1, 2, 10, 3, 4, 5, 6]

3. Operations on Sets
Python
# Set operations
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

print(set1.union(set2)) # Output: {1, 2, 3, 4, 5, 6, 7, 8}


print(set1.intersection(set2)) # Output: {4, 5}
print(set1.difference(set2)) # Output: {1, 2, 3}
4. Operations on Dictionary
Python
# Dictionary operations
my_dict = {"name": "John", "age": 30}

print(my_dict["name"]) # Output: John


my_dict["city"] = "New York"
print(my_dict) # Output: {'name': 'John', 'age': 30, 'city': 'New York'}
del my_dict["age"]
print(my_dict) # Output: {'name': 'John', 'city': 'New York'}

5. Simple OOP – Constructors – Create a class for representing a car


Python
class Car:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year
def print_details(self):
print(f"Brand: {self.brand}")
print(f"Model: {self.model}")
print(f"Year: {self.year}")

my_car = Car("Toyota", "Camry", 2020)


my_car.print_details()
6. Method Overloading – Create classes for vehicle and Bus and demonstrate
method overloading
class Vehicle:
def __init__(self, brand, model):
self.brand = brand
self.model = model

def display_details(self, *args):


print(f"Brand: {self.brand}")
print(f"Model: {self.model}")
if args:
print(f"Additional details: {args}")

class Bus(Vehicle):
def __init__(self, brand, model, capacity):
super().__init__(brand, model)
self.capacity = capacity

def display_details(self, *args):


super().display_details(*args)
print(f"Capacity: {self.capacity}")

my_bus = Bus("Mercedes", "Sprinter", 20)


my_bus.display_details("Luxury bus")
7. Files – Reading and Writing – Perform the basic operation of reading and
writing with student file
# Writing to a file
with open("students.txt", "w") as file:
file.write("John Doe, 20\n")
file.write("Jane Doe, 22\n")

# Reading from a file


with open("students.txt", "r") as file:
for line in file:
print(line.strip())

8. Regular Expressions
import re

text = "My phone number is 123-456-7890"


pattern = r"\d{3}-\d{3}-\d{4}"
match = re.search(pattern, text)

if match:
print(f"Phone number found: {match.group()}")
else:
print("No phone number found")
9. Modules
Let's create a simple module called math_operations.py:
# math_operations.py
def add(a, b):
return a + b

def subtract(a, b):


return a - b
# Now, let's use this module in another script:
# main.py
import math_operations

result = math_operations.add(5, 3)
print(result)
# Output: 8
10. Packages
Let's create a simple package called utils with two modules:
math_operations.py and string_operations.py.
utils/
__init__.py
math_operations.py
string_operations.py
#math_operations.py remains the same as above. Let's add a
#string_operations.py module:
# string_operations.py
def reverse_string(s):
return s[::-1]
#Now, let's use this package in another script:
# main.py
from utils.math_operations import add
from utils.string_operations import reverse_string

result = add(5, 3)
print(result)
# Output: 8
print(reverse_string("hello"))
# Output: olleh
11. Exception Handling
def divide(a, b):
try:
result = a / b
return result
except ZeroDivisionError:
print("Error: Division by zero is not allowed")
except TypeError:
print("Error: Invalid input type")
except Exception as e:
print(f"An error occurred: {e}")
print(divide(10, 2))
# Output: 5.0
print(divide(10, 0))
# Output: Error: Division by zero is not allowed

You might also like