UNIT-2
🧵 1. Strings and String Functions
Definition:
A string is a sequence of characters enclosed in single, double, or triple quotes.
Common String Methods:
capitalize(): Converts the first character to uppercase.
lower(): Converts all characters to lowercase.
upper(): Converts all characters to uppercase.
strip(): Removes leading and trailing spaces.
replace(old, new): Replaces occurrences of a substring with another substring.
split(separator): Splits the string into a list based on the separator.
join(iterable): Joins elements of an iterable into a single string.
Sample Program:
text = " Hello, Python World! "
print(text.strip().upper()) # Output: HELLO, PYTHON WORLD!
For a comprehensive list of string methods, refer to the GeeksforGeeks String
Methods page.
🔢 2. Lambda Functions
Definition:
Lambda functions are small anonymous functions defined with the lambda
keyword.
Syntax:
lambda arguments: expression
Sample Program:
# Function to add 10 to a number
add_ten = lambda x: x + 10
print(add_ten(5)) # Output: 15
Learn more about lambda functions at W3Schools Python Lambda.
📋 3. Lists, Tuples, and Dictionaries
Lists:
Ordered, mutable collection.
Defined using square brackets [].
Tuples:
Ordered, immutable collection.
Defined using parentheses ().
Dictionaries:
Unordered, mutable collection of key-value pairs.
Defined using curly braces {}.
Sample Program:
# List
fruits = ["apple", "banana", "cherry"]
print(fruits[1]) # Output: banana
# Tuple
coordinates = (10, 20)
print(coordinates[0]) # Output: 10
# Dictionary
person = {"name": "Alice", "age": 25}
print(person["name"]) # Output: Alice
🧱 4. Introduction to OOP (Object-Oriented Programming)
Key Concepts:
Class: A blueprint for creating objects.
Object: An instance of a class.
Attributes: Variables that belong to a class.
Methods: Functions that belong to a class.
Sample Program:
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def display_info(self):
print(f"Car Brand: {self.brand}, Model: {self.model}")
my_car = Car("Toyota", "Corolla")
my_car.display_info()
🧬 5. Inheritance and Polymorphism
Inheritance:
Allows a class (child) to inherit attributes and methods from another class (parent).
Polymorphism:
Allows methods to do different things based on the object it is acting upon.
Sample Program:
class Animal:
def sound(self):
return "Some generic sound"
class Dog(Animal):
def sound(self):
return "Bark"
class Cat(Animal):
def sound(self):
return "Meow"
animals = [Dog(), Cat()]
for animal in animals:
print(animal.sound())
In this example, both Dog and Cat classes inherit from the Animal class and
override the sound method to provide their own implementation. This demonstrates
polymorphism, where the same method name behaves differently based on the
object type
UNIT-3.
🧱 Abstract Classes and Interfaces in Python
Abstract Classes
Definition:
An abstract class in Python is a class that cannot be instantiated directly. It serves as
a blueprint for other classes. Abstract classes can contain abstract methods, which
are methods that are declared but contain no implementation. Subclasses of an
abstract class must implement all abstract methods to be instantiated.
Key Points:
Defined using the abc module.
Contains one or more abstract methods.
Cannot be instantiated directly.
Sample Program:
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Dog(Animal):
def sound(self):
return "Bark"
dog = Dog()
print(dog.sound()) # Output: Bark
Interfaces in Python
Definition:
Python does not have a built-in interface keyword like Java or C#. However,
interfaces can be implemented using abstract classes with only abstract methods.
Sample Program:
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
def start_engine(self):
pass
@abstractmethod
def stop_engine(self):
pass
class Car(Vehicle):
def start_engine(self):
return "Car engine started"
def stop_engine(self):
return "Car engine stopped"
car = Car()
print(car.start_engine()) # Output: Car engine started
🚨 Exception Handling in Python
Definition:
Exception handling in Python is managed using try, except, else, and finally blocks.
It allows developers to handle runtime errors, ensuring the program continues to run
smoothly.
Sample Program:
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print("Division successful.")
finally:
print("Execution completed.")
📂 Working with Files in Python
Definition:
Python provides built-in functions to create, read, update, and delete files. The
open() function is used to open a file, and it returns a file object.
Sample Program:
# Writing to a file
with open("sample.txt", "w") as file:
file.write("Hello, Python!")
# Reading from a file
with open("sample.txt", "r") as file:
content = file.read()
print(content) # Output: Hello, Python!
🔍 Regular Expressions in Python
Definition:
Regular expressions (regex) are sequences of characters that form search patterns.
Python's re module provides support for working with regular expressions.
Sample Program:
import re
pattern = r"\d{2}-\d{2}-\d{4}"
text = "Date of birth: 12-31-1990"
result = re.findall(pattern, text)
print(result) # Output: ['12-31-1990']
Python Database Connectivity (DB-API)
Definition:
Python provides a standardized interface for connecting to relational databases
through the DB-API. The sqlite3 module is part of Python's standard library and
provides a lightweight disk-based database.
Sample Program:
import sqlite3
# Connect to a database (or create it if it doesn't exist)
conn = sqlite3.connect("example.db")
cursor = conn.cursor()
# Create a table
cursor.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER
PRIMARY KEY, name TEXT)''')
# Insert a record
cursor.execute("INSERT INTO users (name) VALUES ('Alice')")
# Commit the transaction
conn.commit()
# Fetch and display records
cursor.execute("SELECT * FROM users")
print(cursor.fetchall()) # Output: [(1, 'Alice')]
# Close the connection
conn.close()
UNIT-4
Certainly! Here's a comprehensive guide on Data Science using Python, focusing
on creating and manipulating DataFrames, and visualizing data through various
plots. This is tailored for MCA students and includes explanations, sample
programs, and visual examples.
📊 Data Science with Python: A Comprehensive Guide for MCA Students
1. Creating DataFrames
a. From a CSV File
import pandas as pd
# Load data from a CSV file
df_csv = pd.read_csv('data.csv')
print(df_csv.head())
b. From an Excel File
# Load data from an Excel file
df_excel = pd.read_excel('data.xlsx')
print(df_excel.head())
c. From a Dictionary
# Create DataFrame from a dictionary
data_dict = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']}
df_dict = pd.DataFrame(data_dict)
print(df_dict)
d. From a List
# Create DataFrame from a list
data_list = [['Alice', 25, 'New York'],
['Bob', 30, 'Los Angeles'],
['Charlie', 35, 'Chicago']]
df_list = pd.DataFrame(data_list, columns=['Name', 'Age', 'City'])
print(df_list)
2. Operations on DataFrames
Selecting Columns:
# Select a single column
print(df_dict['Name'])
# Select multiple columns
print(df_dict[['Name', 'Age']])
Filtering Rows:
# Filter rows where Age is greater than 28
print(df_dict[df_dict['Age'] > 28])
Adding a New Column:
# Add a new column
df_dict['Country'] = ['USA', 'USA', 'USA']
print(df_dict)
Dropping a Column:
# Drop a column
df_dict = df_dict.drop('Country', axis=1)
print(df_dict)
3. Data Visualization with Matplotlib
a. Bar Graph
import matplotlib.pyplot as plt
# Bar graph
df_dict['Age'].plot(kind='bar')
plt.title('Age Distribution')
plt.xlabel('Index')
plt.ylabel('Age')
plt.show()
b. Histogram
# Histogram
df_dict['Age'].plot(kind='hist', bins=5)
plt.title('Age Distribution')
plt.xlabel('Age')
plt.show()
c. Pie Chart
# Pie chart
df_dict['City'].value_counts().plot(kind='pie', autopct='%1.1f%%')
plt.title('City Distribution')
plt.ylabel('')
plt.show()
d. Line Graph
# Line graph
df_dict['Age'].plot(kind='line')
plt.title('Age Trend')
plt.xlabel('Index')
plt.ylabel('Age')
plt.show()
4. Additional Resources
For a more in-depth understanding and practical examples, you can explore the
following resources:
Python Plotting Tutorial with Matplotlib and Pandas: A comprehensive
tutorial covering line graphs, histograms, pie charts, and box plots using real-
world data. Watch the tutorial
Data Visualization with Matplotlib: An article that provides examples and
explanations on creating various plots using Matplotlib. Read the article
Data Visualization using Matplotlib in Python: A guide that covers the
basics of data visualization using Matplotlib. Explore the guide