0% found this document useful (0 votes)
13 views41 pages

Python

The document covers file handling and exception handling in Python, detailing operations on text and binary files, as well as built-in exceptions. It also introduces GUI programming with Tkinter, data analysis using NumPy and Pandas, and data visualization with Matplotlib. Key concepts include file types, error handling, and the structure of Python programs.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views41 pages

Python

The document covers file handling and exception handling in Python, detailing operations on text and binary files, as well as built-in exceptions. It also introduces GUI programming with Tkinter, data analysis using NumPy and Pandas, and data visualization with Matplotlib. Key concepts include file types, error handling, and the structure of Python programs.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

File Handling & Exception Handling File Handling: File Types (Text vs Binary).

Operations on Files: Create, Open, read (read,


readline, readlines), Write, Append, Close. File Names, Absolute and Relative Paths.

Exception Handling: Errors vs Exceptions. Built-in Exceptions (IndexError, KeyError, ImportError, etc.). The try, except, else, and
finally blocks.

2. GUI Interface (Tkinter): Introduction to tkinter Module. Root Window and Main Event Loop. Widgets: Label, Button, Entry,
Text, Checkbutton, Radiobutton, Listbox, Scrollbar. Layout Management: Pack, Grid, and Place geometry managers. Event
Handling (Binding functions to buttons/keys).

Python SQLite: The sqlite3 module. Connection Object & Cursor Object. SQL Operations: CREATE Table, INSERT data, SELECT
(fetching capabilities), UPDATE, and DELETE.

3. Data Analysis (NumPy & Pandas): NumPy (Numerical Python): Introduction to NumPy and Ndarray. Array Creation (from lists,
ranges, zeros, ones). Array Operations: Arithmetic, Slicing, Indexing, and Reshaping.

Pandas (Data Manipulation): Introduction to Series and DataFrames. Creating DataFrames from Dictionary, List of Tuples, CSV,
and Excel files. Data Inspection: head (), tail (), info (), describe ().

4. Data Visualization & Reporting: Introduction to Data Visualization: Importance of Visualization in Data Analysis. Matplotlib
Library: The pyplot interface. Plot Types: Line Chart, Bar Chart (Vertical/Horizontal), Histogram, Pie Chart. References: 1. Think
Python How to Think Like a Computer Scientist, Allen Downey et al., 2nd Edition, Green Tea Press. Freely available online @
File Handling:---

 Python is a simple and easy-to-learn programming language.

 It was created by Guido van Rossum and released in 1991.

 File handling in Python refers to the process of working with files stored on a computer system.

 It allows a program to perform important operations such as creating, opening, reading, writing, and closing files.

 Files help in permanent storage of data, which means the information remains saved even after the program ends.

 Python provides a built-in function called open(). It is used to start working with a file. In Python, file handling is done using
built-in functions like open(), read(), write(), etc.

 File handling is useful for storing user information, records, logs, reports, and large amounts of data.

 File handling is commonly used in text editors, database systems, data analysis programs, and many real-world applications.

File Types
Files are mainly divided into two types based on how data is stored. These types help us decide how to read or write
information into the file.

1. Text Files

• These files store data in the form plain readable text. The data is arranged and stored line by line, and each line
usually ends with a newline character (\n). Text files can be easily opened and edited using text editors such as
Notepad, VS Code, or Notepad++.

• They usually have extensions such as .txt, .csv, .py, .html, .json, .xml

Examples:

• [Link], [Link], [Link]

Simple Meaning: A text file is like a normal notebook where you write simple words and sentences.

2. Binary Files

A binary file stores data in the form of binary digits (0s and 1s) instead of readable characters.

In binary files, the data is stored as bytes (rwa data), and it cannot be understood directly by humans without special software.

Binary files are mainly used to store complex data such as images, videos, audio, and executable programs.

Common extensions include .jpg, .png, .mp4, .pdf, .bin.

Examples:

• [Link], song.mp3, [Link]

A binary file is like a coded storage system where the computer stores data using 0s and 1s, which humans cannot easily read.
[Link]. Text File Binary File

1 Stores data in plain text format. Stores data in binary (0s and 1s) format.

2 Easily readable by humans. Not readable by humans directly.

3 Data is stored as characters and lines. Data is stored as bytes.

Occupies more space because data is stored as Occupies less space because data is compact in binary
characters. form.

4 Suitable for simple data like numbers, names, Suitable for complex data like images, audio, software,
messages. videos.

5 Slower processing because characters must be Faster processing because the computer directly works
converted into binary with binary data.

6 Example formats: .txt, .csv, .json Example formats: .bin, .exe, .jpg, .mp3, .xlsx

7 Editing can be done using any text editor (Notepad, Needs specific software to edit (Photoshop, Excel, etc.)
etc.)

Operations on Files

Python allows us to work with files using different operations such as Create, Open, Read, Write, and Close. All file operations
are done using the open() function.

The basic syntax is:

file = open("filename", "mode") like file = open("[Link]", "w")

[Link]()

1. Creating a File:-- A file can be created using write mode ("w") or append mode ("a"). If the file does not exist, Python
automatically creates a new file.

Example:

file = open("[Link]", "w")

[Link]("Hello, this is a new file.")

[Link]()

What happens?

• If [Link] does not exist → Python creates a new file and writes the text.

• If [Link] exists → It is overwritten (old data is deleted).


2. Opening a File:-- Python provides a built-in function called open(). It is used to start working with a file. To work with a file,
we must open it using the open() function.

Common Modes:

Mode Meaning

"r" Read mode

"w" Write mode (creates/overwrites file)

"a" Append mode (adds data without deleting)

"rb" Read binary

"wb" Write binary

Example:

file = open("[Link]", "r")

This opens [Link] in read mode.

3. Reading from a File:-- Reading means getting data from the file. Python provides three reading methods:

• read() → reads the entire file as a single string


• readline() → reads one line at a time from the file including the newline character (\n).
• readlines() → reads all lines and return them as a list of string

Example: This program reads all the text from [Link] and prints it.

file = open("[Link]", "r")

content = [Link]()

print(content)

[Link]()

4. Writing to a File:-- Writing means adding new data to a file. We use the write mode ("w") or append mode ("a") to write
data.

Example:

file = open("[Link]", "w")

[Link]("Welcome to Python File Handling.")

[Link]()

Explanation:
This writes new text into the file.
(If the file already exists, "w" will overwrite it.) If the file does not exist, it is created.

5. Appending to a File:-- Append mode adds new data at the end of the file without deleting existing content. Mode used: a
(append mode).

Example:

file = open("[Link]", "a")

[Link]("\nThis is a new line added.")

[Link]()
6. Closing a File:-- After reading or writing, the file must be closed using: close().

Example:

[Link]()

File Names and Paths


When working with files in programming, we must know where the file is located and how to identify it.
This is done using file names and file paths.

1. File Name
A file name is the label/name given to a file so that it can be identified by the operating system and the user. Every file has a
name and an extension.

A file name has two parts:

1. Name (Main Title of the File)

This is the actual name given to the file. Examples: notes, student_record, image1

2. Extension (Type of the File)

The extension comes after a dot (.) and shows what type of file it is.
Examples:

• .txt → text file

• .csv → comma-separated values file

• .jpg → image file

• .pdf → document file

Structure of a File Name [Link] { [Link] [Link] [Link] }

2. File Path
A file path is the complete address or location of a file in the computer's directory (folder) structure. It tells the program exactly
where the file is stored so that it can be accessed. It shows how to reach the file from a particular location.

There are two main types of paths:

A. Relative Path

• A relative path refers to the current working directory/folder of the program.

• It does NOT give the full location of the file. It does not start from the root directory.

• It is Short and simple to use.

Example:

file = open("[Link]", "r")

This means the file [Link] is in the same folder as the Python program.

Another example:

file = open("folder/[Link]", "r")


B. Absolute Path

• An absolute path gives the full address of the file starting from the root directory. It gives the exact
location of the file in the system.  It starts from the root directory or drive.
•  It is usually longer but very accurate and precise.

Feature Relative Path Absolute Path


Definition A relative path refers to the current An absolute path gives the full address of the file starting
working directory/folder of the from the root directory.
program.
Location It does not give the full location of the It gives the exact and complete location of the file in the
Information file. system.
Starting Point Starts from the current directory of the Starts from the root directory or drive.
program.
Length of Path Usually short and simple. Usually longer but more precise.
Dependency Depends on the current working Independent of the current working directory.
directory.
Example file = open("[Link]", "r") file = open("C:\\Users\\Student\\Documents\\[Link]", "r")
(Code)

Format Operator
The format operator is represented by the % symbol in Python. It is used to insert values (like strings, integers, floats) into a
string in a formatted way.

It works with placeholders like

• %s → string
• %d → integer
• %f → float

Values are supplied after the string using the % operator.

Multiple values can be inserted using a tuple: "%s is %d" % (name, age).

Decimal formatting can be controlled for floats using %.nf (e.g., %.2f → 2 decimal places).

Exception Handling (Detailed & Simple Explanation)


Introduction

• Exception Handling is a method used in programming to handle errors that occur during program execution.

• It allows a program to run continuously without crashing, even if an unexpected error happens.

• Using exception handling, we can write safe, error-free and reliable programs.

• It helps in identifying the error, controlling it, and giving meaningful messages to the user.

• The try–except structure is used to catch and handle exceptions.

What is an Error?

• An error is a mistake in a program that stops it from executing correctly..

• Errors usually occur before the code runs, during compilation or syntax checking.
• They must be fixed by the programmer.

• Example: SyntaxError (wrong code structure).

Example of Error

print("Hello"

Output: SyntaxError: unexpected EOF while parsing

Types of Errors in Python

Errors in Python are mainly divided into three types:

1. Syntax Errors

2. Runtime Errors (Exceptions)

3. Logical Errors

1. Syntax Error

A syntax error occurs when the program does not follow the correct syntax rules of Python. These errors are detected before
the program runs. Ex:

print("Hello" # SyntaxError: unexpected EOF while parsing

2. Runtime Error (Exception)

A runtime error occurs while the program is running. These errors are called exceptions.

Example:

a = 10
b=0
print(a/b)

Output

ZeroDivisionError: division by zero

3. Logical Error

A logical error occurs when the program runs without crashing but produces incorrect results. These errors are caused by
wrong logic in the program.

Example:

a = 10
b=5
print("Sum:", a - b)

Output

Sum: 5+

What is an Exception?

• An exception is a problem that occurs while the program is running.

• Even if the syntax is correct, the program may face unexpected situations.

• Exceptions can be handled using try–except so the program does not stop.

• Example: dividing a number by zero.


Example of Exception

a = 10 / 0

Output: ZeroDivisionError

Difference: Errors vs Exceptions (Detailed Table)

Errors Exceptions

Errors occur due to serious issues in code or Exceptions are problems that occur during program execution
system. (runtime)..

Occur while the program is running..


Occur before the program runs.

Can be handled using try and except blocks.


Usually cannot be handled using exception
handling.

Program stops immediately when an error occcurs Program continues running if exception is handled.

Example: SyntaxError, MemoryError. Example: IndexError, ZeroDivisionError, KeyError.

Indicates a problem in the code structure. Indicates a problem during runtime execution.
Built-in Exceptions in Python (Proper Explanation + Points)
Built-in exceptions are predefined errors in Python that occur when something goes wrong during the execution of a
program.
Python automatically shows these errors, and programmers can handle them using try and except blocks.

Common Built-in Exceptions


IndexError
• Occurs when we try to access a list/tuple/string index that does not exist. Happens when the index is out of range.

• It indicates you are trying to access a wrong or invalid position.

Example:

numbers = [10, 20, 30]

print(numbers[5]) # IndexError

KeyError
• Occurs when we try to access a key that is not present in a dictionary. It means the specified key is not found in the
dictionary. Usually happens due to wrong spelling or missing key.

Example:

student = {"name": "Amit", "age": 20}

print(student["marks"]) # KeyError

ImportError
• Occurs when Python cannot find a module that we are trying to import. Happens if module name is wrong or the
module is not installed. It indicates an issue with importing external libraries.

Example:

import myModule # ImportError if module does not exist

TypeError
• Occurs when an operation is applied to the wrong data type. Indicates incompatible types being used in an operation.

• Example: adding a string to a number.

Example:

print("Hello" + 5) # TypeError

ValueError
• Occurs when the data type is correct but the value is invalid. Indicates the function received wrong or unexpected
value. Example: converting "abc" to an integer.

Example: int("abc") # ValueError


ZeroDivisionError
• Occurs when a number is divided by zero. Division by zero is mathematically not allowed. Python immediately stops
the program and raises this exception.

Example:

a = 10 / 0 # ZeroDivisionError

FileNotFoundError
Occurs when trying to open a file that does not exist. Happens due to wrong file name or wrong path. Indicates missing or
deleted file.

Example:

f = open("[Link]") # FileNotFoundError if file missing

AttributeError
Occurs when you try to access an attribute/function that does not exist in an object.

• Happens due to spelling mistakes or wrong object. Python tells you the object has no such attribute.

Example:

x = "Hello"

[Link]("!") # AttributeError

Python’s built-in exceptions help identify runtime errors clearly. They make debugging easier by telling exactly what mistake
happened (wrong index, wrong key, wrong module, wrong type, etc.). Understanding these exceptions helps in writing error-
free and stable programs.
Try, Except, Else, Finally (Python Exception Handling)
Common Example Code (used for all explanations)

try:

num = int(input("Enter a number: "))

result = 10 / num

except ZeroDivisionError:

print("You cannot divide by zero!")

else:

print("Division successful. Result =", result)

finally:

print("Program ended.")

1. try Block – Explanation

• The try block contains the code that may cause an exception.

• Python tests this code first before moving to except.

• If an error occurs inside try, the remaining try code stops immediately. Control automatically jumps to the
corresponding except block.

Using the Example

• int(input()) and 10 / num are inside try because they can cause errors.

2. except Block – Explanation

• The except block runs if an error occurs in the try block. It handles the exception and prevents the program from
crashing.

• You can write specific exceptions (like ZeroDivisionError) or a general one.

• Runs only when an exception occurs.

Using the Example

• If user enters 0, division by zero happens → except prints:


"You cannot divide by zero!"

3. else Block – Explanation

• else block executes only when no error occurs in try block. Useful for writing code that must run after successful
execution. Keeps the program clean by separating “success logic” from “error logic”.

• else block is skipped if any exception happens.

Using the Example: If user enters a valid non-zero number → else prints the result.
4. finally Block – Explanation

• The finally block always executes whether an exception occurs or not..

• Used for clean-up tasks: closing files, releasing resources, etc.

• Executes even if try or except contains return statements.

• Ensures program ends in a controlled manner.

Using the Example

• Whether user enters 0 or any number → finally prints:


"Program ended."

try:

num1 = int(input("Enter first number: "))

num2 = int(input("Enter second number: "))

result = num1 / num2

except ZeroDivisionError:

print("Cannot divide by zero")

except ValueError:

print("Invalid input")

else:

print("Result:", result)

finally:

print("Program execution completed")

1. try Block
The try block contains the code that may cause an error. Here, the program takes two numbers from the user and
performs division.

2. except ZeroDivisionError
This block handles the error when the second number is 0, since division by zero is not allowed.

3. except ValueError
This block runs when the user enters invalid input (such as letters instead of numbers).

4. else Block
The else block executes if no error occurs in the try block and prints the result of the division.

5. finally Block
The finally block always executes, whether an error occurs or not, and displays the message that the program has
finished execution.
Module : 2 GUI Interface in Python – Tkinter
A Graphical User Interface (GUI) allows users to interact with a program using windows, buttons, text boxes, and menus
instead of typing commands. In Python, GUI applications can be created using the Tkinter module.

Tkinter is the standard GUI library in Python that provides tools and widgets to build desktop applications easily.

1. The Tkinter Module

• Tkinter is the standard GUI (Graphical User Interface) library for Python.
• It allows developers to create windows, buttons, text boxes, menus, and other GUI elements in a Python program.
• Tkinter acts as a bridge between Python and the Tk GUI toolkit. It allows Python programs to communicate with
the Tk library.
• Using Tkinter, developers can build desktop applications that users can interact with using a mouse
and keyboard instead of typing commands in the terminal.

Features of Tkinter

• It is included with Python, so no extra installation is required.


• It provides many built-in widgets such as Label, Button, Entry, Text, Listbox, etc.
• It supports event handling, allowing programs to respond to user actions like clicking buttons or pressing
keys.
• It allows arranging widgets using layout managers such as pack(), grid(), and place().
• To use Tkinter, we import it in the program:

import tkinter as tk

tkinter → the module

as tk → gives it a short name tk for easier use

import tkinter as tk

root = [Link]()

[Link]("Tkinter Example")

label = [Link](root, text="Hello Tkinter")

[Link]()

[Link]()

Tkinter: Root Window and Main Event Loop


Tkinter is Python’s standard library for creating Graphical User Interfaces (GUI). In every Tkinter application, two fundamental
components are crucial:

1. Root Window – The main window of the application.

2. Main Event Loop – Keeps the GUI responsive to user actions.

1. Root Window
Definition

• The Root Window is the main container/window in a Tkinter application.

• It is the first window created and serves as the parent for all other widgets (buttons, labels, frames, etc.).

• All other windows or widgets either attach to the root window or are created as child windows (Toplevel).
• Created using root = [Link]().
• It Can be customized: title, size, background color, and icon.
o title() → window title

o geometry() → size of the window

o configure() → background color and style

o iconbitmap() → icon for the window

• Closing the root window terminates the application.


• Parent for Widgets: All GUI elements are placed inside the root window.

• Closing the Root Window Ends the Program: When the user closes the root window, the entire application terminates.

Example

import tkinter as tk

root = [Link]() # Create root window

[Link]("Root Window Example") # Set window title

[Link]("500x300") # Set window size

[Link](bg="lightblue") # Set background color

label = [Link](root, text="Welcome to Tkinter!", font=("Arial", 16))

[Link](pady=50)

[Link]() # Start main event loop

Explanation

• [Link]() → Creates the root window.

• [Link]() → Names the window.

• [Link]() → Sets width and height.

• [Link]() → Changes background color.

• Label(root, ...) → Creates a label inside the root window.

• pack() → Places the widget.

2. Main Event Loop


Definition

• The Main Event Loop is the core of the Tkinter application.

• The Main Event Loop is an infinite loop that keeps the window running and responsive.
• It waits for user events like button clicks, key presses, or mouse movements and responds accordingly.
• In Tkinter, it is called using: [Link]().

• Keeps the GUI window open and interactive.


• Handles user-driven events, enabling dynamic response.
• Runs until the root window is closed, ensuring continuous interaction.
• Essential for event-driven programming in Tkinter.

Example

import tkinter as tk

root = [Link]()

[Link]("Event Loop Example")

[Link]("400x200")

def on_click():

[Link](text="Button Clicked!")

label = [Link](root, text="Click the Button Below", font=("Arial", 14))

[Link](pady=20)

button = [Link](root, text="Click Me", command=on_click)

[Link]()

[Link]() # Start main event loop

Explanation

• [Link]() → Starts the event loop.

• Waits for the button click event.

• When clicked, on_click() updates the label.

• The window stays interactive until closed.

3. Difference Between Root Window and Main Event Loop

Feature Root Window Main Event Loop

Definition Main window that holds widgets Loop that keeps GUI active and responsive

Purpose Container for all widgets Handles events and updates GUI

Creation root = [Link]() [Link]()

Effect of Closing Terminates the application Stops event processing

Customization Can set title, size, background, icon No customization; purely runs events

3. Widgets

Widgets are GUI elements that allow users to interact with the application. Tkinter provides a variety of widgets for building
interactive interfaces.

1. Widgets are interactive elements placed inside a window.

2. They allow users to input, display, or interact with data.

3. Common widgets: Label, Button, Entry, Text, Checkbutton, Radiobutton, Frame.


4. Widgets are added to the window using layout managers (pack, grid, place).

5. Widgets can be customized (text, color, font, size).

Widget Purpose

Label • A Label is used to display text or images in the GUI. It is non-editable by the
user.

Key Points

• Displays information like instructions, titles, or messages.

• Can set font, color, size, and alignment.

• Supports text wrapping and image display.

Button • A Button is a clickable widget that triggers a function or command when


pressed.

Key Points

• Executes functions or actions on click.

• Supports text, images, and colors.

• Can be disabled or enabled using state.

Entry • An Entry widget is a single-line text input field. Users can enter or modify
text.

Key Points

• Used for taking user input like names, passwords, numbers.

• Supports get() to read input and delete() to clear.

• Can set width, font, and show characters for passwords.

Text • A Text widget is a multi-line text box for input or display.

Key Points

• Supports multiple lines of text.

• Can be used for notes, comments, or documents.

• Methods include get() for reading and insert() for writing text.

Checkbutton • A Checkbutton is used to select one or more options.

• Can be checked or unchecked.

Key Points

• Can hold Boolean (0/1) values.

• Supports multiple checkboxes in the same window.

• Variable is linked using IntVar() or BooleanVar().

Radiobutton • Radiobuttons allow the user to select only one option from a group.

Key Points

• Linked using a single variable (IntVar or StringVar).

• Used for multiple-choice selections.

• Each button has a value assigned to it.


Listbox • A Listbox displays a list of items from which the user can select.

Key Points

• Can allow single or multiple selection.

• Items are added using insert().

• Selection is retrieved using curselection().

Scrollbar • A Scrollbar allows the user to scroll through widgets like Text or Listbox when
content exceeds the visible area.
Key Points
• Can be vertical or horizontal.
• Linked to other widgets using command.
• Improves navigation for large content.

Layout Management in Tkinter


Layout managers is used to control and arrange the widgets inside a window. Layout management controls how widgets are
arranged and positioned inside the parent window (root or frame). Tkinter provides three main layout managers: pack(),
grid(), and place().

1. pack()

• Pack arranges widgets in blocks before or after each other.


• It places widgets top, bottom, left, or right in the container.

Key Points

• Automatically adjusts the widget size to fit content.


• Supports padding (padx, pady), fill, and side options.
• Easy to use for simple layouts.

Example: [Link](side="top")

2. grid()

• Arranges widgets in a table-like structure with rows and columns.

• grid() gives better control than pack() .

• it is mainly used for forms and structured layouts. Each widget is placed in a specific cell.

Key Points

• Very flexible for forms, calculators, and tables.

• Supports rowspan, columnspan, padding. Coordinates start from row=0, column=0 (top-left corner).

Example: [Link](row=0, column=1)

3. place()

• Places widgets at specific coordinates (x, y) inside the parent window..

Key Points

• More control over exact position and size of widgets.


• Supports width, height, relx, rely for relative placement.
• Useful for custom layouts or graphics.
Example: [Link](x=50, y=100)

Event Handling in Tkinter


• Event Handling allows a Tkinter application to respond to user actions, such as:

o Clicking a button

o Pressing a key

o Moving the mouse

• When such an action occurs, it is called an event, and a specific function is executed to handle that event.

• Functions that respond to events are called callback functions.

• Tkinter uses event-driven programming: the program waits for events and reacts.

• An event can be a button click, key press, mouse movement, or window action.

• You can bind an event to a widget using the .bind() method or Button’s command option.

Two common types of events are:

1. Button Clicks

2. Key Presses

1. Button Events

Definition

• A Button is a clickable widget.

• A Button event occurs when a user clicks the button.

• You can bind a function to the button to perform an action.

Key Points

• Buttons make applications interactive.

• Use the command option to trigger a function when the button is clicked.

• Functions triggered by buttons are called callback functions.

• You can customize buttons with text, font, color, and size.

• For advanced control, you can use .bind() to detect single, double, or right-click.

2. Key Events

Definition

• A key event occurs when the user presses a key on the keyboard.

• You can bind a function to respond to specific keys or all key presses.

Key Points

• Key events allow keyboard interaction with the GUI.

• Use the .bind() method to link a function to a key event.

• The callback function receives an event object with:

o [Link] → Name of the key pressed

o [Link] → Numeric key code


• Useful for shortcuts, text input, or navigation.

1. Tkinter Architecture

Tkinter follows a layered architecture that connects Python programs with the Tk GUI toolkit.

Layers of Tkinter Architecture

1. Python Application
o This is the program written by the developer using Python.
o It contains instructions to create GUI components like labels, buttons, and text boxes.
2. Tkinter Module
o Tkinter acts as an interface between Python and the Tk toolkit.
o It converts Python commands into instructions that the Tk library understands.
3. Tk Toolkit
o Tk is a GUI toolkit written in C language.
o It provides the actual implementation of widgets such as buttons, menus, labels, etc.
4. Operating System
o The operating system finally displays the GUI window on the screen..

Thus , The Python program sends commands to Tkinter, Tkinter communicates with Tk toolkit, and the operating system
displays the GUI.

Simple Flow

Python Application

Tkinter Module

Tk Library (Tk Toolkit)

Operating System GUI

2. Program to Create a Login Form (Tkinter)

import tkinter as tk

def login():
username = entry_user.get()
password = entry_pass.get()
print("Username:", username)
print("Password:", password)

root = [Link]()
[Link]("Login Form")

[Link](root, text="Username").grid(row=0, column=0)


[Link](root, text="Password").grid(row=1, column=0)

entry_user = [Link](root)
entry_pass = [Link](root, show="*")

entry_user.grid(row=0, column=1)
entry_pass.grid(row=1, column=1)
login_btn = [Link](root, text="Login", command=login)
login_btn.grid(row=2, column=1)

[Link]()

Explanation:

• Label → displays text (Username, Password)

• Entry → input box for user data

• Button → performs login action

• grid() → arranges widgets in rows and columns

3. Widgets with Example

Widgets are GUI elements used to interact with the user.

Widget Purpose

Label Displays text

Button Performs an action when clicked

Entry Takes single-line input

Text Takes multi-line input

Checkbutton Allows multiple selections

Radiobutton Allows one option selection

Listbox Displays a list of items

Example

import tkinter as tk

root = [Link]()

label = [Link](root, text="Welcome")


[Link]()

entry = [Link](root)
[Link]()

button = [Link](root, text="Submit")


[Link]()

[Link]()

Explanation

• Label shows text

• Entry allows user input

• Button performs an action


4. Comparison of pack(), grid(), and place()

Feature pack() grid() place()

Layout Style Arranges widgets vertically or Arranges widgets in rows and Places widgets at specific
horizontally columns coordinates

Complexity Simple layout Structured layout Precise positioning

Usage Small/simple interfaces Forms and structured designs Custom GUI designs

Position Limited Moderate Exact control


Control

Example [Link]() [Link](row=0,column=1) [Link](x=50,y=40)

Python SQLite – Notes


1. The SQLite3 Module

• sqlite3 is a built-in Python module used to work with SQLite databases.


• It allows Python programs to create and manage databases easily.
• SQLite is a file-based database, meaning data is stored in a single .db file.
• It does not require any server, so it is very easy to use.
• The module supports all SQL commands like CREATE, INSERT, SELECT, UPDATE, DELETE.
• It is lightweight, fast, and suitable for small applications and projects.
• Provides useful methods like connect(), cursor(), execute(), and close() for database operations.

Python SQLite: Connection Object & Cursor Object


SQLite is a lightweight, serverless database built into Python using the sqlite3 module. To interact with a database, two main
objects are used:

1. Connection Object

2. Cursor Object

1. Connection Object

Definition

• The Connection object represents the connection between Python and the SQLite database.

• It is used to open, manage, and close the database.

• Every database operation requires an active connection.

• Created using [Link]("database_name.db").

• If the database does not exist, SQLite creates a new database file.

• Responsible for committing transactions (commit()) and closing the connection (close()).

Explanation

• [Link]() → Opens or creates a database file.

• conn → Connection object to manage the database.

• [Link]() → Closes the database connection.


2. Cursor Object

Definition

• The Cursor object is used to execute SQL queries and fetch data from the database.

• It acts as a pointer to traverse the database tables.

• Created from a connection object using [Link]().

• Executes SQL statements using execute() method.

• Retrieves query results using fetchone(), fetchall(), or fetchmany().

• Required for inserting, updating, deleting, or reading data.

1. [Link]() → Creates a cursor object.


2. [Link]() → Executes SQL commands.
3. [Link]() → Saves changes to the database.
4. [Link]() → Retrieves all rows from a query.

SQLite Methods
1. connect()

1. Used to connect to an SQLite database. If the file does not exist, it creates a new database.

2. Returns a connection object used for further operations.

3. Example: con = [Link]("[Link]")

2. cursor()

1. Used to create a cursor object. The cursor helps to execute SQL commands.

2. It acts as a middleman between the program and the database.

3. Example: cur = [Link]()

3. execute()

1. Used to run SQL queries such as CREATE, INSERT, SELECT, UPDATE, DELETE. Takes SQL command as a string.

2. Used for both modifying data and retrieving data.

3. Example: [Link]("SELECT * FROM Student")

4. close()

1. Used to close the database connection. Helps to save memory and prevent data corruption.

2. Must be called after all operations are completed.

3. Example: [Link]()

SQL Operations:
1. Connect to Database
• A database in SQLite is stored as a single .db file.
• The connect() method is used to create or open the database.
• If the database file name does not exist, SQLite creates it automatically.
• This is the first step before creating tables or inserting data.
• The connection object is used to perform all database operations.

Example: [Link]("file_name.db")

con = [Link]("[Link]")

2. Create Table

• To create a table, use the CREATE TABLE SQL command.

• A table stores data in rows and columns. Each table has columns with specific data types (like INTEGER, TEXT).

• Use [Link]() to save the table creation.

• If a table already exists, SQLite gives an error. To avoid this, use CREATE TABLE IF NOT EXISTS..

Example:

[Link]("CREATE TABLE IF NOT EXISTS Student(RollNo INTEGER, Name TEXT, Marks INTEGER)")

3. Insert Records

• Insert means adding new data (rows) into a table.


• We use the SQL command INSERT INTO to add values to specific columns

Example:

[Link]("INSERT INTO students (name, age) VALUES ('Rahul', 20)")

[Link]()

4. Select Records

• SELECT is used to retrieve and display data from the table..// Select is used to read or view data from the table.
• We use the SQL command SELECT to fetch specific columns or all columns.
• It helps us read and display stored information from the database.
• You can select all records or apply conditions using WHERE.
• fetchall() is used to get all rows

Example:

[Link]("SELECT * FROM students")

5. Update Records

• Update means changing or modifying existing data in a table.


• We use the SQL command UPDATE to change values in specific rows.
• It is used when you want to correct or edit stored information.
• Always use WHERE to avoid updating all rows by mistake.

Examples:

[Link]("UPDATE students SET age = 20 WHERE id = 1")

[Link]()
6. Delete Records

• DELETE means removing specific rows from a table.

• We use the SQL command DELETE to remove one or more rows.


• It permanently removes the data from the database.
• Always use a WHERE condition to avoid deleting all records.
• Useful for removing incorrect, old, or unnecessary data.

Example: [Link]("DELETE FROM students WHERE id = 3")

7. Drop Table

• DROP TABLE is used to remove the entire table permanently.

• It removes all the data and the table structure permanently.

• Once dropped, the table cannot be recovered unless recreated.

Example:

[Link]("DROP TABLE students")

[Link]()
MODULE 3

 NumPy (Numerical Python) is a Python library used for scientific and numerical. NumPy is widely used in data science,
machine learning, artificial intelligence, and scientific research because it performs calculations much faster than normal
Python lists.

 It provides a special data structure called ndarray (N-dimensional array) that is faster and more efficient than Python lists.

 NumPy arrays store data in continuous memory blocks, which improves performance.

 NumPy allows us to do math on whole arrays at once — we don’t need loops.


Example: a + b adds two arrays directly.

 It offers a large collection of mathematical, statistical, and linear algebra functions.

 NumPy is written in C and C++, which makes it much faster than native Python operations.

 It supports multi-dimensional arrays (1D, 2D, 3D, etc.), useful for matrices and scientific data.

 It provides easy functions to create arrays like:

• [Link]() [Link]() [Link]() [Link]() [Link]() [Link]()

Importing NumPy

Before using NumPy, it must be imported into the program.

import numpy as np

Here:

• numpy is the library name.

• np is a commonly used alias (short name).

Why NumPy arrays (ndarray)?


• ndarray is a homogeneous, fixed-type, N-dimensional container for numeric data.

• Stored in contiguous memory, so operations are fast (implemented in C).

• The ND Array is the main data structure of NumPy. It represents a collection of elements of the same
data type arranged in multiple dimensions.
• The term N-dimensional means the array can have any number of dimensions.

Types of ND Arrays

Array Type Description Example


1D Array A one-dimensional array similar to a list [1,2,3,4]
2D Array Two-dimensional array arranged in rows and columns (matrix) [[1,2],[3,4]]
3D Array Array containing multiple matrices [[[1,2],[3,4]]]

1. Creating Arrays from Python Lists and Tuples


• Arrays can be created from Python lists using the [Link]() function..

• A Python list can be converted into a NumPy array using [Link]().


• All elements in the array are stored in continuous memory locations.
• Elements usually have the same data type.
• It supports creation of 1D, 2D, or multi-dimensional arrays.
• This method is simple and commonly used for creating arrays.

1.
• It automatically detects dimensions:

o 1D → simple list

o 2D → list of lists

o 3D → nested lists

Example:

import numpy as np

a = [Link]([1, 2, 3, 4]) # 1D array

b = [Link]([[1, 2, 3],

[4, 5, 6]]) # 2D array (matrix)

c = [Link](((1,2),(3,4))) # created from tuple

2. Arrays of Zeros
• The zeros() function creates an array filled with zero values.
• It is useful when we need an empty structure to store values later.
• programmmer must specify the shape of the array (size, rows, columns).
• The default data type is float (0.0), but it can be changed.

• • zeros() creates arrays containing only 0 values.


• • It can create 1D or multi-dimensional arrays.
• • The size of the array must be specified. It is commonly used in scientific computing and matrix
operations.

Examples: Arr = [Link]((3, 4)) # 3 rows, 4 columns filled with 0

-------------------------------- 3. Creating Arrays with a Specific Value


• [Link]() creates an array filled with a user-defined constant value.
• user must provide the Shape and fill value must be specified.
• Useful for simulations and mathematical algorithms.
• Supports both integer and floating values.
• Provides a quick method to create predefined-value matrices.

Example: Arr = [Link]((2, 2), 7) # 2x2 array filled with value 7

4. Creating Arrays of Ones ([Link]())


• [Link]() creates an array where all elements are 1.
• It is similar to [Link]() but filled with the value 1.

• It supports multi-dimensional arrays.


• The dimensions must be specified in the function.
• It is useful for testing and initializing matrices.
• It is commonly used in data analysis and machine learning.
• Default data type is float, but can be set to int.
• Useful for initializing values in algorithms (e.g., adding bias).
• Works faster than manually filling arrays with loops.

Example: arr = [Link]((3, 2))


5. Creating Empty Arrays
1. [Link]() creates an array without initializing the values.

2. The elements contain random garbage values in memory.

3. It is extremely fast because it does not fill any value.

4. Useful when you plan to overwrite the array entirely later.

5. Should be used carefully to avoid unexpected results.

6. Works best for performance-critical applications.

Example:

arr = [Link]((3, 3))

6. Using arange() — Like Python Range


• The arange() function creates arrays with values in a specific range.
• arange() generates numbers within a given range.
• The syntax is [Link](start, stop, step).
• The start value indicates the beginning of the sequence.
• The stop value indicates the end of the sequence (not included).
• The step value determines the interval between numbers.

Example: [Link](0, 10, 2) # [0, 2, 4, 6, 8]

7. Using linspace() — Evenly Spaced Values


• [Link]() creates evenly spaced values between a start and end point.
• Unlike arange(), you specify how many values you want.
• Widely used in data visualization and graphs.
• Helps divide a range into equal parts.
• Supports float precision and gives accurate spacing.
• Very useful in scientific and mathematical calculations.

Example: [Link](0, 1, 5)

# Output: [0. 0.25 0.5 0.75 1.0]

8. [Link]() – Identity Matrix


• Creates a square matrix with diagonal elements = 1 and others = 0.
• It is extremely important in mathematics and linear algebra.
• [Link]() creates this matrix directly without loops.
• Mostly used in matrix operations and solving equations.
• Helps in matrix multiplication and finding inverses.
• Saves time compared to writing nested loops.

Example: [Link](4) # 4x4 identity matrix


OPERATIONS ON ARRAYS (NumPy)

NumPy provides powerful operations to work efficiently with arrays. These operations allow fast calculations, data access, and
shape manipulation, which are widely used in data analysis and scientific [Link] operations are fast because
NumPy uses optimized C code.

1. Arithmetic Operations (+ , − , × , ÷ , %, //, **)

Arithmetic operations allow mathematical calculations on arrays such as addition, subtraction, multiplication, and division.

1. These operations are applied element-wise on arrays.

2. Arrays must have same shape or NumPy will use broadcasting.

3. Can be performed between two arrays or array and scalar.

4. Faster than Python loops. Improves performance in numerical computing.

5. Returns a new array, original remains unchanged.

6. • Operations are performed element by element.


7. • NumPy arrays support vectorized calculations.
8. • These operations are faster than Python list operations.
9. • They are widely used in scientific and numerical computations.

Code Example

import numpy as np

a = [Link]([10, 20, 30])

b = [Link]([2, 4, 6])

print(a + b) # Addition

print(a - b) # Subtraction

print(a * b) # Multiplication

print(a / b) # Division

2. Indexing in NumPy Arrays

Indexing is used to access individual elements of an array using their position.

• • Each element in an array has an index position.


• • Indexing starts from 0.
• • Negative indexing accesses elements from the end of the array.
• • In 2D arrays, both row and column indexes are used.
• • Indexing allows users to retrieve or modify values.

Code Example

import numpy as np

arr = [Link]([5, 10, 15, 20])

print(arr[0])

print(arr[2])

print(arr[-1])

Explanation:→ arr[0] → First element. arr[2] → Third element. arr[-1] → Last element.
3. Slicing in NumPy Arrays

Array slicing means extracting a part (subset) of an array instead of using the full array.

• Slicing is used to access a range of elements from an array.


• It is done using colon (:) notation.
• Syntax format:
array[start : stop : step]
• Start index → where slicing begins (inclusive).
• Stop index → where slicing ends (exclusive).
• Step → gap between elements (optional).
• Works for 1D, 2D, and multi-dimensional arrays.
• Slicing does not copy data, it creates a view of the original array..
• Useful in data analysis and preprocessing. Avoids unnecessary loops.  Makes code short and efficient.

Code Example

import numpy as np

arr = [Link]([10, 20, 30, 40, 50])

print(arr[1:4])

print(arr[:3])

print(arr[0:5:2])

Explanation

• arr[1:4] → Elements from index 1 to 3. # [20 30 40]

• arr[:3] → First three elements.

• arr[0:5:2] → Every second element. # [10 30 50]

4. Reshaping NumPy Arrays

Reshaping changes the shape (rows and columns) of an array without changing its data.

• Reshaping changes rows and columns, not values.


• It is Done using the reshape() method.
• The Total number of elements must remain same.
• Used to convert 1D to 2D, 2D to 3D, etc.
• -1 can be used to let NumPy automatically calculate size.
• Very useful in machine learning and data analysis.
• Original array data order is preserved.  It helps organize data into rows and columns.
•  It is widely used in data processing and machine learning.

Code Example

import numpy as np

arr = [Link]([1, 2, 3, 4, 5, 6])

new_arr = [Link](2, 3)

print(new_arr)

Output

[[1 2 3]

[4 5 6]]
Introduction to Pandas
 Pandas is a Python library used for data analysis and data manipulation.

 It provides two main data structures: Series (1D) and DataFrame (2D).

 Pandas makes it easy to clean, filter, sort, and transform data.

 It can read and write data from CSV, Excel, SQL, JSON, and many other formats.

 It is built on top of NumPy, making it fast and efficient for large datasets.

 Pandas is widely used in Data Science, Machine Learning, and Data Analytics.

 It allows operations like grouping, merging, joining, and aggregation.

 It helps convert raw data into meaningful insights with simple commands.

1. Pandas Series –
A Series is a one-dimensional labeled array capable of holding any data type (integer, float, string, etc.). Each element in a
Series has an index that labels it. It is part of a DataFrame structure.

Key Characteristics of a Series

1. One-dimensional: Holds data in a single row or column.

2. Indexing: Each element has an index (default is integers starting from 0, but you can set custom labels).

3. Holds any data type: Integers, floats, strings, Python objects, etc.

4. Immutable size: You can change values but not the size of the Series.

2. Pandas DataFrame –
A DataFrame in pandas is a two-dimensional labeled data structure with rows and columns. It is similar to a table in a
spreadsheet or a SQL table. DataFrames can be created from multiple sources like Excel files, CSV files, dictionaries, and
tuples.

Key Characteristics of DataFrame

1. Two-dimensional: Rows and columns.

2. Heterogeneous data: Each column can have a different data type.

3. Labeled axes: Both rows and columns can have labels.


4. Size mutable: You can add or remove rows/columns.

5. Supports operations: Like selection, filtering, aggregation, and joins.

Creating DataFrames from Excel Sheet and .CSV File


Pandas allows us to create DataFrames from different data sources such as Dictionary, List of Tuples, CSV files, and Excel files.
These methods help in loading and organizing data in tabular form for analysis.

Creating DataFrame from an Excel Sheet


Excel files are spreadsheets that may contain multiple sheets (tabs). Data is stored in tabular form with cells organized into
rows and columns.. Pandas provides the read_excel() function to load this data into a DataFrame.

Syntax: df = pd.read_excel('[Link]', sheet_name='Sheet1')

import pandas as pd

data = {

"Name": ["John","Anna","Mike"],

"Age": [20,21,19]

df = [Link](data)

print(df)

Parameters:

Parameter Description

'[Link]' Name of the Excel file

sheet_name (Optional) Name of the sheet to read

Note: Reading Excel files usually requires the openpyxl library internally.

Importance of Creating DataFrame from Excel

1. Multiple Sheets – Can read data from different sheets in the same file.

2. Well-Formatted Data – Excel supports formatting, formulas, and headers.

3. User-Friendly Source – Many users store data in Excel for simplicity.

4. Supports Complex Data – Useful for business reports and structured tables.

5. Better Organization – Data can be grouped and arranged neatly.

Creating DataFrame from a CSV File


A CSV (Comma Separated Values) file stores tabular data in plain text, where each value is separated by a comma. It is widely
used for data storage and exchange due to its simplicity and compatibility. Pandas provides the read_csv() function to load CSV
files into a DataFrame

Syntax: df = pd.read_csv('[Link]')

Important Notes:

• It automatically reads column names from the first row. It loads data faster than Excel due to its simple text format.

Importance of Creating DataFrame from CSV


1. Easy to Use – CSV files are simple text files and load very quickly.

2. Widely Supported – Almost all software and databases export data in CSV format.

3. Lightweight – File size is small, ideal for large datasets.

4. Faster Processing – Reading CSV is faster compared to Excel.

5. Good for Data Exchange – Easy to share between systems and platforms.

Example
import pandas as pd

df = pd.read_csv('[Link]')
print(df)

Creating DataFrame from a Dictionary


A dictionary is a data structure that stores data in key–value pairs. Each key is unique, and represents a column name and
each value represents the column data..

• Each Keys must be unique and cannot be changed (immutable). Values can be any data type (numbers, strings, lists,
etc.).
• Dictionaries are unordered collections (do not follow indexing like lists).
• Data is accessed using keys, not index.
• Dictionary is mutable, meaning data can be added, removed, or changed.
• Created using curly braces {}.

Importance of Dictionary

• Useful for fast access to data using keys.

• Ideal for structured data like student records, product details, etc.

Syntax:

df = [Link](data/dictionary)

Example:

import pandas as pd

data = {

'Name': ['Alice', 'Bob', 'Charlie'],

'Age': [25, 30, 35],

'City': ['New York', 'Los Angeles', 'Chicago']

df = [Link](data)

print(df)

Creating DataFrame from List of Tuples


A tuple is an ordered and immutable collection of elements. A list of tuples can be converted into a DataFrame where each
tuple represents a row.

• Each tuple represents one row in DataFrame.


• Column names must be provided separately.
• Faster than lists due to immutability..
• Elements can be of different data types.
• Uses parentheses ( ) for declaration.
• Supports indexing and slicing like lists.
• Faster than lists because it is fixed (immutable).

Importance of Tuple

• Best for storing constant or fixed data that should not change.

• Improves performance due to immutability.

Syntax

df = [Link](data, columns=[...])

Example

import pandas as pd

data = [

('Alice', 25, 'New York'),

('Bob', 30, 'Los Angeles'),

('Charlie', 35, 'Chicago')

df = [Link](data, columns=['Name', 'Age', 'City'])

print(df)

Data Inspection in Pandas

Data inspection is the process of examining and understanding the structure and content of a dataset before performing
analysis.
In Pandas, several built-in functions help users quickly view the data, check its structure, and understand important statistical
information.

Data inspection is important because it helps to:

• Understand the size and structure of the dataset

• Identify missing values or incorrect data

• View sample records from the dataset

• Understand data types of each column

• Perform initial data analysis

Pandas provides useful functions such as head(), tail(), info(), and describe() for data inspection.

Simple Diagram

Dataset (DataFrame)

┌─────┼─────┐
│ │ │
head() tail() info()

describe()

These functions help in exploring and understanding the dataset.


1. head() Function

The head() function is used to display the first few rows of a DataFrame.

By default, it shows the first 5 rows of the dataset.

Syntax

[Link]()

Example

import pandas as pd

data = {
"Name": ["John","Anna","Mike","Sara","Tom"],
"Age": [20,21,19,22,23]
}

df = [Link](data)

print([Link]())

Output

Name Age
0 John 20
1 Anna 21
2 Mike 19
3 Sara 22
4 Tom 23

Important Points

1. Displays the top rows of the dataset.

2. Default output is first 5 rows.

3. Helps to quickly preview the dataset.

4. Useful for checking if data is loaded correctly.

5. You can specify number of rows.

Example:

[Link](3)

2. tail() Function

The tail() function displays the last few rows of a DataFrame.

By default, it shows the last 5 rows.

Syntax

[Link]()

Example

[Link]()

Output
Name Age
0 John 20
1 Anna 21
2 Mike 19
3 Sara 22
4 Tom 23

Important Points

1. Displays the last rows of the dataset.

2. Default output shows 5 rows.

3. Useful for checking end of the dataset.

4. Helps verify if data is complete and correctly loaded.

5. Can also display a specific number of rows.

Example:

[Link](2)

3. info() Function

The info() function provides summary information about the DataFrame.

It shows details about:

• Number of rows and columns

• Column names

• Data types

• Non-null values

Syntax

[Link]()

Example

[Link]()

Example Output

<class '[Link]'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 2 columns):
Name 5 non-null object
Age 5 non-null int64

Important Points

1. Displays structure of the dataset.

2. Shows number of rows and columns.

3. Displays data type of each column.

4. Shows non-null values (missing data).

5. Helps identify data quality issues.


4. describe() Function

The describe() function generates a statistical summary of numerical columns.

It provides important statistics such as:

• count

• mean

• standard deviation

• minimum value

• maximum value

Syntax

[Link]()

Example

[Link]()

Example Output

Age
count 5.0
mean 21.0
std 1.58
min 19.0
max 23.0

Important Points

1. Provides statistical summary of data.

2. Works mainly with numeric columns.

3. Shows count, mean, standard deviation.

4. Displays minimum and maximum values.

5. Helps understand data distribution.


Data Visualization
• Data Visualization is the process of representing data in visual form like graphs, charts, and plots.
• It helps in understanding trends, patterns, and relationships in data quickly and easily. Instead of reading large tables
of numbers, visualization helps users quickly analyze information through visual representation.
• Data visualization is widely used in data analysis, business reports, scientific research, and machine learning to make
data easier to interpret..
• It is used to Supports both categorical data (e.g., bar chart) and numerical data (e.g., line chart, histogram).
• Makes analysis interactive and user-friendly when combined with tools like Python or Excel.

Importance of Data Visualization

1. Simplifies Complex Data


Large and complicated datasets become easier to understand using visual charts and graphs.
2. Shows Patterns and Trends
Visualization helps identify patterns and trends in data over time.
3. Improves Decision Making
Businesses use visual data to analyze performance and make better decisions.
4. Saves Time
Graphs provide quick understanding compared to reading large tables of numbers.
5. Improves communication
Data can be presented clearly to others using visual charts formats.
6. detect errors or outliers
 Unusual values or mistakes in data can be easily identified through graphs.
7. Used in Many Fields
Data visualization is widely used in finance, healthcare, marketing, science, and business.

1. Supports data analysis


Analysts use visualization tools to explore datasets.

Data visualization helps transform complex data into simple visual representations, making analysis and decision-making
easier
1. Matplotlib

Matplotlib is a popular Python library used for creating charts, graphs, and visualizations from data.
It helps represent numerical data in graphical form for better understanding.

Key Points

1. It is widely used for data visualization in Python.

2. It can create different types of graphs like line, bar, pie, and histogram.

3. It works well with NumPy and Pandas data.

4. It is mainly used in data analysis and scientific computing.

5. The most commonly used module is pyplot.

Import Syntax

import [Link] as plt

2. Pyplot

Pyplot is a module of Matplotlib that provides functions to create and control graphs easily.

Key Points

1. Pyplot provides functions like plot(), bar(), hist(), pie().

2. It helps display graphs using show().

3. It allows adding titles, labels, and legends.

4. It makes graph creation simple and interactive.

5. It is imported as plt.

Example

import [Link] as plt

x = [1,2,3]
y = [10,20,30]

[Link](x,y)
[Link]()

DIFFERENT TYPES OF CHARTS USING PYLOT

To use any chart in Python, first import Pyplot: import [Link] as plt

LINE CHART
A Line Chart is a type of graph that displays data points connected by straight lines. A line chart shows the relationship
between two variables and is mainly used to display trends over time.
It is used to show changes, trends, or progressions over a continuous period.

Key Features

• Displays continuous data


• • Points are connected using lines.
• • Used in sales, temperature, and stock market analysis.
• • Created using plot() function.

BAR CHART

A bar chart is used to compare values between different categories or group . A Bar Chart uses rectangular bars to represent
data.

A Vertical Bar Chart displays bars vertically. The categories are shown on the X-axis, and the values are shown on the Y-axis.

A Horizontal Bar Chart displays bars horizontally. The categories are shown on the Y-axis, and the values are shown on the X-
axis.

Key Points

• Uses rectangular bars.


• Each bar represents a category.
• Height of bar shows value.
• Used for comparison of data.
• Created using bar() functions
HISTOGRAM

A Histogram is a graphical representation that shows the frequency distribution of continuous data.
The data is divided into bins (intervals), and each bar shows how many values fall in each bin.

Key Features

 Displays frequency of data values.

 Groups data into intervals (bins).

 Useful for statistical analysis.

 Shows data distribution clearly.

 Created using hist().

PIE CHART

A Pie Chart is a circular graph divided into slices, where each slice represents a percentage of the whole dataset.

Key Points

1. Data shown as circular slices.

2. Each slice represents a percentage.

3. Useful for showing proportions.

4. Easy to understand visually.

5. Created using pie() function.

Example Code

import [Link] as plt

labels = ["Python", "Java", "C", "C++"]

sizes = [40, 25, 20, 15]

[Link](sizes, labels=labels)

[Link]()
Chart Type Definition Best Use

Line Chart Connects data points with lines to show trends Time-series data

Bar Chart Uses bars to compare categories Category comparison

Histogram Shows frequency distribution by using bins Distribution analysis

Pie Chart Circular chart showing percentage of whole Percentage composition

Comparison / Relational Operations

(==, !=, >, <, >=, <=)

1. Compares elements one-by-one between arrays. Returns a Boolean array (True/False). Useful for filtering and
conditional selection. Can compare array-to-array or array-to-scalar. Helps find values meeting certain conditions (ex:
>30).

Logical Operations (logical_and, logical_or, logical_not)

1. Works on Boolean arrays created from comparisons. Used to combine multiple conditions. Returns a Boolean array.
More efficient than Python logical operators. Useful for filtering data with complex rules.

Aggregation Operations (sum, min, max, mean, std, var)

Perform operations that combine all values. Used for statistics like mean, sum, highest, lowest. Can apply on entire array
or specific axis. Very fast and optimized. Output is usually a single number (scalar).

Shape & Reshaping Operations(reshape, ravel, flatten, transpose)

Change the shape of an array without altering data. reshape() creates new dimensions. ravel() and flatten() convert array
to 1D. transpose() swaps rows and columns. Important for matrix operations and ML data.

Concatenation & Splitting(concatenate, vstack, hstack, split)

Used to join and divide arrays. concatenate() joins arrays along an axis. vstack() stacks arrays vertically. hstack() stacks
arrays horizontally. split() divides arrays into equal parts.

Matrix Operations (dot, matmul, transpose, inverse)

Used for linear algebra applications. dot() performs matrix multiplication. Very fast due to optimized math libraries. Used in
ML, graphics, scientific calculations. Supports determinant, inverse, eigenvalues (via linalg).

You might also like