Python
Python
LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Python Programming
Material
OUR PARTNERS &
CERTIFICATIONS
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
CHAPTER -1
Introduction to Python
What is Python?
2. Interpreted Language
3. Dynamically Typed
5. Cross-Platform Compatibility
Applications of Python
program:
python
print("Hello, Python!")
python :
CHAPTER -2
Python Basics - Syntax and Variables
Example:
# Print a message
print("Hello, Python!") # Output: Hello, Python!
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
1. Variables
Variables store data and are dynamically typed (no need for
explicit declaration).
Assigned using = (e.g., x = 10).
2. Data Types
Example Code:
x = 10 # Integer
y = 3.14 # Float
name = "Python" # String
is_active = True # Boolean
print(greet("Santhosh"))
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
C Programming - Basics
1. Features of C
1. Fast & Efficient – Low-level memory access and minimal
runtime overhead.
2.Portable & Cross-Platform – Can run on various operating
systems.
3. Structured Programming – Supports functions and modular
code.
4.Rich Library Support – Standard libraries for I/O, math, and
more.
5.Foundation for Other Languages – Influenced C++, Java, and
Python.
2. Basic Syntax in C
int main() {
printf("Hello, C!"); // Print statement
return 0; // Exit the program
}
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
4. Type Casting in C
Explicit conversion using type casting:
int a = 10;
float b = (float)a; // Converts int to float
printf("%f", b); // Output: 10.000000
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Example:
#include <stdio.h>
int main() {
printf("Hello, C Programming!\n"); // \n is used for a
new line
return 0;
}
Output:
Hello, C Programming!
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Chapter 3
Operators and Expressions
Arithmetic Operators
Arithmetic Operators in C
Arithmetic operators in C are used to perform mathematical
operations like addition, subtraction, multiplication, etc.
Example in Python
a = 10
b=3
print("Addition:", a + b) # 13
print("Subtraction:", a - b) # 7
print("Multiplication:", a * b) # 30
print("Division:", a / b) # 3.3333
print("Modulus:", a % b) #1
print("Exponentiation:", a ** b) # 1000
print("Floor Division:", a // b) # 3
Comparison Operators
Comparison operators are used to compare two values and return a boolean
result (True or False).
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Examples in Python
age = 18
if age >= 18:
print("You can vote.")
else:
print("You cannot vote.")
4.Using in Loops
num = 1
while num <= 5:
print(num)
num += 1
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Logical Operators
Logical operators are used to combine multiple conditions and
return a Boolean value (True or False)
age = 20
has_voter_id = True
if rainy or umbrella:
print("You are prepared for rain.") # Output: You are prepared for
rain.
else:
print("You might get wet!")
if not is_sunny:
print("It's not a sunny day.") # Output: It's not a sunny day.
Usage in Loops
num = 5
while not (num == 0): # Loop runs until num becomes 0
print(num)
num -= 1
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Assignment Operators
Assignment operators are used to assign values to variables. They can
also perform operations like addition, subtraction, multiplication, etc.,
while assigning values.
x = 10
print(x) # Output: 10
Real-World Example
user_roles = ["admin", "editor", "viewer"]
if "admin" in user_roles:
print("Access granted!")
else:
print("Access denied.")
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Chapter 4
Control Flow - Decision Making
1.if Statement
The if statement executes a block of code only if the condition is
True.
age = 18
if age >= 18:
print("You are eligible to vote.")
Output:
You are eligible to vote.
2.if-else Statement
The else block runs if the if condition is False.
age = 16
if age >= 18:
print("You can vote.")
else:
print("You cannot vote yet.")
Output:
You cannot vote yet.
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
3.if-elif-else Statement
1.elif (short for "else if") allows checking multiple conditions.
2.The first condition that evaluates to True gets executed, and the
rest are ignored.
marks = 85
4.Nested if Statements
You can place an if inside another if to check multiple conditions.
age = 20
has_voter_id = True
Output:
You can vote.
Real-World Example
username = "admin"
password = "1234"
Nested Conditionals
A nested conditional means placing one if statement inside another.
This allows for checking multiple conditions where one condition
depends on another.
Syntax of Nested Conditionals
if condition1:
if condition2:
# Code block executes if both conditions are True
else:
# Code block executes if condition1 is True but condition2 is False
else:
# Code block executes if condition1 is False
Example 1: Checking Age and ID for Voting
age = 20
has_voter_id = True
if x != 0 and y / x > 2:
print("Condition met!")
else:
print("Short-circuited: Division by zero avoided!")
Output:
Short-circuited: Division by zero avoided!
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Chapter 5
Loops and Iterations
1.for Loop
A for loop is used to iterate over a sequence (list, tuple, string,
dictionary, range, etc.) and execute a block of code multiple times.
1.Basic Syntax
for variable in sequence:
# Code to execute in each iteration
2.Looping Through a List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
3.Using range() in a for Loop
The range(start, stop, step) function generates a sequence of
numbers.
for i in range(1, 6): # Loops from 1 to 5
print(i)
4.Looping Through a String
for letter in "Python":
print(letter)
5.Looping Through a Dictionary
student = {"name": "Hari", "age": 20, "grade": "A"}
for key, value in student.items():
print(key, ":", value)
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
2.while Loop
A while loop repeats a block of code as long as a given condition is
True.
1.Basic Syntax
while condition:
# Code to execute
2.Example: Print Numbers from 1 to 5
i=1
while i <= 5:
print(i)
i += 1 # Increment to avoid infinite loop
3.Infinite Loop (Be Careful!)
while True: # Infinite loop
print("This will run forever!")
4.Using break in while Loop
i=1
while i <= 10:
if i == 5:
break # Stops when i is 5
print(i)
i += 1
5.Using continue in while Loop
i=0
while i < 5:
i += 1
if i == 3:
continue # Skips printing 3
print(i)
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Chapter 6
Functions and Modules
greet("Santhosh")
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
result = add_numbers(5, 3)
print("Sum:", result)
result = square(4)
print("Square:", result)
result = square(4)
print("Square:", result)
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
4.Lambda Functions
A lambda function (also called an anonymous function) is a small,
one-line function that does not require a name. It is used for short,
simple operations where defining a full function is unnecessary.
Chapter 7
Data Structures - Lists and Tuples
1.Lists: Creation, Indexing, Slicing
A list in Python is a mutable, ordered collection that can store
different data types like integers, strings, and even other lists.
3.List Comprehensions
List comprehension is a concise and efficient way to create lists in
Python. It helps write clean, readable, and faster code.
🔹 Basic Syntax
new_list = [expression for item in iterable if condition]
expression → What to do with each item
iterable → Any iterable (list, tuple, range, etc.)
condition (optional) → Filter items based on a condition
Examples:
1. Creating a list from a range
squares = [x**2 for x in range(1, 6)]
print(squares) # Output: [1, 4, 9, 16, 25]
2. Filtering even numbers
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # Output: [0, 2, 4, 6, 8]
3. Applying a function to each element
words = ["hello", "world", "python"]
upper_words = [word.upper() for word in words]
print(upper_words) # Output: ['HELLO', 'WORLD', 'PYTHON']
4. Using if-else in list comprehension
labels = ["Even" if x % 2 == 0 else "Odd" for x in range(5)]
print(labels) # Output: ['Even', 'Odd', 'Even', 'Odd', 'Even']
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Accessing Elements
Tuples support indexing and slicing like lists.
t = (10, 20, 30, 40, 50)
Chapter 8:
Dictionaries and Sets
1. Using {}
student = {"name": "Santhosh", "age": 22, "course": "Python"}
print(student)
# Output: {'name': 'Santhosh', 'age': 22, 'course': 'Python'}
2. Using dict()
person = dict(name="Chinni", city="Hyderabad", age=21)
print(person)
# Output: {'name': 'Chinni', 'city': 'Hyderabad', 'age': 21}
Modifying Dictionary
1. Creating a Set
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A) # Output: {1, 2, 3, 4, 5}
print(B) # Output: {4, 5, 6, 7, 8}
2. Union (| or union())
Combines all elements from both sets without duplicates.
C = A | B # Using `|` operator
print(C) # Output: {1, 2, 3, 4, 5, 6, 7, 8}
D = A.union(B) # Using `union()` method
print(D) # Output: {1, 2, 3, 4, 5, 6, 7, 8}
4. Difference (- or difference())
Returns elements that are only in the first set, removing common elements.
C = A - B # Using `-` operator
print(C) # Output: {1, 2, 3}
D = A.difference(B) # Using `difference()` method
print(D) # Output: {1, 2, 3}
E=B-A
print(E) # Output: {6, 7, 8} (elements only in B)
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
5. Conclusion
Use a dictionary (dict) when you need to map keys to values and perform fast
lookups.
Use a set (set) when you need a collection of unique items or want to perform
set operations efficiently.
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Chapter 9:
Working with Strings
custom_text = "---Hello---"
print(custom_text.strip("-")) # Output: "Hello"
Related Methods:
lstrip() → Removes leading (left) spaces/characters.
rstrip() → Removes trailing (right) spaces/characters.
txt = " Hello "
print(txt.lstrip()) # Output: "Hello "
print(txt.rstrip()) # Output: " Hello"
Slicing a String
print(text[0:5]) # Hello
print(text[:5]) # Hello
print(text[7:]) # Python!
print(text[-7:-1]) # Python
2. Modifying Strings
Converting Case
text = "Python Programming"
print(text.upper()) # PYTHON PROGRAMMING
print(text.lower()) # python programming
print(text.title()) # Python Programming
print(text.capitalize()) # Python programming
print(text.swapcase()) # pYTHON pROGRAMMING
Stripping Whitespace
text = " Hello, Python! "
print(text.strip()) # "Hello, Python!"
print(text.lstrip()) # "Hello, Python! "
print(text.rstrip()) # " Hello, Python!"
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
5. Formatting Strings
Using f-strings
name = "Santhosh"
age = 21
print(f"My name is {name} and I am {age} years old.")
6. Reversing a String
text = "Python"
print(text[::-1]) # nohtyP
Chapter 10
File Handling
1.Reading and Writing Files (open(), read(), write())
In Python, file handling is done using built-in functions like open(), read(), and
write(). Here’s how you can use them:
Modes available:
"r" → Read mode (default, file must exist)
"w" → Write mode (creates a new file or overwrites an existing file)
"a" → Append mode (adds content to an existing file)
"r+" → Read and write
"w+" → Write and read (overwrites)
"a+" → Append and read
Chapter 11
Exception Handling
1.Try, except, finally, and else
In Python, the try, except, finally, and else blocks are used for handling
exceptions. Here’s how each of them works:
1. try Block
The code inside the try block is executed first.
If an exception occurs, it is caught by the except block.
If no exception occurs, the else block (if present) is executed.
2. except Block
This block is executed if an exception occurs inside the try block.
Multiple except blocks can handle different exceptions.
3. else Block (Optional)
If no exception occurs in the try block, the else block is executed.
It is used when you want to run some code only if no errors occur.
4. finally Block (Optional)
The finally block is always executed, regardless of whether an exception
occurs or not.
It is commonly used for cleanup tasks like closing files or database
connections.
Example:
# Define a custom exception
class CustomError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
Output:
Caught an error: Value cannot be negative
Chapter 12
Object-Oriented Programming (OOP)
Example:
# Define a custom exception
class CustomError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
Instance Variables
These are variables that belong to an instance of a class.
They are defined inside the constructor (__init__) using self.
Example:
class Student:
def __init__(self, name, age, course):
self.name = name # Instance variable
self.age = age # Instance variable
self.course = course # Instance variable
def display_info(self):
print(f"Name: {self.name}, Age: {self.age}, Course: {self.course}")
1. Inheritance
Inheritance allows a child class (subclass) to acquire properties and behaviors
(methods) from a parent class (superclass). This promotes code reuse and
hierarchical relationships between classes.
Key Points:
The child class inherits attributes and methods from the parent class.
The child class can extend or override methods from the parent class.
Helps in implementing code reusability and modular programming.
# Parent class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "Animal makes a sound"
# Child class inheriting from Animal
class Dog(Animal):
def speak(self):
return "Woof! Woof!"
# Child class inheriting from Animal
class Cat(Animal):
def speak(self):
return "Meow! Meow!"
# Creating objects
dog = Dog("Buddy")
cat = Cat("Kitty")
print(dog.name, "says:", dog.speak()) # Buddy says: Woof! Woof!
print(cat.name, "says:", cat.speak()) # Kitty says: Meow! Meow!
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Types of Inheritance:
1. Single Inheritance – One child class inherits from one parent class.
2. Multiple Inheritance – A child class inherits from multiple parent classes.
3. Multilevel Inheritance – A class inherits from another class, which in turn
inherits from another class.
4. Hierarchical Inheritance – Multiple child classes inherit from the same parent
class.
5. Hybrid Inheritance – A combination of two or more types of inheritance.
2. Polymorphism
Polymorphism allows objects of different classes to be treated as objects of a
common superclass. It enables methods to have the same name but different
behaviors in different classes.
Key Points:
A single method can be implemented in different ways in different classes.
Helps in flexibility and scalability of the code.
class Sparrow(Bird):
def fly(self):
return "Sparrows can fly fast"
class Penguin(Bird):
def fly(self):
return "Penguins cannot fly"
# Creating objects
sparrow = Sparrow()
penguin = Penguin()
print(sparrow.fly()) # Sparrows can fly fast
print(penguin.fly()) # Penguins cannot fly
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Types of Polymorphism:
1. Method Overloading – Defining multiple methods with the same name but
different parameters (Not directly supported in Python).
2. Method Overriding – Redefining a parent class method in the child class.
3. Operator Overloading – Using operators (+, -, *, etc.) with user-defined
meanings.
num1 = Number(10)
num2 = Number(20)
def get_balance(self):
return self.__balance # Getter method
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
# Usage
account = BankAccount(12345, 5000)
account.deposit(2000)
account.withdraw(3000)
print("Balance:", account.get_balance())
Abstraction
Abstraction is the process of hiding implementation details and only exposing the
essential features of an object. It helps simplify complex systems by providing a
clear interface.
🔹 Key Features of Abstraction:
Hides unnecessary details from the user.
Achieved using abstract classes and interfaces.
Improves code reusability and scalability.
Chapter 13:
Working with Modules and Packages
import sys
print(sys.version) # Python version
print(sys.platform) # OS platform
sys.exit() # Exit the program
import mymodule
mymodule = importlib.import_module("mymodule")
print(mymodule.greet("Santhosh"))
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
2. Upgrading a Library
To update a package:
pip install --upgrade library_name
3. Uninstalling a Library
If you no longer need a library, uninstall it using:
import requests
response = requests.get("https://api.github.com")
print(response.status_code)
Activate it:
Windows: myenv\Scripts\activate
Mac/Linux: source myenv/bin/activate
Now, you can install packages inside this isolated environment.
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Chapter 14
Working with Databases (SQLite & MySQL)
1.Introduction to Databases
Introduction to Databases
A database is an organized collection of data that allows efficient storage,
retrieval, and management of information. It serves as a backbone for
applications and systems that require structured data handling, such as websites,
banking systems, and enterprise applications.
Why Use Databases?
1. Efficient Data Management – Stores and organizes large volumes of data
efficiently.
2. Data Integrity & Consistency – Ensures that stored data remains accurate and
reliable.
3. Security – Provides authentication and authorization to protect sensitive
information.
4. Concurrency Control – Supports multiple users accessing data
simultaneously.
5. Data Recovery – Allows data backup and restoration in case of failure.
Types of Databases
4.Time-Series Databases
Specially designed for tracking changes over time.
Examples: InfluxDB, TimescaleDB.
2.Connecting to SQLite/MySQL
Connecting to SQLite and MySQL in Python
1. Connecting to SQLite
SQLite is a lightweight database that doesn’t require a separate server. You can
use the sqlite3 module in Python.
Steps to Connect to SQLite:
import sqlite3
# Connect to database (or create it if it doesn’t exist)
conn = sqlite3.connect('my_database.db')
# Create a cursor object to execute SQL commands
cursor = conn.cursor()
# Example: Creating a table
cursor.execute('''CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
2. Connecting to MySQL
To connect to MySQL, you need the mysql-connector-python package. Install it if
you haven’t:
cursor = conn.cursor()
# Create a table
cursor.execute('''CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT
PRIMARY KEY, name VARCHAR(255), age INT)''')
# Insert data
cursor.execute("INSERT INTO users (name, age) VALUES (%s, %s)", ("Bob", 30))
# Commit and close
conn.commit()
conn.close()
Chapter 15
Web Scraping with Python
1.Introduction to Web Scraping
Introduction to Web Scraping
Web scraping is the process of extracting data from websites using automated
scripts or programs. It enables users to collect, analyze, and store data from the
web efficiently. Web scraping is widely used in industries such as e-commerce,
finance, research, and marketing.
Why Use Web Scraping?
1. Data Collection – Automates the retrieval of large volumes of data.
2. Market Research – Gathers competitor prices, product details, and customer
reviews.
3. Lead Generation – Extracts contact information from business directories.
4. Sentiment Analysis – Collects user feedback from social media and reviews.
5. News Aggregation – Compiles articles from multiple sources.
6. Passing Parameters
For URLs that require query parameters:
params = {"q": "Python", "sort": "recent"}
response = requests.get("https://example.com/search", params=params)
print(response.url) # Shows the final URL with parameters
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Basic Usage
1. Import Required Libraries
from bs4 import BeautifulSoup
import requests
2. Finding by ID
element = soup.find(id="main-content")
print(element)
first_link = soup.find("a")
print(first_link["href"]) # Extracts the href attribute
url = "https://example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
df = pd.DataFrame(data)
df.to_csv("output.csv", index=False)
Save to a Database:
cursor.execute("INSERT INTO users (name, age) VALUES (%s, %s)", ("John", 30))
connection.commit()
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Chapter 16
Data Visualization with Matplotlib and Seaborn
1.Introduction to matplotlib
Introduction to Matplotlib
Matplotlib is a popular Python library used for data visualization. It provides a
wide variety of plotting options to create high-quality static, animated, and
interactive graphs.
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 50]
Explanation:
Line Plot: Uses plot() with markers and a line connecting the points.
Bar Plot: Uses bar() to create vertical bars.
Scatter Plot: Uses scatter() to plot individual points.
# Sample Data
data = pd.DataFrame({
'A': [1, 2, 3, 4, 5],
'B': [2, 3, 4, 5, 6],
'C': [5, 4, 3, 2, 1]
})
# Regression plot
sns.lmplot(x="total_bill", y="tip", data=tips, hue="sex", markers=["o", "s"])
plt.title("Regression Plot of Total Bill vs Tip")
plt.show()
plt.tight_layout()
plt.show()
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
Chapter 17
Machine Learning Basics
# Load dataset
iris = datasets.load_iris()
X, y = iris.data, iris.target
# Make predictions
y_pred = model.predict(X_test)
# Evaluate performance
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy:.2f}")
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
# Load dataset
boston = datasets.load_boston()
X, y = boston.data, boston.target
# Split dataset
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42)
# Train model
regressor = LinearRegression()
regressor.fit(X_train, y_train)
# Predict
y_pred = regressor.predict(X_test)
# Evaluate
mse = mean_squared_error(y_test, y_pred)
print(f"Mean Squared Error: {mse:.2f}")
1. Supervised Learning
Supervised learning is a type of machine learning where the model is trained
using labeled data. This means the input data has corresponding output labels,
and the model learns the relationship between them.
✅ Key Features:
Uses labeled data (input-output pairs).
The goal is to map inputs to correct outputs.
Requires human intervention for data labeling.
Common algorithms: Linear Regression, Logistic Regression, Decision
Trees, Random Forest, Support Vector Machines (SVM), Neural Networks.
✅ Examples:
Spam detection: Classify emails as "spam" or "not spam."
Fraud detection: Identify fraudulent transactions in banking.
Medical diagnosis: Predict disease based on patient data.
2. Unsupervised Learning
Unsupervised learning is a type of machine learning where the model is trained
on unlabeled data and finds hidden patterns without explicit guidance.
✅ Key Features:
Uses unlabeled data (no predefined output).
The goal is to discover hidden patterns and relationships in data.
No human intervention is needed for labeling.
Common algorithms: K-Means Clustering, Hierarchical Clustering, Principal
Component Analysis (PCA), Autoencoders, DBSCAN.
✅ Examples:
Customer segmentation: Grouping customers based on purchasing
behavior.
Anomaly detection: Identifying unusual network activity for cybersecurity.
Recommendation systems: Suggesting similar movies or products (e.g.,
Netflix, Amazon).
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
# Load dataset
data = load_iris()
X_train, X_test, y_train, y_test = train_test_split(data.data, data.target,
test_size=0.2, random_state=42)
# Train model
model = LogisticRegression(max_iter=200)
model.fit(X_train, y_train)
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
# Load dataset
data = load_iris()
X_train, X_test, y_train, y_test = train_test_split(data.data, data.target,
test_size=0.2, random_state=42)
# Train model
model = LogisticRegression(max_iter=200)
model.fit(X_train, y_train)
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
3. Model Evaluation
Evaluate the trained model using various metrics:
Accuracy: (Correct Predictions) / (Total Predictions)
Precision, Recall, F1-score (for classification tasks)
Mean Squared Error (MSE), R² Score (for regression tasks)
Example:
from sklearn.metrics import accuracy_score
# Evaluate model
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy:.2f}")
Chapter 18
Introduction to Web Development with Flask/Django
1. Install Flask
pip install flask
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, Flask!"
if __name__ == '__main__':
app.run(debug=True)
Flask (Python)
Flask uses the render_template() function to render HTML templates stored in
the templates/ folder.
Setting up Routes
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html') # Renders index.html
@app.route('/about')
def about():
return render_template('about.html') # Renders about.html
if __name__ == '__main__':
app.run(debug=True)
Express.js (Node.js)
Express uses the res.render() function along with Pug, EJS, or Handlebars as
the templating engine.
Setting up Express Routes
const express = require('express');
const app = express();
app.listen(3000, () => {
console.log("Server running on port 3000");
});
Django (Python)
Django follows the MTV (Model-Template-View) pattern.
Setting up Django Routes
In views.py:
from django.shortcuts import render
def home(request):
return render(request, 'index.html')
def about(request):
return render(request, 'about.html')
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
1. Creating a Form
A form is used to collect user input. This is typically done using HTML.
Example (HTML Form):
<form action="process.php" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<button type="submit">Submit</button>
</form>
// Database connection
$conn = new mysqli("localhost", "root", "", "mydatabase");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
$conn->close();
}
?>
$conn->close();
Chapter 19
Testing and Debugging in Python
1. Importing unittest
The unittest module is included in Python’s standard library, so no extra
installation is needed.
import unittest
class TestMathOperations(unittest.TestCase):
def test_add(self):
self.assertEqual(add(3, 5), 8)
self.assertEqual(add(-1, 1), 0)
self.assertEqual(add(0, 0), 0)
def test_subtract(self):
self.assertEqual(subtract(10, 5), 5)
self.assertEqual(subtract(-1, -1), 0)
self.assertEqual(subtract(0, 5), -5)
def test_multiply(self):
self.assertEqual(multiply(2, 3), 6)
self.assertEqual(multiply(-2, 3), -6)
self.assertEqual(multiply(0, 5), 0)
def test_divide(self):
self.assertEqual(divide(10, 2), 5)
self.assertEqual(divide(-10, 2), -5)
self.assertRaises(ValueError, divide, 10, 0)
if __name__ == '__main__':
unittest.main()
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
2.Navigation Commands
c (continue) → Resume execution until the next breakpoint.
n (next) → Execute the next line of code.
s (step) → Step into function calls.
q (quit) → Exit the debugger.
r (return) → Run until the function returns.
3.Variable Inspection
p var → Print the value of var.
pp var → Pretty-print var (useful for dictionaries/lists).
whos → List all variables in scope.
4.Breakpoints
b 10 → Set a breakpoint at line 10.
b my_function → Break at the start of my_function.
cl → Clear all breakpoints.
5.Stack Navigation
l → List source code around the current line.
w → Show the current stack frame.
up / down → Move up/down the call stack.
Example Debugging Session
def add(a, b):
result = a + b
return result
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
def main():
x, y = 5, 10
import pdb; pdb.set_trace() # Breakpoint
sum_result = add(x, y)
print(f"Sum: {sum_result}")
if __name__ == "__main__":
main()
5. KeyError: 'key'
Cause: Trying to access a key in a dictionary that doesn't exist.
data = {"name": "Alice"}
print(data["age"]) # 'age' key is missing
Fix:
print(data.get("age", "Key not found")) # Use .get() method with default value
Chapter 20
Advanced Python Concepts
1.Decorators and Generators
Decorators and Generators in Python
Both decorators and generators are advanced Python features that help in
making code more readable, efficient, and reusable. Let's go through each
concept in detail.
1. Generators
Generators are special types of iterators that allow you to iterate over data
without storing the entire dataset in memory. They are defined using the yield
keyword.
Why Use Generators?
Memory Efficient: They generate values on the fly instead of storing
everything in memory.
Lazy Evaluation: They compute values as needed, making them useful for
large datasets.
State Retention: Unlike normal functions, generators retain their state
between function calls.
gen = count_up_to(5)
print(next(gen)) # Output: 1
print(next(gen)) # Output: 2
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
2. Decorators
A decorator is a function that takes another function as input and extends its
functionality without modifying its actual code.
Why Use Decorators?
Code Reusability: Helps avoid redundant code.
Separation of Concerns: Keeps logic separate from enhancements.
Useful for Logging, Authorization, Timing Functions, etc.
say_hello()
Output:
Wrapper executed before say_hello
Hello!
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
def print_numbers():
for i in range(5):
print(i)
# Starting threads
thread1.start()
thread2.start()
# Waiting for threads to finish
thread1.join()
thread2.join()
print("Threads finished execution")
2. Parallel Processing
Parallel processing involves dividing a task into smaller subtasks and executing
them simultaneously on multiple CPU cores or even multiple machines. It is
primarily used for CPU-bound tasks.
Key Characteristics:
True parallel execution on multi-core processors.
Independent processes (not just threads) with separate memory spaces.
Best suited for CPU-intensive tasks like scientific computations, AI model
training, and large data processing.
Example Use Cases:
Machine learning model training
Large-scale data processing (Pandas, NumPy)
Scientific simulations
Example
(Python Multiprocessing)
import multiprocessing
def square(n):
return n * n
if __name__ == "__main__":
numbers = [1, 2, 3, 4, 5]
with multiprocessing.Pool(processes=2) as pool:
results = pool.map(square, numbers)
print("Squared numbers:", results)
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana
On macOS/Linux:
source myenv/bin/activate
3. Installing Packages
Once the virtual environment is activated, you can install packages using pip:
pip install package_name
For example:
pip install numpy pandas
Chapter 21
Python Project Ideas and Best Practices
def method_one(self):
pass
def method_two(self):
pass
CODTECH IT SOLUTIONS PVT.LTD
IT SERVICES & IT CONSULTING
8-7-7/2, Plot NO.51, Opp: Naveena School, Hasthinapuram Central, Hyderabad , 500 079. Telangana