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

Python Programming Lab1

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)
4 views8 pages

Python Programming Lab1

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

Sure!

Below are Python programs demonstrating each of the topics you've mentioned:

---

### 1. **Flow Controls, Functions, and String Manipulation**

```python

# Flow Control: if-else

def check_even_odd(num):

if num % 2 == 0:

return "Even"

else:

return "Odd"

# Function: String Manipulation

def reverse_string(s):

return s[::-1]

# Example Usage:

number = 5

print(f"{number} is {check_even_odd(number)}.")

text = "Python"

print(f"Reversed string: {reverse_string(text)}")

```

---

### 2. **Operations on Tuples and Lists**


```python

# Tuple Operations

my_tuple = (1, 2, 3, 4)

print("Tuple:", my_tuple)

print("Tuple Length:", len(my_tuple))

print("Index of 3 in Tuple:", my_tuple.index(3))

# List Operations

my_list = [10, 20, 30, 40]

my_list.append(50)

print("List after Append:", my_list)

my_list.remove(30)

print("List after Remove:", my_list)

```

---

### 3. **Operations on Sets**

```python

# Set Operations

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

print("Set:", my_set)

my_set.add(6)

print("Set after Add:", my_set)

my_set.remove(2)

print("Set after Remove:", my_set)


# Union and Intersection

set_a = {1, 2, 3}

set_b = {3, 4, 5}

print("Union of A and B:", set_a | set_b)

print("Intersection of A and B:", set_a & set_b)

```

---

### 4. **Operations on Dictionary**

```python

# Dictionary Operations

my_dict = {"name": "John", "age": 25, "city": "New York"}

print("Original Dictionary:", my_dict)

my_dict["age"] = 26 # Update value

print("Updated Dictionary:", my_dict)

my_dict["country"] = "USA" # Add new key-value pair

print("Dictionary after Adding new key:", my_dict)

del my_dict["city"] # Remove key

print("Dictionary after Deleting key:", my_dict)

```

---
### 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 display_info(self):

print(f"Car Information: {self.year} {self.brand} {self.model}")

# Example Usage:

car1 = Car("Toyota", "Corolla", 2020)

car1.display_info()

```

---

### 6. **Method Overloading – Create classes for Vehicle and Bus**

```python

class Vehicle:

def display_info(self):

print("This is a vehicle")

class Bus(Vehicle):

def display_info(self, capacity=None):

if capacity:
print(f"This bus can carry {capacity} passengers.")

else:

print("This is a bus.")

# Example Usage:

bus1 = Bus()

bus1.display_info() # Method Overloading (No argument)

bus1.display_info(50) # Method Overloading (With argument)

```

---

### 7. **Files – Reading and Writing – Perform basic operation of reading and writing with student
file**

```python

# Writing to a file

with open("student.txt", "w") as file:

file.write("Name: John Doe\n")

file.write("Age: 20\n")

file.write("Course: Computer Science\n")

# Reading from a file

with open("student.txt", "r") as file:

content = file.read()

print(content)

```

---
### 8. **Regular Expressions**

```python

import re

# Match a phone number pattern (e.g., 123-456-7890)

pattern = r"\d{3}-\d{3}-\d{4}"

phone_number = "Call me at 123-456-7890"

match = re.search(pattern, phone_number)

if match:

print(f"Found phone number: {match.group()}")

else:

print("Phone number not found.")

```

---

### 9. **Modules**

```python

# Assuming we have a module named 'math_operations.py'

# math_operations.py content:

# def add(a, b):

# return a + b

# Main Script

import math_operations
result = math_operations.add(5, 7)

print(f"The sum is: {result}")

```

---

### 10. **Packages**

1. Create a directory `mypackage` with an `__init__.py` file.

2. Inside `mypackage`, create a file `calculator.py` with the following content:

```python

# calculator.py inside mypackage

def add(a, b):

return a + b

def subtract(a, b):

return a - b

```

3. Now, in the main script, you can import and use the package:

```python

from mypackage import calculator

sum_result = calculator.add(10, 20)

print(f"Sum: {sum_result}")
difference_result = calculator.subtract(10, 5)

print(f"Difference: {difference_result}")

```

---

### 11. **Exception Handling**

```python

def divide_numbers(a, b):

try:

result = a / b

except ZeroDivisionError:

return "Error: Cannot divide by zero."

except Exception as e:

return f"An error occurred: {e}"

else:

return f"The result is: {result}"

# Example Usage:

print(divide_numbers(10, 2)) # Valid division

print(divide_numbers(10, 0)) # Division by zero error

print(divide_numbers(10, 'a')) # Invalid data type error

```

---

These Python examples cover all the topics you've mentioned. Let me know if you'd like more detailed
explanations or have any further questions!

You might also like