Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
6 views33 pages

TUPLES and SETS and Further Oxfd

python

Uploaded by

oxfordmeera
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)
6 views33 pages

TUPLES and SETS and Further Oxfd

python

Uploaded by

oxfordmeera
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/ 33

TUPLES and SETS IN PYTHON

Tuples and sets are built-in data structures in Python used to store collections of
items. They differ in their characteristics and use cases.

Tuples
Tuples are ordered, immutable sequences of items. They are defined using
parentheses () and can contain elements of different data types.
Python
my_tuple = (1, "hello", 3.14)

Once a tuple is created, its elements cannot be modified, added, or


removed. However, it is possible to access elements by their index.
Python
print(my_tuple[0]) # Output: 1

Sets
Sets are unordered collections of unique elements. They are defined using curly
braces { } or the set() constructor. Sets do not allow duplicate values, and elements
are not stored in any particular order.
Python
my_set = {1, 2, 2, 3}
print(my_set) # Output: {1, 2, 3}

Sets are useful for removing duplicates from a sequence and performing operations
like union, intersection, and difference.
Python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.union(set2)) # Output: {1, 2, 3, 4, 5}

Key Differences
Feature Tuple Set

Ordered Yes No

Mutable No Yes

Duplicates Allowed Not allowed

Defined by () {} or set()

Use Cases
 Tuples are suitable for storing fixed collections of items that should not be modified, such as
coordinates, database records, or function arguments.
 Sets are useful for tasks involving membership testing, removing duplicates, and performing
set operations.
Sets in Python

Sets are used to store multiple items in a single variable.

Set is one of 4 built-in data types in Python used to store collections of data, the
other 3 are List, Tuple, and Dictionary, all with different qualities and usage.

A set is a collection which is unordered, unchangeable*, and unindexed.

Sets are written with curly brackets.

Example

Create a Set:

thisset = {"apple", "banana", "cherry"}


print(thisset)
Set Items
Set items are unordered, unchangeable, and do not allow duplicate values.

Unordered
Unordered means that the items in a set do not have a defined order.

Set items can appear in a different order every time you use them, and cannot be
referred to by index or key.

Unchangeable

Set items are unchangeable, meaning that we cannot change the items after the
set has been created.
Once a set is created, you cannot change its items, but you can remove
items and add new items.

Duplicates Not Allowed


Sets cannot have two items with the same value.

Example
Duplicate values will be ignored:
thisset = {"apple", "banana", "cherry", "apple"}

print(thisset)

The values True and 1 are considered the same value in sets, and are treated as
duplicates:
Example

True and 1 is considered the same value:

thisset = {"apple", "banana", "cherry", True, 1, 2}

print(thisset)

The values False and 0 are considered the same value in sets, and are
treated as duplicates:

Example

False and 0 is considered the same value:

thisset = {"apple", "banana", "cherry", False, True, 0}

print(thisset)
Python Set Operations (Union, Intersection, Difference and Symmetric
Difference)
Union of sets
The union of two sets combines all unique elements from both sets.
Syntax:

set1 | set2 # Using the ‘|’ operator


set1.union(set2) # Using the union() method

Example:
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

# Using '|' operator


res1 = A | B
print("using '|':", res1)

# Using union() method


res2 = A.union(B)
print("using union():",res2)

Output
using '|': {1, 2, 3, 4, 5, 6}
using union(): {1, 2, 3, 4, 5, 6}
Note : | operator and union() method both return a new set containing all
unique elements from both sets

Intersection of sets
The intersection of two sets includes only the common elements present in
both sets.
Syntax:

set1 & set2 # Using the ‘&’ operator


set1.intersection(set2) # Using the intersection() method

Example:
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

# Using '&' operator


res1 = A & B
print("using '&':",res1)

# Using intersection() method


res2 = A.intersection(B)
print("using intersection():",res2)

Output
using '&': {3, 4}
using intersection(): {3, 4}

Note : & operator and intersection() method return a new set containing
only elements that appear in both sets.

Difference of sets
The difference between two sets includes elements present in the first set but
not in the second.
Syntax:

set1 – set2 # Using the ‘-‘ operator


set1.difference(set2) # Using the difference() method

Example :
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

# Using '-' operator


res1 = A - B
print("using '-':", res1)
# Using difference() method
res2 = A.difference(B)
print("using difference():", res2)

Note : - operator and difference() method return a new set containing


elements of A that are not in B

Output
using '-': {1, 2}
using difference(): {1, 2}

Symmetric Difference of sets :


The symmetric difference of two sets includes elements that are in either set
but not in both.
Syntax:

set1 ^ set2 # Using the ‘^’ operator


set1.symmetric_difference(set2) # Using the symmetric_difference() method

Example:
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

# Using '^' operator


res1 = A ^ B
print("using '^':", res1)

# Using symmetric_difference() method


res2 = A.symmetric_difference(B)
print("using symmetric_difference():", res2)

Output
using '^': {1, 2, 5, 6}
using symmetric_difference(): {1, 2, 5, 6}

Note : ^ operator and symmetric_difference() method return a new set


containing elements that are in either A or B but not in both.

Python Set Methods

 add(): Adds a given element to a set


 clear(): Removes all elements from the set
 discard(): Removes the element from the set
 pop(): Returns and removes a random element from the set
 remove(): Removes the element from the set

Example: Adding and removing elements from the Set.

# set of letters
s = {'g', 'e', 'k', 's'}

# adding 'f'
s.add('f')
print('Set after updating:', s)

# Discarding element from the set


s.discard('g')
print('\nSet after updating:', s)

# Removing element from the set


s.remove('e')
print('\nSet after updating:', s)

# Popping elements from the set


print('\nPopped element', s.pop())
print('Set after updating:', s)

s.clear()
print('\nSet after updating:', s)

Output
Set after updating: {'g', 'k', 's', 'e', 'f'}
Set after updating: {'k', 's', 'e', 'f'}
Set after updating: {'k', 's', 'f'}
Popped element k
Set after updating: {'s', 'f'}
Set after updating: set()

Table of Python Set Methods

Functions Name Description

add() Adds a given element to a set

clear() Removes all elements from the set


Functions Name Description

copy() Returns a shallow copy of the set

difference() Returns a set that is the difference between two sets

Updates the existing caller set with the difference


difference_update()
between two sets

discard() Removes the element from the set

frozenset() Return an immutable frozenset object

intersection() Returns a set that has the intersection of all sets

Updates the existing caller set with the intersection


intersection_update()
of sets

isdisjoint() Checks whether the sets are disjoint or not

Returns True if all elements of a set A are present in


issubset()
another set B

Returns True if all elements of a set A occupies set


issuperset()
B

pop() Returns and removes a random element from the set

remove() Removes the element from the set

Returns a set which is the symmetric difference


symmetric_difference()
between the two sets

symmetric_difference_update( Updates the existing caller set with the symmetric


) difference of sets

union() Returns a set that has the union of all sets

update() Adds elements to the set


File Handling in Python:

1. File Types
2. Operations on Files (Create, Open, Read, Write, Close)
3. File Names and Paths
4. Format Operator (%)

Python makes it easy to work with files. Whether you're reading data from a
text file or writing to a log file, file handling is a key part of any application.

1️⃣ File Types

Files in Python are mainly classified into two types:

1. Text Files

 Store data in human-readable format.


 Examples: .txt, .csv, .json, .log
 Data is organized as lines of text.
 Can be opened in text mode ('t' - default).

2. Binary Files

 Store data in binary (non-human-readable) format.


 Examples: .jpg, .png, .pdf, .exe
 Data is accessed in binary mode ('b').

🔸 Key Differences:

Feature Text File Binary File


Readability Human-readable Machine-readable (0s & 1s)
Mode 't' (default) 'b'
Example "data.txt" "image.jpg"
Use Case Logs, configs, reports Images, executables, videos

2️⃣ Operations on Files

Python provides a built-in function open() to work with files.


✅ A. Creating a File

To create a new file or overwrite an existing one:

file = open("myfile.txt", "w") # 'w' creates if not exists, or overwrites


file.write("This is a new file.")
file.close()

To create a file only if it doesn't exist:

file = open("newfile.txt", "x") # 'x' raises error if file exists


✅ B. Opening a File

Syntax:

file = open("filename", "mode")

Common Modes:

Mode Description
'r' Read (default), file must exist
'w' Write, creates file or truncates
'a' Append, creates file if not exists
'x' Exclusive creation, error if exists
'b' Binary mode (e.g., 'rb', 'wb')
't' Text mode (default)
'+' Read and write

Example:

file = open("example.txt", "r") # Open for reading

✅ C. Reading from a File

Methods:

file.read() # Reads entire file


file.readline() # Reads one line
file.readlines() # Reads all lines into a list

Example:

file = open("data.txt", "r")


content = file.read()
print(content)
file.close()

✅ D. Writing to a File
file.write("Text to write\n") # Writes a string
file.writelines(["Line1\n", "Line2\n"]) # Writes list of strings

Example:

file = open("output.txt", "w")


file.write("Hello, Python!\n")
file.writelines(["Line1\n", "Line2\n"])
file.close()

✅ E. Closing a File

Files should be closed after operations to:

 Free system resources


 Save changes (especially in write/append mode)

file.close()

Or use with (auto-closes file):

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


print(file.read()) # File closes automatically

3️⃣ File Names and Paths


🔹 File Names:

 Must include the extension (e.g., notes.txt)


 Case-sensitive on some OS (like Linux)

🔹 File Paths:

Relative Path:

 Relative to current working directory.

open("data/info.txt", "r")

Absolute Path:

 Full path from root directory.


open("/home/user/documents/info.txt", "r")
🔹 Using os Module for Path Handling:
import os

# Absolute path
abs_path = os.path.abspath("file.txt")
print(abs_path)

# Check if file exists


print(os.path.exists("file.txt"))

4️⃣ Format Operator (%)

The % operator allows formatting strings by inserting variables into


placeholders.

🔹 Syntax:
"format string" % (values)

🔹 Common Format Specifiers:


Specifier Meaning
%s String
%d Integer
%f Float
%.2f Float (2 decimals)
🔹 Example:
name = "John"
age = 25
print("Name: %s, Age: %d" % (name, age))
🔹 Float Precision:
pi = 3.14159
print("Value of pi: %.2f" % pi) # Output: 3.14

🔹 Better Alternatives (Recommended):

1. .format() Method

print("Name: {}, Age: {}".format(name, age))

2. f-Strings (Python 3.6+)

print(f"Name: {name}, Age: {age}")


✅ Summary Table
Operation Method/Function
3Create File open("file.txt", "w")
Read File .read(), .readline()
Write File .write(), .writelines()
Close File .close()
Use Path os.path.abspath()
String Format %s, %d, %f

Object Oriented Programming in python:

Python is an object-oriented programming language, which means that it


is based on principle of OOP concept. The entities used within a Python
program is an object of one or another class. For instance, numbers, strings,
lists, dictionaries, and other similar entities of a program are objects of the
corresponding built-in class.
In Python, a class named Object is the base or parent class for all the
classes, built-in as well as user defined.
Key components of OOP in Python include:
 Classes:
User-defined blueprints for creating objects. They define the type of data an
object can hold and the actions it can perform.
 Objects:
Instances of classes. They are concrete entities that possess the attributes
and behaviours defined by their class.

 Methods:
Functions defined within a class that operate on the object's data. They
define the actions an object can perform.
 Constructors:
Special methods (typically named __init__) that are automatically called
when an object is created. They initialize the object's attributes.

Python Class
A class is a collection of objects. Classes are blueprints for creating
objects. A class defines a set of attributes and methods that the created
objects (instances) can have.
Some points on Python class:
 Classes are created by keyword class.
 Attributes are the variables that belong to a class.
 Attributes are always public and can be accessed using the dot (.)
operator. Example: Myclass.Myattribute

Creating a Class
Here, the class keyword indicates that we are creating a class
followed by name of the class (Dog in this case).

class Dog:
species = "Canine" # Class attribute

def __init__(self, name, age):


self.name = name # Instance attribute
self.age = age # Instance attribute

Explanation:
 class Dog: Defines a class named Dog.
 species: A class attribute shared by all instances of the class.
 __init__ method: Initializes the name and age attributes when a new
object is created.

Python Objects

An Object is an instance of a Class. It represents a specific


implementation of the class and holds its own data.
An object consists of:
 State: It is represented by the attributes and reflects the properties of
an object.
 Behavior: It is represented by the methods of an object and reflects
the response of an object to other objects.
 Identity: It gives a unique name to an object and enables one object to
interact with other objects.
Creating Object
Creating an object in Python involves instantiating a class to create a new
instance of that class. This process is also referred to as object instantiation.

class Dog:
species = "Canine" # Class attribute

def __init__(self, name, age):


self.name = name # Instance attribute
self.age = age # Instance attribute

# Creating an object of the Dog class


dog1 = Dog("Buddy", 3)
print(dog1.name)
print(dog1.species)

Output

Buddy
Canine
Explanation:
 dog1 = Dog(“Buddy”, 3): Creates an object of the Dog class with
name as “Buddy” and age as 3.
 dog1.name: Accesses the instance attribute name of the dog1 object.
 dog1.species: Accesses the class attribute species of the dog1 object.

CONSTRUCTORS IN PYTHON
In Python, a constructor is a special method that is called automatically
when an object is created from a class. Its main role is to initialize the
object by setting up its attributes or state.
The method __new__ is the constructor that creates a new instance
of the class while __init__ is the initializer that sets up the instance’s
attributes after creation. These methods work together to manage object
creation and initialization.

__new__ Method
This method is responsible for creating a new instance of a class. It
allocates memory and returns the new object. It is called
before __init__.

class ClassName:
def __new__(cls, parameters):
instance = super(ClassName, cls).__new__(cls)
return instance

__init__ Method

__init__ method is the constructor in Python, automatically called


when a new object is created. It initializes the attributes of the class.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age

dog1 = Dog("Buddy", 3)
print(dog1.name)

Output
Buddy
Explanation:
 __init__: Special method used for initialization.
 self.name and self.age: Instance attributes initialized in the
constructor.

Classes with multiple objects:


class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed

def bark(self):
return "Woof!"

# Creating multiple objects of the Dog class


dog1 = Dog("Buddy", "Golden Retriever")
dog2 = Dog("Max", "German Shepherd")
dog3 = Dog("Bella", "Poodle")

# Each object has its own data


print(f"{dog1.name} is a {dog1.breed}") # Output: Buddy is a Golden
Retriever
print(f"{dog2.name} is a {dog2.breed}") # Output: Max is a German
Shepherd
print(dog3.bark()) # Output: Woof!

# Modifying one object does not affect others


dog2.name = "Charlie"
print(f"{dog2.name} is a {dog2.breed}") # Output: Charlie is a German
Shepherd

OBJECTS AS ARGUMENTS IN PYTHON:

In Python, objects can be passed as arguments to functions. This is because


everything in Python is an object — including integers, strings, lists, and even functions
themselves.

When you pass an object to a function, you’re essentially passing a reference to that object.
Depending on the type of object, this may or may not allow the function to modify the
original object.

Explanation
 Immutable objects (like int, str, tuple) cannot be changed inside the function. Any
changes create a new object.
 Mutable objects (like list, dict, set, and custom class objects) can be changed inside the
function, and those changes affect the original object.
Example 1: Passing a Mutable Object (List)
def add_element(my_list):
my_list.append(4)
print("Inside function:", my_list)

nums = [1, 2, 3]
add_element(nums)
print("Outside function:", nums)

Output:

matlab
CopyEdit
Inside function: [1, 2, 3, 4]
Outside function: [1, 2, 3, 4]

✅ The list was modified inside the function because lists are mutable.

Example 2: Passing an Immutable Object (Integer)

def increment(n):
n += 1
print("Inside function:", n)

x=5
increment(x)
print("Outside function:", x)

Output:

bash
CopyEdit
Inside function: 6
Outside function: 5
Inheritance in Python:
Inheritance is a core concept of object-oriented programming (OOP) that allows one
class (called a child or subclass) to inherit attributes and methods from another class (called
a parent or superclass).

This helps promote code reuse, modularity, and extensibility.

🔸 Syntax of Inheritance
class Parent:
# parent class code

class Child(Parent):
# child class inherits from Parent

🔸 Example 1: Basic Inheritance


class Animal:
def speak(self):
print("This animal makes a sound.")

class Dog(Animal): # Dog inherits from Animal


def bark(self):
print("Woof!")

d = Dog()
d.speak() # inherited from Animal
d.bark() # defined in Dog

Output:

css
CopyEdit
This animal makes a sound.
Woof!

✅ Dog can access methods from Animal because it inherits from it.

1. Single and Multiple Inheritance

Single Inheritance
In single inheritance, a child class inherits from one parent class.

Example:

class Animal:
def speak(self):
print("Animal speaks")

class Dog(Animal): # Inherits from Animal


def bark(self):
print("Dog barks")

d = Dog()
d.speak() # Inherited from Animal
d.bark() # Defined in Dog

Output:

Animal speaks
Dog barks

🔸 Only one parent class is involved.

🔹 2. Multiple Inheritance

In multiple inheritance, a class inherits from two or more parent classes.


Example:

class Father:
def skills(self):
print("Gardening, Carpentry")

class Mother:
def skills(self):
print("Cooking, Painting")

class Child(Father, Mother): # Inherits from both


def skills(self):
print("Child's own skills +")
Father.skills(self)
Mother.skills(self)

c = Child()
c.skills()

Output:

rust
CopyEdit
Child's own skills +
Gardening, Carpentry
Cooking, Painting

Multilevel and Multipath Inheritance

Multilevel inheritance:

Multilevel inheritance is when a class inherits from a class, which itself


inherits from another class — forming a chain of inheritance.

Like a family tree:

 Class A → base class


 Class B(A) → inherits from A
 Class C(B) → inherits from B (and indirectly from A)

✅ Example:

class Grandparent:
def show_grandparent(self):
print("Grandparent's traits")
class Parent(Grandparent):
def show_parent(self):
print("Parent's traits")

class Child(Parent):
def show_child(self):
print("Child's traits")

c = Child()
c.show_grandparent() # From Grandparent
c.show_parent() # From Parent
c.show_child() # From Child

Output:

rust
CopyEdit
Grandparent's traits
Parent's traits
Child's traits

Multipath inheritance:
Multipath Inheritance occurs when a class inherits from two or more
classes that share a common ancestor. This can lead to ambiguity,
especially when the shared base class has methods or attributes that the child
class might inherit through multiple paths.
Example of Multipath Inheritance
class A:
def show(self):
print("A class method")

class B(A):
def show(self):
print("B class method")

class C(A):
def show(self):
print("C class method")

class D(B, C): # D inherits from both B and C, which both inherit from
A
pass

d = D()
d.show()
Output:

B class method

Encapsulation and Polymorphism


1. Encapsulation in Python
🔹 Definition:
Encapsulation is a fundamental concept in object-oriented programming
(OOP) that refers to binding the data (variables) and the code (methods)
that operate on the data into a single unit, i.e., a class.
It also restricts direct access to some of an object's components, which
helps prevent accidental modification of data.

🔹 Private Instance Variables in Python:


In Python, we make variables private by prefixing their names with double
underscores __. These variables cannot be accessed directly outside the
class.
✅ Benefits of Encapsulation:
 Hides internal state of the object.
 Protects data from unwanted changes.
 Encourages use of getter/setter methods for validation.

🧪 Example with Explanation:


class Student:
def __init__(self, name, marks):
self.__name = name # private variable
self.__marks = marks # private variable

# Getter method to access private variable


def get_name(self):
return self.__name

# Getter for marks


def get_marks(self):
return self.__marks

# Setter for marks with validation


def set_marks(self, marks):
if 0 <= marks <= 100:
self.__marks = marks
else:
print("Invalid marks! Please enter between 0 and 100.")
# Using the class
s1 = Student("Ravi", 88)

print("Name:", s1.get_name()) # Accessing name


print("Marks:", s1.get_marks()) # Accessing marks

s1.set_marks(105) # Will show an error message


s1.set_marks(95) # Valid update
print("Updated Marks:", s1.get_marks())
Explanation:
 __name and __marks are private and cannot be accessed directly like
s1.__name.
 get_name() and set_marks() are used to safely access and modify values.

2. Polymorphism in Python
🔹 Definition:
Polymorphism means “many forms”. In Python, polymorphism allows the
same method or operator to behave differently based on the object it is
acting upon.
🔸 Types of Polymorphism:
1. Function/method polymorphism (same method name, different
behavior)
2. Operator overloading (same operator, different behavior)

Operator Overloading in Python


Python allows us to overload built-in operators like +, -, *, etc. This is
done using special methods (also known as magic methods or dunder
methods).
 For example: To overload the + operator, we use the method __add__().

Example: Adding Two Book Objects


python
CopyEdit
class Book:
def __init__(self, pages):
self.pages = pages

# Overload + operator
def __add__(self, other):
return Book(self.pages + other.pages)

def display(self):
print("Total Pages:", self.pages)
# Create two book objects
book1 = Book(150)
book2 = Book(200)

# Add books using overloaded + operator


book3 = book1 + book2

# Display result
book3.display()
Explanation:
 The __add__() method is automatically called when book1 + book2 is
used.
 It returns a new Book object with combined pages.

UNIT – 4
GU Interface
1. Tkinter Module

 Tkinter is the standard GUI library for Python.


 GU Tool Kit – Interface  full form of TKinter
 It provides tools to create windows, buttons, labels, text boxes, and other
GUI components.
 You must import it to use:

import tkinter as tk

2. Window and Widgets

 Window: The main container where all GUI components live.

root = tk.Tk() # Create the main window


root.mainloop() # Starts the GUI event loop

 Widgets: Elements like buttons, labels, entries, etc.


Examples:

label = tk.Label(root, text="Hello World")


button = tk.Button(root, text="Click Me")
entry = tk.Entry(root)

3. Layout Management

Tkinter has three layout managers to arrange widgets: pack, grid, and place.
a. pack()

 Arranges widgets in blocks before or after each other (top, bottom, left,
right).
 Example:

label.pack(side="top")
button.pack(side="left")

 Simple and automatic but less control over precise placement.

b. grid()

 Organizes widgets in a row and column table-like structure.


 Example:

label.grid(row=0, column=0)
entry.grid(row=0, column=1)

 More control than pack(), good for forms and tables.

c. place()

 Places widgets at specific x and y coordinates.


 Example:

button.place(x=50, y=100)

 Offers pixel-perfect control but can be harder to manage dynamically.

Example Putting It All Together


import tkinter as tk

root = tk.Tk()
root.title("Simple GUI")

label = tk.Label(root, text="Enter your name:")


label.grid(row=0, column=0)

entry = tk.Entry(root)
entry.grid(row=0, column=1)

button = tk.Button(root, text="Submit")


button.grid(row=1, column=1)

root.mainloop()
Python SQLite
1. Introduction to sqlite3 Module
SQLite is a lightweight, disk-based database. Python’s built-in module sqlite3
allows you to work with SQLite databases easily.

Importing sqlite3 Module

import sqlite3
2. SQLite Methods
a. connect()
 Used to connect to an SQLite database file.
 If the file does not exist, it will be created.

conn = sqlite3.connect('student.db') # Creates or opens a file named student.db

b. cursor()
 Creates a cursor object which is used to execute SQL commands.

cur = conn.cursor()

c. execute()
 Executes an SQL query.

cur.execute("SQL QUERY")

d. close()
 Closes the database connection.

conn.close()
3. Connecting to a Database

import sqlite3

conn = sqlite3.connect('school.db') # Creates school.db if it doesn't exist


print("Database connected successfully.")
conn.close()

4. Creating a Table

import sqlite3

conn = sqlite3.connect('school.db')
cur = conn.cursor()
cur.execute('''
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER,
grade TEXT)''')

print("Table created successfully.")


conn.commit()
conn.close()
Explanation:
 IF NOT EXISTS: Avoids error if the table already exists.
 id INTEGER PRIMARY KEY: Makes id a unique identifier.

5. Operations on Tables
a. INSERT Records

import sqlite3

conn = sqlite3.connect('school.db')
cur = conn.cursor()

cur.execute("INSERT INTO students (name, age, grade) VALUES (?, ?, ?)",


("Alice", 20, "A"))
cur.execute("INSERT INTO students (name, age, grade) VALUES (?, ?, ?)",
("Bob", 22, "B"))

conn.commit()
print("Records inserted.")
conn.close()
Explanation:
 ? placeholders are used to safely insert values (prevents SQL injection).
 commit() is required to save changes.

b. SELECT Records

import sqlite3

conn = sqlite3.connect('school.db')
cur = conn.cursor()

cur.execute("SELECT * FROM students")


rows = cur.fetchall()

for row in rows:


print(row)
conn.close()
Explanation:
 fetchall() returns all rows from the query result.
 You can also use fetchone() to get a single record.

c. UPDATE Records

import sqlite3

conn = sqlite3.connect('school.db')
cur = conn.cursor()

cur.execute("UPDATE students SET grade = ? WHERE name = ?", ("A+",


"Bob"))

conn.commit()
print("Record updated.")
conn.close()
Explanation:
 Updates Bob's grade to "A+".

d. DELETE Records

import sqlite3

conn = sqlite3.connect('school.db')
cur = conn.cursor()

cur.execute("DELETE FROM students WHERE name = ?", ("Alice",))

conn.commit()
print("Record deleted.")
conn.close()
Explanation:
 Deletes the record where the name is "Alice".

e. DROP Table

import sqlite3

conn = sqlite3.connect('school.db')
cur = conn.cursor()

cur.execute("DROP TABLE IF EXISTS students")

conn.commit()
print("Table dropped.")
conn.close()
Explanation:
 Removes the entire table and all its data.
 Use IF EXISTS to prevent error if the table doesn't exist.

Summary For Reference


Method Description
1. connect() Connects to the SQLite database
2. cursor() Creates a cursor object
3. execute() Executes SQL commands
4. commit() Saves changes to the database
5. close() Closes the connection

DATA ANALYSIS
NumPy
What is NumPy?
NumPy stands for Numerical Python.
It is used to perform fast mathematical operations on arrays and matrices.
It is much faster than Python lists when it comes to numerical operations.
How to use NumPy?
You need to import the library first:
import numpy as np
Here, np is just a short name (alias) for NumPy.
1. Array Creation
a. From a list or tuple
You can create a NumPy array using a Python list:
a = np.array([1, 2, 3])
print(a)
Explanation:
np.array() converts a list into a NumPy array.
Output: [1 2 3] — it's like a list but optimized for numeric work.
b. Creating a 2D Array (Matrix)
b = np.array([[1, 2], [3, 4]])
print(b)
Explanation:
This creates a 2D array with 2 rows and 2 columns.
Output:
[[1 2]
[3 4]]
c. Using built-in functions
i= np.zeros()
z = np.zeros((2, 3))
print(z)
Explanation:
Creates a 2x3 matrix filled with 0s.
Output:
[[0. 0. 0.]
[0. 0. 0.]]
ii. np.ones()
o = np.ones((2, 2))
print(o)
Explanation:
Creates a 2x2 matrix filled with 1s.
Output:
[[1. 1.]
[1. 1.]]
iii. np.arange(start, stop, step)
r = np.arange(0, 10, 2)
print(r)
Explanation:
Generates numbers from 0 to 10 with a step of 2.
Output: [0 2 4 6 8]
iv. np.linspace(start, stop, num)
l = np.linspace(0, 1, 5)
print(l)
Explanation:
Generates 5 evenly spaced numbers between 0 and 1.
Output: [0. 0.25 0.5 0.75 1. ]

2. Basic Operations on Arrays


a. Arithmetic Operations
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(a + b) # Addition
print(a * b) # Element-wise multiplication
print(a ** 2) # Square of each element
Explanation:
a + b adds each element: [1+4, 2+5, 3+6] = [5 7 9]
a * b multiplies elements: [1*4, 2*5, 3*6] = [4 10 18]
a ** 2 squares elements: [1, 4, 9]
b. Comparison
print(a > 2)
Explanation:
Compares each element of a to 2.
Output: [False False True] because only 3 > 2
c. Matrix Multiplication
A = np.array([[1, 2], [3, 4]])
B = np.array([[2, 0], [1, 3]])
print(A @ B)
Explanation:
@ is matrix multiplication (like dot product).

Calculates:
[[1×2 + 2×1, 1×0 + 2×3],
[3×2 + 4×1, 3×0 + 4×3]]
= [[4, 6], [10, 12]]
d. Statistical Functions
a = np.array([1, 2, 3, 4])
print(np.mean(a)) # Average = (1+2+3+4)/4 = 2.5
print(np.max(a)) # Largest value = 4
print(np.min(a)) # Smallest value = 1
print(np.sum(a)) # Total = 10

Pandas in Python
Introduction to Pandas (Python Library)
What is Pandas?
Pandas is a Python library used for working with data.
It helps with:
 Organizing data
 Analyzing data
 Manipulating data
It’s especially useful for working with tabular data (like Excel spreadsheets).

Installing and Importing Pandas


pip install pandas
This command installs the Pandas library using pip (Python's package
manager).
import pandas as pd
This imports Pandas and gives it the nickname pd, so we can use it with shorter
code.

What is a Series?
A Series is a one-dimensional array — like a single column of data.
Example:
import pandas as pd
s = pd.Series([10, 20, 30])
print(s)
Output:
0 10
1 20
2 30
 This creates a Series with three values.
 Each value has a default index (0, 1, 2).
 It's similar to a list, but with labels (index) that Pandas manages.

Series with Custom Index


You can assign your own index labels for clarity.
Example:
s = pd.Series([85, 90, 75], index=['Math', 'Science', 'English'])
print(s)
Output:
Math 85
Science 90
English 75
 The values now have subject names as indexes.
 Makes the data easier to read and interpret.

What is a DataFrame?
A DataFrame is a two-dimensional table — similar to a spreadsheet or SQL
table.
Example:
data = {'Name': ['Amit', 'Riya', 'John'], 'Marks': [88, 92, 79]}
df = pd.DataFrame(data)
print(df)
Output:
Name Marks
0 Amit 88
1 Riya 92
2 John 79
 The data dictionary holds columns and values.
 Pandas converts this dictionary into a table-like structure.
 The index (0, 1, 2) is added automatically.

Dictionaries & Tuples in Pandas


Dictionary Example:
student = {'Name': 'Amit', 'Age': 16}
 Stores data as key-value pairs.
 Often used to create DataFrames.
Tuple Example:
marks = (88, 92, 79)
 A tuple is like a list, but it cannot be changed.
 Useful for storing fixed data.

Viewing Data in DataFrame


df.head() # Shows the first 5 rows
df.tail() # Shows the last 5 rows
df.shape # Returns (rows, columns)
df.columns # Lists column names
These commands help you get a quick overview of your data.

Accessing Data in a DataFrame


df['Name'] # Get the 'Name' column
df.iloc[0] # Get the first row (by position)
df.loc[1, 'Marks'] # Get the 'Marks' value from row with index 1
Explanation:
 df['Name']: Returns a Series of all names.
 df.iloc[0]: Returns all data in the first row.
 df.loc[1, 'Marks']: Returns the value at row index 1 and column 'Marks'.

DATA VISUALIZATION IN PYTHON

Introduction to Data Visualization


 Data visualization means presenting data using graphs or charts.
 It helps reveal patterns, trends, and insights quickly.
 Common in data analysis, reporting, and presentations.

Matplotlib Library
 matplotlib is a powerful Python library for creating static, interactive,
and animated visualizations.
 We often use the pyplot module for quick and easy plotting.

Install and Import


pip install matplotlib

import matplotlib.pyplot as plt

1. Line Chart
🔹 Use: To show trends over time or continuous data.
🔹 Code Example:
import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y = [10, 20, 15, 25]

plt.plot(x, y)
plt.title("Line Chart")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.show()
🔹 Explanation:
 plot(x, y) draws a line through data points.
 Useful to show changes or progression.

2. Bar Chart
🔹 Use: To compare categories or groups.
🔹 Code Example:
subjects = ['Math', 'Science', 'English']
marks = [85, 90, 78]

plt.bar(subjects, marks)
plt.title("Student Marks")
plt.xlabel("Subjects")
plt.ylabel("Marks")
plt.show()
🔹 Explanation:
 bar(x, y) draws vertical bars for each category.
 Good for comparing values side-by-side.

3. Histogram
🔹 Use: To show frequency distribution of continuous data.
🔹 Code Example:
ages = [18, 19, 21, 20, 22, 23, 24, 21, 22, 25]

plt.hist(ages, bins=5)
plt.title("Age Distribution")
plt.xlabel("Age")
plt.ylabel("bins1")
plt.show()
🔹 Explanation:
 hist(data, bins) groups data into intervals.
 Shows how many values fall into each range (bin).

4. Pie Chart
🔹 Use: To show percentage distribution (parts of a whole).
🔹 Code Example:
labels = ['Math', 'Science', 'English']
sizes = [30, 40, 30]

plt.pie(sizes, labels=labels, autopct='%1.1f%%')


plt.title("Subject Distribution")
plt.show()
🔹 Explanation:
 pie() creates a circular chart.
 autopct shows percentage values on slices.

You might also like