Python Notes
Python Notes
Definition:
A string is a sequence of characters enclosed in single, double, or triple quotes.
Sample Program:
🔢 2. Lambda Functions
Definition:
Lambda functions are small anonymous functions defined with the lambda
keyword.
Syntax:
Sample Program:
Lists:
Tuples:
Dictionaries:
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
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}")
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"
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
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:
Sample Program:
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:
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
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.")
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!")
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']
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
# 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')")
1. Creating DataFrames
import pandas as pd
c. From a Dictionary
d. From a List
2. Operations on DataFrames
Selecting Columns:
Filtering Rows:
Dropping a Column:
# Drop a column
df_dict = df_dict.drop('Country', axis=1)
print(df_dict)
a. Bar Graph
# 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: