Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
71 views

Complete Python Notes

Uploaded by

mevi.programs
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views

Complete Python Notes

Uploaded by

mevi.programs
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 173

Python Notes By Mevi Technologies LLP

Chapter 0: Introduction To Programming


(😊cause index starts from 0)

What is a Program?

A program is a collection of written instructions that tell a computer


how to perform specific tasks. These instructions are written in a

LP
programming language that is either human-readable (high-level
language) or closer to machine code (low-level language).

sL
ie
Why Do We Need Programs?
og
● Computers are powerful tools, but they do not have intelligence
or decision-making capabilities. They rely entirely on programs
ol

to perform tasks.
hn

● Programs help in automating repetitive tasks, solving complex


problems, or performing actions faster and more accurately than
ec

humans.
iT

How Programs Work


ev

● A programmer writes a program in a specific language, such as


M

Python, Java, or C.
● The program is then translated into machine code (binary) using
a compiler or an interpreter.
● Once the program is converted, the computer executes the
instructions.

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

Examples of Programs

1. Simple Calculator: A program that takes two numbers as input,


adds them, and displays the result.

# Example in Python

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

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

print("The sum is:", num1 + num2)

sL
Instruction: The program asks the user to input two numbers,
calculates their sum, and displays the result.

ie
Gaming Programs: Games like Chess or PUBG have programs
og
controlling everything, from player movements to game rules.
ol

Robotics Programs: Instructions that guide a robot to perform tasks


hn

like moving or lifting objects.


ec

What is an Application?
iT

An application is software designed to perform a specific function or


ev

task for the user. Applications are built by combining multiple


programs.
M

Why Are Applications Important?


● They simplify complex tasks for users.
● Applications provide user-friendly interfaces for interacting

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

with the underlying programs.

Types of Applications

1. Mobile Applications: Apps designed to run on mobile devices.

Examples: WhatsApp for messaging, Instagram for social media.

LP
2. Web Applications: Programs that run in a web browser and require
an internet connection

sL
Examples: Gmail for email, YouTube for streaming videos.

ie
3. Desktop Applications: Software installed on a computer.
og
Examples: Microsoft Word for document creation, VLC Player for
ol

watching videos.
hn

How Applications Work?


ec

● Applications are built using a combination of front-end (user


iT

interface) and back-end (logic and database).


● The front-end interacts with the user, while the back-end
ev

performs the tasks and retrieves data.


M

Example: Calculator Application


Front-End: Displays buttons for numbers and operations (e.g.,
addition, subtraction).
Back-End: The program processes user input, performs the
calculation, and displays the output.
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

What is Software?

Software is the collection of applications and system-level tools that


enable a computer to perform tasks. It acts as a bridge between users
and hardware, providing instructions to the hardware to perform
specific functions. Without software, hardware is just a set of
components without any functionality.

LP
Why is Software Important?

sL
● Functionality: Enables hardware to perform operations.
● User Interaction: Provides interfaces for users to interact with
ie
the system (e.g., a mouse click or keyboard input).
og
● Automation: Automates repetitive and complex tasks, making
systems efficient and reliable.
ol
hn

Types of Software
ec

Software can be classified into several categories based on its


iT

functionality and usage:


ev

1. System Software

System software provides the foundation for application software by


M

managing the hardware and system resources.

Subtypes of System Software:


● Operating Systems (OS): Manage hardware resources and
provide a platform for applications to run.
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

○ Examples: Windows, Linux, macOS.


○ Functions: Task scheduling, memory management,
file handling.
● Utility Software: Maintains and optimizes system
performance.
○ Examples: Disk Cleanup, Antivirus, Backup Tools.
○ Functions: Detect malware, clean up disk space,

LP
optimize speed.
● Device Drivers: Allow communication between the OS and

sL
hardware devices.
○ Examples: Printer Driver, Graphics Driver.
○ Functions: Translate OS commands into hardware
ie actions.
og
How It Works:
ol

When you open a file, the OS fetches it from the storage (via drivers)
hn

and displays it to the user.


ec

2. Application Software
iT

Application software consists of collections of programs designed to


ev

perform specific user tasks. They sit on top of system software and
depend on it to function.
M

● Subtypes of Application Software:


○ Desktop Applications: Installed and run on a computer
system.
■ Examples: Microsoft Word (document editing), VLC
Player (media playback).

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

○ Web Applications: Operate in a browser and require an


internet connection.
■ Examples: Gmail (email), Google Docs (collaborative
editing).
○ Mobile Applications: Designed for mobile devices like
smartphones and tablets.
■ Examples: WhatsApp (messaging), Instagram (social

LP
media).
○ Enterprise Applications: Cater to organizational needs,

sL
managing large-scale data or operations.
■ Examples: SAP (enterprise resource planning),

ie Salesforce (customer relationship management).


○ Game Applications: Focus on entertainment and gaming.
og
■ Examples: PUBG, Chess.
ol

How Applications Work:


hn

Front-End: User interface that interacts with the user.


ec

Back-End: Logic and database processing user inputs.


iT

Example: In a Calculator app:


● The front-end displays buttons for numbers
ev

● The back-end processes inputs, performs calculations, and


returns results.
M

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

LP
sL
ie
What is ASCII?
og
ASCII (American Standard Code for Information Interchange) is a
ol

character encoding standard used to represent text in computers and


hn

other devices that work with text. ASCII assigns numbers to


characters, making it possible for computers to understand and
ec

display text. It uses 7 bits to represent each character, allowing it to


store 128 characters in total.
iT

These 128 characters include:


ev

1. Control Characters: These are non-printable characters that


control the flow of data. Examples include:
M

a. Line feed (LF), which creates a new line.


b. Tab (TAB), which adds a horizontal space.
c. Return (CR), which moves the cursor to the beginning of
the line.
2. Printable Characters: These characters can be displayed as text

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

on a screen. They include:


a. Letters (uppercase and lowercase): A, B, C,..., Z and a, b,
c,..., z.
b. Digits: 0, 1, 2, ..., 9.
c. Punctuation Marks: ., ?, !, :, ;, @, #, etc.
d. Space: Represents an empty space between words.

LP
Examples:

sL
● The letter A in ASCII is represented by the number 65 in
decimal, which is 01000001 in binary.
ie
● The digit 5 is represented by the number 53 in decimal, which is
og
00110101 in binary.
● A space is represented by the number 32 in decimal, which is
ol

00100000 in binary.
hn
ec

How Does a Computer Understand Humans?


iT

Computers do not inherently understand human languages, gestures,


or emotions. They rely on a multi-layered process to interpret our
ev

inputs, such as text typed on a keyboard, mouse movements, or voice


commands. Let’s break it down step by step in the context of
M

keyboard input, involving binary, electrical signals, and encoding


standards like ASCII.

1. Input Through the Keyboard


When you press a key on the keyboard:
● The keyboard acts as an input device.
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

● Each key is associated with a specific electrical circuit.


● Pressing a key completes the circuit, sending an electrical
signal to the computer.

2. Electrical Signals
Computers operate using electrical signals:
○ ON state (1): Current flows.
○ OFF state (0): No current flows. These ON and OFF states

LP
form the foundation of the binary system, which uses only
two symbols: 0 and 1.

sL
When you press a key:
○ A specific electrical signal is generated based on the key’s
ieposition and the circuit it completes.
og
○ This signal travels from the keyboard to the computer’s
keyboard controller via the USB or PS/2 interface.
ol
hn

3. Scan Codes
The keyboard controller translates the electrical signal into a scan
ec

code:
iT

● A scan code is a unique identifier for each key on the


keyboard.
ev

● For example:
○ Pressing the 'A' key generates a scan code (e.g., 0x1E
M

in hexadecimal).
The scan code is then sent to the computer’s operating system for
further interpretation.

4. Conversion to Binary
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

The computer converts the scan code into binary code:


● Binary is the computer's native language, consisting of 0s
and 1s.
● Example:
○ The scan code for 'A' (e.g., 0x1E) is converted to its
binary equivalent: 00011110.

LP
5. ASCII and Other Encoding Standards
Once the scan code is converted to binary, it is mapped to a

sL
character using encoding standards like ASCII.
● ASCII (American Standard Code for Information
ieInterchange):
og
○ A widely-used encoding system that assigns a unique
numerical value to characters, symbols, and control
ol

keys.
hn

○ Example:
■ The letter 'A' in ASCII is represented as 65 in
ec

decimal, which is 01000001 in binary.


■ The space character (' ') is represented as 32 in
iT

decimal, or 00100000 in binary.


Other encoding standards include Unicode (for multilingual text)
ev

and UTF-8 (a web-friendly encoding).


M

6. Processing by the Computer


The operating system and applications interpret the binary data:

1. System Level: The OS recognizes the binary data as a specific


character (e.g., 'A').
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

2. Application Level: The application (e.g., a text editor) displays the


character on the screen.
For example:

● When you type "Hello," the keyboard sends the corresponding


binary data for 'H', 'e', 'l', 'l', and 'o'.
● The text editor processes this binary data and renders the letters
"Hello" on the screen.

LP
sL
Example: Typing the Letter 'A'

ie
1. Key Press: Pressing the 'A' key completes an electrical circuit.
og
2. Signal: The circuit generates an electrical signal corresponding to
the key’s scan code.
ol

3. Scan Code: The keyboard controller sends the scan code for 'A'
hn

(e.g., 0x1E) to the computer.


ec

4. Binary Conversion: The scan code is converted into binary (e.g.,


00011110).
iT

5. ASCII Mapping: The binary code is matched with its ASCII value
ev

(65 for 'A').

6. Processing: The computer processes the input and displays 'A' on


M

the screen.

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

Why Do Computers Use Binary?

Computers are built on digital circuits:

● These circuits use transistors, which can only detect two states:
ON and OFF.
● Binary aligns perfectly with this two-state system, allowing
efficient processing and storage of data.

LP
sL
How the Computer Understands User Input Using ASCII
● The keyboard sends a unique scan code for each key pressed.

ie
● This scan code is converted to binary.
● The computer uses ASCII to map that binary code to a character
og
(like "A", "5", or "space").
ol

● Finally, the computer processes the ASCII value and displays the
corresponding character on the screen.
hn

Thus, the ASCII encoding system helps the computer convert your
ec

keyboard input into characters it can understand and display.


iT
ev
M

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

LP
sL
ie
og
ol
hn
ec

Summary of the Process


iT

Step Description
ev

1. Key Press User presses a key, completing an electrical


circuit.
M

2. Electrical Signal Signal travels to the computer, representing


the key press.

3. Scan Code The keyboard controller generates a unique


scan code for the pressed key.

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

4. Binary The scan code is converted to binary format


Conversion for the computer to understand.

5. ASCII Mapping Binary is mapped to an ASCII value to


represent the character.

6. Processing The operating system and applications


process the input and display the result.

LP
sL
Other Input Scenarios

ie
While the above explanation focuses on keyboards, similar processes
apply to other input devices:
og
● Mouse: Sends positional data and click events as binary signals.
ol

● Microphone: Converts sound waves into digital signals using


hn

sampling and encoding.


● Touchscreens: Detect touch points and convert them into binary
ec

positional data.
iT

By following these steps, computers bridge the gap between


human-readable inputs and machine-understandable binary data.
ev
M

Example of Emoji Encoding in UTF-8, UTF-16, and UTF-32

Let's take the emoji 😊 (Smiling Face with Smiling Eyes) as an


example and see how it is encoded in UTF-8, UTF-16, and UTF-32.

Emoji: 😊 (Smiling Face with Smiling Eyes)


www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

😊 is U+1F60A. This code point is the same in all UTF


This emoji is represented by a Unicode code point. The Unicode code
point for
encodings, but the number of bytes used to represent this emoji varies
depending on the encoding.

UTF-8 Encoding:

LP
😊:
UTF-8 is variable-length and uses 1 to 4 bytes to represent a
character. For

sL
● Unicode Code Point: U+1F60A (decimal 128522)

ie
● UTF-8 Representation: The emoji 😊 is represented in UTF-8 by
the following 4 bytes:
og
■ 0xF0 0x9F 0x98 0x8A

😊 in UTF-8 requires 4 bytes to store.


ol

This means
hn
ec

Why 4 bytes?
iT

UTF-8 uses the following rules for encoding characters:

● Characters that are within the ASCII range (0-127) take 1 byte.
ev

● Characters that are outside the ASCII range, like emojis, take
M

more bytes (2, 3, or 4 bytes).

For 😊 (Unicode U+1F60A), since it is outside the ASCII range, it


takes 4 bytes in UTF-8.

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

UTF-16 Encoding:

UTF-16 is also variable-length but uses 2 bytes for most common


characters. If the character is outside the Basic Multilingual Plane
(BMP), UTF-16 uses 4 bytes (2 "surrogate pairs").

For 😊:
● Unicode Code Point: U+1F60A
😊 is represented in UTF-16

LP
● UTF-16 Representation: The emoji
by the following 4 bytes (using surrogate pairs):

sL
■ 0xD83D 0xDE0A

ie
In this case, UTF-16 uses 2 16-bit units (surrogate pairs) to represent
the emoji, totaling 4 bytes.
og
ol

Why 4 bytes?
hn

The Unicode code point U+1F60A is outside the BMP (Basic


ec

Multilingual Plane), so it requires 4 bytes in UTF-16 (using surrogate


pairs).
iT
ev

UTF-32 Encoding:
M

UTF-32 is fixed-length and uses 4 bytes for every character, regardless


of its complexity.

For 😊:
Unicode Code Point: U+1F60A
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

UTF-32 Representation: The emoji 😊 is represented in UTF-32 by


the following 4 bytes:

0x0001F60A

In this case, UTF-32 uses 4 bytes directly to store the emoji.

LP
Why 4 bytes?

UTF-32 always uses 4 bytes (32 bits) to represent each character, even

sL
if the character is simple and could be represented in fewer bytes by
other encodings.
ie
og
Summary of Emoji Encoding in Different UTF Formats
ol

Encoding Emoji Code Point Bytes Used Hex


hn

Representation

😊
ec

UTF-8 U+1F60A 4 bytes 0xF0 0x9F 0x98 0x8A

😊
iT

UTF-16 U+1F60A 4 bytes 0xD83D 0xDE0A

UTF-32 😊 U+1F60A 4 bytes 1F60A


ev
M

Conclusion:

😊 is represented with 4 bytes.


UTF-8: The emoji

UTF-16: The emoji 😊 is also represented with 4 bytes, but it uses


surrogate pairs.
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

UTF-32: The emoji 😊 is represented with 4 bytes because UTF-32


uses a fixed-length encoding.

Why Emojis Use More Bytes:

Emojis are often part of the Supplementary Multilingual Plane of


Unicode, meaning they have higher code points (above U+FFFF). This

LP
is why they need more bytes in encoding formats like UTF-8 and
UTF-16. UTF-32, on the other hand, uses 4 bytes for every character,

sL
making it simpler but less efficient for these emojis compared to
UTF-8 and UTF-16.
ie
Size of UTF-8, UTF-16, and UTF-32 Encodings
og
The size of each encoding varies based on the character being
ol

represented. Here's a detailed explanation of the sizes for each


hn

encoding scheme:
ec

UTF-8:
iT

Variable Length: UTF-8 uses 1 to 4 bytes per character, depending on


ev

the character’s Unicode code point.


M

ASCII characters (code points U+0000 to U+007F) use 1 byte.

Extended characters (code points U+0080 to U+07FF) use 2 bytes.

Even more extended characters (code points U+0800 to U+FFFF) use 3


bytes.

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

Characters above U+FFFF (Supplementary Multilingual Plane, like


emojis) use 4 bytes.

Example:

ASCII character A: 1 byte (0x41)

Emoji 😊 (U+1F60A): 4 bytes (0xF0 0x9F 0x98 0x8A)

LP
Summary for UTF-8:

sL
1 byte for characters in the ASCII range (0–127).

ie
2 bytes for characters from U+0080 to U+07FF.
og
3 bytes for characters from U+0800 to U+FFFF.
ol

4 bytes for characters from U+10000 onward (e.g., emojis).


hn
ec

UTF-16:
iT

Variable Length: UTF-16 uses 2 bytes (16 bits) for most characters in
the Basic Multilingual Plane (BMP, code points U+0000 to U+FFFF).
ev

Characters outside the BMP (code points above U+FFFF) are


M

represented using 4 bytes (using surrogate pairs).

Example:

ASCII character A: 2 bytes (0x0041) in UTF-16.

Emoji 😊 (U+1F60A): 4 bytes (using surrogate pairs, 0xD83D

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

0xDE0A).

Summary for UTF-16:

2 bytes for characters in the BMP (0–65535).

4 bytes for characters outside the BMP (above U+FFFF, such as


emojis).

LP
UTF-32:

sL
Fixed Length: UTF-32 uses 4 bytes (32 bits) for every character,

ie
regardless of whether it's a simple ASCII character or a complex
character like an emoji.
og
No variable length: Every character takes exactly 4 bytes.
ol

Example:
hn

ASCII character A: 4 bytes (0x00000041) in UTF-32.

😊 (U+1F60A): 4 bytes (0x0001F60A).


ec

Emoji
iT

Summary for UTF-32:


ev

4 bytes for every character, no matter how simple or complex the


character is.
M

Comparison of Size (in Bytes):

Character UTF-8 UTF-16 UTF-32

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

ASCII character (A) 1 byte 2 bytes 4 bytes

Emoji ( 😊) 4 bytes 4 bytes 4 bytes

Character (汉) 3 bytes 2 bytes 4 bytes

Character (𐍈) 4 bytes 4 bytes 4 bytes

LP
Summary of Size for Each Encoding:

sL
UTF-8: Uses 1 to 4 bytes depending on the character.

UTF-16: Uses 2 bytes for most characters, 4 bytes for characters

ie
outside the BMP.
og
UTF-32: Uses 4 bytes for every character, making it simpler but less
efficient than UTF-8 and UTF-16 for memory usage.
ol
hn

Why Size Matters:


ec

UTF-8 is the most efficient for storing text in most languages,


iT

especially for English, since it uses only 1 byte for ASCII characters.
ev

UTF-16 is often used in systems where characters from non-Latin


scripts (like Chinese, Japanese, etc.) are common.
M

UTF-32 is useful when fixed-width encoding is needed, but it is less


memory efficient than UTF-8 or UTF-16.

What is a Compiler?
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

A compiler is a tool that translates code written in a high-level


programming language (like C or Java) into machine code (binary)
that a computer can directly execute.

The compiled output is typically stored as a binary file (e.g., .exe or


.out), which contains instructions in binary format for the computer.

The compiled program does not need the compiler to run again; it

LP
executes directly on the computer.

sL
How Does a Compiler Work?

ie
Source Code: The programmer writes human-readable code in a
og
language like C.
ol

Example:

# Example in Python
hn

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


ec

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


iT

print("The sum is:", num1 + num2)

● Compilation: The compiler translates the source code into binary


ev

(machine code).
● During this process, it performs syntax checking, optimization,
M

and translation.
● Execution: The computer executes the binary file directly.

What is an Interpreter?

An interpreter is a program that reads and executes code line by line,


www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

converting it into machine code that the computer can understand


and execute. Unlike a compiler, which translates the entire program
into machine code before execution, an interpreter processes the code
at runtime, which means it translates and executes one line at a time.

● No Intermediate Files: Interpreters don't generate an


independent machine code file like compilers do. They execute
the program directly.

LP
● Platform-independent: Since interpreters process the code at
runtime, the same source code can run on any machine that has

sL
the appropriate interpreter installed.
● Slower Execution: Since the code is translated line by line

ie
during execution, interpreted languages tend to be slower than
og
compiled languages.

Examples of interpreted languages include Python, JavaScript, and


ol

Ruby.
hn
ec
iT
ev

How Python Executes Programs (With Explanation of


Interpreter)
M

Python differs from compiled languages like C because it uses an


interpreter, not a compiler, to execute programs. Let’s understand
Python’s execution flow.

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

Step 1: Writing the Code

A programmer writes Python code in a text file with a .py extension.


For example:

# A simple Python program to add two numbers

# Example in Python

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

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

print("The sum is:", num1 + num2)

ie
og
Code Explanation:
ol

num1 = 10: Assigns the value 10 to the variable num1.


hn

num2 = 20: Assigns the value 20 to the variable num2.


ec

result = num1 + num2: Adds num1 and num2, storing the result in
iT

result.

print("The result is:", result): Prints the result to the screen.


ev

The code you write is human-readable, meaning it can be understood


M

by people but not directly executed by the computer because the


computer only understands binary (machine code).

Step 2: Python Interpreter Reads the Code (Line by Line)


www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

When you run the Python program, the Python interpreter takes over
and starts reading the code. The interpreter doesn’t process the entire
code at once. Instead, it processes the code line by line.

Example: num1 = 10

The interpreter reads the first line: num1 = 10.

The interpreter recognizes this as an instruction to store the value 10

LP
in the variable num1.

sL
The computer’s memory (RAM) is updated with this information, so
now there’s a place in memory that holds the value 10 under the
name num1.
ie
og
The interpreter does not execute this step directly; it prepares the
system to run this logic.
ol
hn

Step 3: Conversion to Bytecode


ec

After the interpreter reads a line, it converts the human-readable code


iT

into bytecode. Bytecode is an intermediate form of code that is


machine-independent (i.e., it can run on any platform as long as there
ev

is a Python interpreter).

What happens during bytecode conversion:


M

● Bytecode Generation: The interpreter translates the code into


bytecode instructions.
● Bytecode Example for num1 = 10:
● The line num1 = 10 would be converted to bytecode.

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

● Bytecode is a low-level representation of the code that can be


understood by the Python Virtual Machine (PVM).
● For this line, the bytecode may look something like:
● LOAD_CONST 10 # Load constant 10 into memory
● STORE_NAME num1 # Store it in the variable num1
● Storage of Bytecode: The generated bytecode is stored in
memory. If the program is executed again, the bytecode may be

LP
saved to a .pyc file (compiled Python file) in the __pycache__
folder.

sL
ie
Step 4: Python Virtual Machine (PVM)
og
The Python Virtual Machine (PVM) is responsible for executing the
bytecode generated by the interpreter. It is part of the Python runtime
ol

environment.
hn

How the PVM Works:


ec

The PVM interprets the bytecode and translates it into machine code
that the computer's CPU can understand.
iT

The machine code is in binary form (e.g., a sequence of 0s and 1s).


ev

The PVM executes the bytecode instructions one by one, performing


the necessary operations.
M

Example of Bytecode Execution:

The bytecode LOAD_CONST 10 tells the PVM to load the constant


value 10.

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

The PVM translates this bytecode into machine-level instructions that


the CPU can execute. It places the value 10 into memory at the
location where num1 is stored.

Next, the bytecode LOAD_CONST 20 would load the value 20, and
ADD would add num1 and num2 together.

For example, the PVM may execute

LP
LOAD_CONST 20 # Load constant 20

sL
BINARY_ADD # Add the two constants

STORE_NAME result # Store the result in 'result'

ie
og
The CPU executes the machine-level instructions generated by the
ol

PVM to carry out these operations.


hn

Step 5: Displaying the Output


ec
iT

After the program executes, it produces some output. For example,


when the Python program finishes adding num1 and num2, it will
ev

print the result to the screen.

Example Output:The result is: 30


M

How the Output is Displayed:

The result 30 is stored in the variable result.

The print() function sends this value to the computer’s display screen.

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

Each character in the output (like "The result is: 30") is encoded using
ASCII (or Unicode) encoding.

For example, "T" in ASCII is represented by the binary value


01010100.

The bytecode tells the PVM to print each character of the message to
the screen.

LP
When the PVM encounters the bytecode that corresponds to the
print() function, it knows to send the data to the output buffer, which

sL
eventually displays the message on the screen.

ie
og
Code Editors vs IDEs (Integrated Development
Environments)
ol

Both code editors and IDEs are essential tools for software
hn

development, but they serve different purposes and offer different


levels of functionality. Here's a detailed comparison:
ec
iT
ev

1. What is a Code Editor?


M

A code editor is a text editor designed specifically for writing and


editing code. It provides basic features like syntax highlighting, code
indentation, and simple text manipulation but doesn't come with
advanced tools like a compiler, debugger, or build automation
system. It's essentially a lightweight, simple tool for writing code.

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

Key Features of a Code Editor:

● Syntax Highlighting: Displays different parts of the code


(keywords, variables, functions) in different colors for easier
reading and understanding.
● Code Auto-completion: Suggests possible code completions
based on what you type.
● Basic Text Editing: Features like copy, paste, cut, find, and

LP
replace to edit the code.
● File Management: Helps you open, save, and manage multiple

sL
files at once.
● Extensions/Plugins: Some editors allow you to install plugins or
ie
extensions to add extra functionality, like version control
og
integration, linters, etc.
ol

Examples of Code Editors:

● Visual Studio Code (VS Code): A lightweight but feature-rich


hn

editor with extensions for many programming languages and


ec

tasks.
● Sublime Text: Known for its speed and simplicity, with many
iT

customizable features.
● Notepad++: A simple, free code editor for Windows that
ev

supports many programming languages.


● Pros of Code Editors:
M

● Lightweight: Code editors are fast and use fewer system


resources.
● Customizable: You can install plugins or extensions to add new
features.
● Simpler to Use: Great for smaller projects or quick edits.
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

Cons of Code Editors:

● Features: Lacks built-in debugging, compilation, or other


advanced features that come with IDEs.
● Requires Configuration: You may need to install extensions and
configure settings for specific languages or frameworks.

LP
sL
2. What is an IDE (Integrated Development Environment)?

An IDE is a comprehensive software application that integrates all the


ie
tools you need for software development into one platform. It is more
og
feature-rich than a code editor and often includes tools like a code
editor, compiler, debugger, build automation tools, and sometimes
ol

even version control systems.


hn
ec

Key Features of an IDE:


iT

● Code Editor: Like in a code editor, an IDE will have a text editor
with syntax highlighting, indentation, and auto-completion.
ev

● Compiler/Interpreter: It often includes a built-in compiler (for


compiled languages) or an interpreter (for interpreted
M

languages), allowing you to directly run your code within the


IDE.
● Debugger: An IDE often includes a powerful debugger to step
through your code, inspect variables, set breakpoints, and
identify errors.
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

● Build Automation: Some IDEs come with build tools for


compiling and packaging your code automatically.
● Version Control Integration: Many IDEs integrate with version
control systems like Git, making it easy to manage code changes.
● Project Management: IDEs can manage large projects with
multiple files, providing features like file explorers, build
configurations, and dependency management.

LP
sL
Examples of IDEs:

● PyCharm: A full-featured IDE for Python development, with


ie
integrated testing, debugging, and version control.
og
● Eclipse: Primarily for Java development but supports many
other languages with plugins.
ol

● IntelliJ IDEA: A Java-focused IDE that supports multiple


hn

languages and provides advanced code completion, refactoring,


and debugging tools.
ec

● Visual Studio: A comprehensive IDE for C++, C#, and other


languages.
iT
ev

Pros of IDEs:
M

● All-in-One Tool: Everything you need (code editing,


compilation, debugging, etc.) is integrated into one platform.
● Advanced Features: Includes powerful features for debugging,
profiling, and testing.
● Time-Saving: IDEs can automatically manage tasks like

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

compiling, linking, and version control.


● Good for Large Projects: IDEs excel in managing complex,
multi-file projects.

Cons of IDEs:

● Heavy and Resource-Intensive: IDEs are usually much larger

LP
and require more system resources compared to code editors.
● Steep Learning Curve: Because they offer so many features, it

sL
can take some time to learn how to use all the tools in an IDE.
● Slower Performance: Can be slower than code editors, especially
ie
on older or less powerful machines.
og
ol

Code Editor vs IDE: When to Use Each?


hn

When to Use a Code Editor:


ec

● For Small Projects: Code editors are excellent for quick edits,
iT

smaller scripts, or lightweight projects.


● For Learning: If you're new to programming, a code editor is a
ev

simpler tool that doesn’t overwhelm you with extra features.


● Fast Editing: Code editors are faster, more responsive, and less
M

resource-heavy, making them ideal for simple tasks.


● When to Use an IDE:
● Large Projects: IDEs are more suited for complex applications or
large projects where you need powerful tools like debugging,
version control, and build automation.
● Advanced Features: If you need features like intelligent code
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

completion, refactoring, integrated testing, and deployment


tools, an IDE is the better choice.
● For Professional Development: IDEs are great for professional
developers working in large teams, as they offer integrated
workflows and advanced support for different programming
languages.

LP
What is Syntax in Programming?

sL
Syntax refers to the set of rules that define how a program should be
written. It dictates how we write instructions (code) so the computer
ie
can understand and execute them.
og
ol

What is a Programming Language?


hn

A programming language is a set of instructions used to


communicate with a computer. Different programming languages
ec

have different syntax and are used for different purposes.


iT
ev

Examples of Programming Languages:


M

● Python: Great for beginners, used for web development, data


analysis, artificial intelligence, etc.
● Java: Used for building Android apps, web applications, etc.
● C++: Used for game development, systems programming, etc.
● JavaScript: Used for web development (front-end and back-end).

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

LP
sL
ie
og
ol
hn
ec
iT
ev

Chapter 1: Starting with Python Basics


M

1. The First print Statement


The print() function in Python is used to display output on the screen.
It is one of the most fundamental and frequently used functions in
programming. Let's write the first Python program:

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

print("Hello, World!")
Output: Hello, World!

Explanation:
● The print keyword is a built-in Python function.
● "Hello, World!" is a string (text) that will be displayed when
the program runs.

LP
2. Different Types of print Statements
Python's print() function can do much more than just display simple

sL
text. Let's explore a few variations:
● Printing Multiple Values:

ie
name = "Meghna"
og
age = 25
ol

print("Name:", name, "Age:", age)


hn

● Formatted Strings (f-strings):


ec

name = "Meghna" age = 25


print(f"My name is {name} and I am {age} years old.")
iT

● Using sep and end Parameters:


ev

o sep (Separator): Defines how multiple values are separated.


o end: Defines what comes at the end of the print statement
M

(default is a newline).
print("Python", "is", "fun", sep="-", end="!")

Output: Python-is-fun!

3. Understanding Variables
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

A variable is like a container that stores data values. In Python,


variables are created when you assign a value to them.

Example:

x = 10
name = "Meghna"
is_active = True

LP
sL
Explanation:
♦ x = 10: Assigns an integer value to x.
ie
♦ name = "Meghana": Assigns a string value to name.
og
♦ is_active = True: Assigns a Boolean value (True or False).
ol

4. Printing Variables
You can combine variables with text in the print function:
hn

Example:
ec

name = "Meghna"
iT

age = 25
ev

print(f"My name is {name} and I am {age} years old.")


M

Multiple Variables:

x, y, z = 10, 20, 30
print(f"x = {x}, y = {y}, z = {z}")

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

LP
sL
ie
og
ol
hn
ec
iT
ev
M

Chapter 2: Data Types in Python

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

1. What are Data Types?


In Python, every value belongs to a specific data type. Data types
define the kind of value a variable holds and the operations that can
be performed on it. Python provides various built-in data types to
handle different kinds of data.

2. Classification of Data Types

LP
1. Numeric Types

sL
◦ Integer (int)
◦ Floating-point (float)
◦ Complex (complex)
2. ieText Type
og
◦ String (str)
3. Boolean Type
ol

◦ Boolean (bool)
4. Sequence Types
hn

◦ List (list)
◦ Tuple (tuple)
ec

◦ Range (range)
5. Mapping Type
iT

◦ Dictionary (dict)
6. Set Types
ev

◦ Set (set)
◦ Frozen Set (frozenset)
M

7. Binary Types
◦ Bytes (bytes)
◦ Byte Array (bytearray)
◦ Memory View (memoryview)

3. Detailed Overview of Data Types


www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

A. Numeric Types
1. Integer (int):
o Stores whole numbers without a decimal point.
o Example:
x = 10
y = -5

LP
print(type(x))
Output: <class 'int'>

sL
2. Floating-point (float):
o Stores numbers with a decimal point.
ie
o Example:
og
x = 10
y = -5
ol

print(type(x))
hn

Output: <class 'int'>


ec

3. Complex (complex):
o Stores numbers with a real and imaginary part.
iT

o Example:
num = 4 + 3j
ev

print(type(num))
M

Output: <class 'complex'>

B. Text Type
1. String (str):
o A sequence of characters enclosed in single, double, or triple
quotes.
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

o Example:

name = "Python"
print(type(name))
Output: <class 'str'>
Strings are immutable, meaning they cannot be changed
after creation.

LP
C. Boolean Type
1. Boolean (bool):

sL
o Represents one of two values: True or False.
o Example:
is_active = True
ie
print(type(is_active))
og
Output: <class 'bool'>
ol
hn

D. Sequence Types
ec

1. List (list):
o An ordered collection of items, which can be modified
iT

(mutable).
o Example:
ev

fruits = ["apple", "banana", "cherry"]


M

print(type(fruits))
Output: <class 'list'>

2. Tuple (tuple):
o An ordered collection of items, which cannot be modified
(immutable).

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

o Example:
person = {"name": "John", "age": 30}
print(type(person))

Output: <class 'dict'>

E. Set Types

LP
1. Set (set):
o An unordered collection of unique items.
o Example:

sL
colors = {"red", "green", "blue"}
print(type(colors))
ie
Output: <class 'set'>
og
ol

2. Frozen Set (frozenset):


hn

o Like a set, but immutable.


o Example
ec

frozen_colors = frozenset(["red", "green", "blue"])


iT

print(type(frozen_colors))
Output: <class 'frozenset'>
ev

F. Binary Types
M

1. Bytes (bytes):
o Immutable sequence of bytes.
o Example
data = bytearray(b"Python")
print(type(data))

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

Output: <class 'bytes'>

2. Byte Array (bytearray):


o Mutable sequence of bytes.
o Example
data = bytearray(b"Python")
print(type(data))

LP
Output: <class 'bytearray'>

sL
Memory View (memoryview):
o Provides a view of the memory of another object.
o Example
ie
data = memoryview(b"Python")
og
print(type(data))
ol

Output: <class 'memoryview'>


hn

4. Checking Data Types


ec

Use the type() function to determine the type of a variable.


Example:
iT

x = 10
ev

print(type(x))
M

Output: <class 'int'>

5. Converting Between Data Types


Python provides built-in functions to convert data types.
Examples:

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

1. Convert Integer to String:


x = 10
x_str = str(x)
print(type(x_str))

Output: <class 'str'>

LP
2. Convert String to Integer:
x = "25"

sL
x_int = int(x)
print(type(x_int))

ie
og
Output: <class 'int'>
ol

3. Convert List to Set:


fruits = ["apple", "banana", "apple"]
hn

unique_fruits = set(fruits)
ec

print(unique_fruits)
iT

Output: {'apple', 'banana'}


ev

Hands-on Practice
M

1. Create variables of each type (int, float, str, bool, list, dict, etc.)
and print their types.
2. Write a program to convert a string of digits (e.g., "12345") into
an integer and add 10 to it.
3. Create a dictionary to store the names and ages of your friends.
Print the dictionary.
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

Lists, tuples, sets, and dictionaries in Python are considered both data
types and data structures, depending on the context. Here's a detailed
explanation to clarify this:

As Data Types
1. Definition: In Python, everything is an object, and every object
has a type. Lists, tuples, sets, and dictionaries are built-in data types

LP
that represent collections of data.

sL
2. Why Data Types?
◦ They define the kind of data being stored (e.g.,
ordered/unordered, mutable/ immutable).

ie
The type() function confirms their data type:
og
print(type([1, 2, 3]))
ol

print(type((1, 2, 3)))
hn

print(type({1, 2, 3}))
print(type({"key": "value"}))
ec

Output:
iT

<class 'list'>
<class 'tuple'>
ev

<class 'set'>
<class 'dict'>
M

◦ Python treats them as distinct, predefined data types.

List, Tuples, Set, Dictionary as Data Structures

1. Definition: A data structure refers to how data is organized,


www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

stored, and manipulated in memory. Lists, tuples, sets, and


dictionaries provide structures to store multiple elements efficiently.

2. Why Data Structures?


◦ They are used to solve real-world problems by organizing data
in meaningful ways.
◦ Example use cases:
▪ Lists: Store ordered collections, like a list of student names.

LP
▪ Tuples: Represent fixed collections, like coordinates (x, y, z).
▪ Sets: Manage unique items, like tracking unique email IDs.
▪ Dictionaries: Map keys to values, like storing student records

sL
with IDs as keys.

Summary
ie
og
Concept Data Type Data Structure
Definition Predefined types in Python How data is organized for
ol

(list, etc.). efficient use.


Focus Type/class of the object. Logical organization of data.
hn

Example type([1, 2, 3]) returns <class Used to store, access, and


'list'>. manipulate data.
ec

In essence:
iT

• Technically: They are data types in Python because they belong


to predefined classes (list, tuple, etc.).
ev

• Practically: They function as data structures when you use them


M

to organize and manage data.

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

LP
sL
Chapter 3: Understanding the input()
ie
Function in Python
og
In this chapter, we will explore the input() function, which is a
ol

fundamental tool for making Python programs interactive. By the end


of this chapter, you will understand how to use input() effectively
hn

and how to handle the data entered by users.


ec

What is the input() Function?


The input() function allows a Python program to accept input from
iT

the user during runtime. This makes programs dynamic and


interactive. The input provided by the user is always returned as a
ev

string.
M

Syntax of input()
input(prompt)
• prompt: A string that is displayed on the screen to instruct or
request the user to provide input. This is optional.
• The function waits for the user to type something and press
Enter, then returns the entered value as a string.
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

Examples of Using input()

1. Basic Example

name = input("What is your name? ")


print("Hello, " + name + "!")

LP
Output:
What is your name? Alice

sL
Hello, Alice!

ie
Explanation: The program asks the user for their name and greets
them using the provided input.
og
2. Using Input Without a Prompt
ol
hn

value = input()
print("You entered:", value)
ec

Output:
iT

Python is fun!
ev

You entered: Python is fun!


M

Explanation: If no prompt is given, the program still waits for the


user’s input.

Handling Numeric Input

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

Since the input() function returns a string, you need to convert it into
the desired numeric type (e.g., int, float) for mathematical operations.

Example: Converting Input to Integer

age = input("Enter your age: ")


age = int(age)
print("Next year, you will be", age + 1, "years old.")

LP
sL
Output:
Enter your age: 25

ie
Next year, you will be 26 years old.
og
Example: Converting Input to Float
ol

number = input("Enter a decimal number: ")


hn

number = float(number)
print("Half of the number is", number / 2)
ec
iT

Output:
ev

Enter a decimal number: 10.5 Half of the number is 5.25


M

Common Mistakes with input()


1. Forgetting to Convert Input

Incorrect
num1 = input("Enter first number: ")
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

num2 = input("Enter second number: ")


print("The sum is:", num1 + num2)

Output:
Enter first number: 5
Enter second number: 10
The sum is: 510

LP
Explanation:

sL
The input values are strings, so the + operator concatenates them
instead of performing arithmetic addition.
Solution:
ie
og
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
ol

print("The sum is:", num1 + num2)


hn
ec

Exercises
iT

1. Simple Input Program


Write a program that asks the user for their favorite color and
ev

displays a message including their input.


M

2. Number Validation
Write a program that asks the user to enter a number and validates
the input. If the input is not a number, it should display an error
message.

3. Simple Calculator
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

Create a program that takes two numbers from the user and prints
their sum, difference, product, and quotient.

LP
sL
ie
og
ol

Chapter 4: Strings in Python


hn
ec

What is a String?
A string in Python is a sequence of characters enclosed within single
iT

quotes ('), double quotes ("), or triple quotes (''' or """). Strings are one
of the most commonly used data types in Python and are immutable,
ev

meaning their content cannot be changed once created.


M

Examples:
#Single-quoted string
string1 = 'Hello, World!'

#Double-quoted string
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

string2 = "Python is awesome!"

#Triple-quoted string (useful for multi-line text)

string3 = '''This is

LP
a multi-line string.'''

sL
Creating Strings

1. ie
Strings can be created using:
Single quotes ('example')
og
2. Double quotes ("example")
3. Triple quotes for multi-line strings ('''example''' or """example""")
ol

Example:
hn

single = 'Hello'
ec

double = "World"
iT

multi_line = '''This is
a multi-line string.'''
ev
M

Accessing Strings
You can access individual characters or slices of a string using
indexing and slicing.

Indexing:
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

Strings are indexed, starting from 0 for the first character and -1 for
the last character.
Example:

string = "Python"
print(string[0]) #
print(string[-1])

LP
Output: P(first character)

sL
Output: n(last character)

Use the slice operator: to extract a part of the string.


Syntax:
ie
og
string[start:end:step]
• start: Starting index (inclusive).
ol

• end: Ending index (exclusive).


hn

• step: Step size (optional).


ec

Example:
iT

string = "Python"
print(string[0:4])
ev
M

Output: Pyth (characters from index 0 to 3)

print(string[::2])

Output: Pto (every second character)

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

String Methods
Python provides several built-in methods to manipulate and interact
with strings. These methods do not modify the original string
(because strings are immutable) but return a new string.

Common String Methods:


1. len(): Returns the length of the string.

LP
string = "Hello"
print(len(string))

sL
Output: 5

2.
ie
lower(): Converts all characters to lowercase.
og
string = "HELLO"
ol

print(string.lower())
Output: hello
hn

3. upper(): Converts all characters to uppercase.


ec

string = "hello"
iT

print(string.upper())
Output: HELLO
ev

4. strip(): Removes leading and trailing whitespace.


M

string = " Hello "


print(string.strip())
Output: Hello

5. replace(): Replaces a substring with another.


string = "Hello, World!"
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

print(string.replace("World", "Python"))

Output: Hello, Python!

6. split(): Splits a string into a list of substrings based on a


delimiter.

LP
string = "apple,banana,cherry"
print(string.split(","))

sL
Output: ['apple', 'banana', 'cherry']

7. ie
join(): Joins elements of a list into a string using a delimiter.
og
fruits = ["apple", "banana", "cherry"]
ol

print(",".join(fruits))
hn

Output: apple,banana,cherry
ec
iT

8. find(): Returns the index of the first occurrence of a substring.

string = "Hello, World!"


ev

print(string.find("World"))
M

Output: 7

9. startswith(): Checks if the string starts with a specified


substring.
string = "Python"
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

print(string.startswith("Py"))

Output: True

10. endswith(): Checks if the string ends with a specified substring.


string = "Python"
print(string.endswith("on"))

LP
Output: True

sL
11. isalpha(): Checks if the string contains only alphabetic
characters.

ie
string = "Hello"
og
print(string.isalpha())
Output: True
ol

12. isdigit(): Checks if the string contains only digits.


hn

string = "12345"
ec

print(string.isdigit())
Output: True
iT

String Operations
ev

Concatenation:
Joining two or more strings using the + operator.
M

str1 = "Hello"
str2 = "World"
print(str1 + " " + str2)

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

Output: Hello World


Repetition:
Repeating a string using the * operator.
string = "Hello"
print(string * 3)

LP
Output: HelloHelloHello

Membership:

sL
Checking if a substring exists within a string using in and not in.

ie
string = "Python"
og
print("Py" in string)
print("Java" not in string)
ol
hn

Output:
True
True
ec
iT

String Types
1. Empty String: A string with no characters.
ev

empty = ""
print(empty)
M

Output: (blank line)

2. Single-Line String: A single line of text.


single_line = "This is a single line."

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

3. Multi-Line String: Text spanning multiple lines using triple


quotes.
multi_line = """ This is
a multi-line string

."""

LP
sL
Practice Exercise:

1.
2. ie
Create a string and print its length.
Convert a string to uppercase and lowercase.
og
3. Replace a word in a sentence with another word.
4. Check if a string starts and ends with certain characters.
ol

5. Use f-strings to format a message containing variables.


hn
ec
iT
ev
M

Chapter 5: Operators in Python

In Python, operators are special symbols or keywords used to


perform operations on variables and values. Python supports a wide

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

range of operators, categorized by the types of operations they


perform.

Types of Operators:
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Logical Operators
4. Bitwise Operators

LP
5. Assignment Operators
6. Membership Operators

sL
7. Identity Operators

1. Arithmetic Operators
ie
Arithmetic operators are used to perform mathematical operations.
og
Operator Description Example Output
ol

+ Addition 5+3 8
hn

- Subtraction 10-Apr 6
ec

* Multiplication 6*7 42

/ Division 15-Mar 5
iT

% Modulus (Remainder) 10 % 3 1
ev

** Exponentiation 2 ** 3 8
M

// Floor Division 17 // 3 5

Example:

num1 = 15
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

num2 = 4
print("Addition:", num1 + num2)
print("Subtraction:", num1 - num2)
print("Multiplication:", num1 * num2)
print("Division:", num1 / num2)
print("Modulus:", num1 % num2)

LP
print("Exponentiation:", num1 ** num2)
print("Floor Division:", num1 // num2)

sL
Output:
Addition: 19

ie
Subtraction: 11
Multiplication: 60
og
Division: 3.75
Modulus: 3
ol

Exponentiation: 50625
hn

Floor Division: 3

2. Comparison (Relational) Operators


ec

Comparison operators compare two values and return a boolean


iT

result (True or False).


ev

Operator Description Example Output


== Equal to 5 == 5 TRUE
M

!= Not equal to 5 != 3 TRUE


> Greater than 10 > 5 TRUE
< Less than 5<3 FALSE
Greater than or
>= 7 >= 7 TRUE
equal to
<= Less than or equal to 4 <= 8 TRUE
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

Example:

x = 10
y = 20
print("x == y:", x == y)
print("x != y:", x != y)

LP
print("x > y:", x > y)
print("x < y:", x < y)

sL
print("x >= y:", x >= y)
print("x <= y:", x <= y)
ie
og
Output:
x == y: False
ol

x != y: True
hn

x > y: False
x < y: True
x >= y: False
ec

x <= y: True
iT
ev

3. Logical Operators
M

Logical operators are used to combine conditional statements.

Operator Description Example Output

Returns True if both


and True and False FALSE
conditions are True
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

Returns True if at least


or True or False TRUE
one condition is

not Reverses the logical state not True FALSE

Example:

x=5

LP
y = 10

sL
print((x > 2) and (y > 5))
print((x > 6) or (y > 5))

ie
print(not(x > 2))
og
Output:
ol

True
True
hn

False
ec

4. Bitwise Operators
Bitwise operators work on binary numbers at the bit level.
iT

Operator Description Example Output


ev

& AND 5&3 1


` ` `5 OR `3 7
M

^ XOR 5^3 6
~ NOT ~5 -6
<< Left Shift 5 << 1 10
>> Right Shift 5 >> 1 2

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

Example:

a = 5 #0b0101
b = 3 #0b0011
print("AND:", a & b)
print("OR:", a | b)
print("XOR:", a ^ b)

LP
print("NOT:", ~a)

sL
print("Left Shift:", a << 1)
print("Right Shift:", a >> 1)

ie
og
Output:
AND: 1
ol

OR: 7
XOR: 6
hn

NOT: -6
Left Shift: 10
ec

Right Shift: 2
iT

5. Assignment Operators
ev

Assignment operators are used to assign values to variables.


M

Operator Description Example Equivalent To


= Assigns value x=5 -
+= Add and assign x+=3 x=x + 3
-= Subtract and assign x-=3 x=x - 2
*= Multiply and assign x*=4 x=x * 4
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

/= Divide and assign x/=2 x=x / 2


%= Modulus and assign x%=3 x=x % 3
**= Exponent and assign x**=2 x=x **2
//= Floor divide and assign x//=3 x=x //3

Example:

x = 10

LP
x += 5

sL
print(x)

ie
Output: 15
og
6. Membership Operators
ol

Membership operators check for membership in a sequence (e.g.,


string, list, tuple).
hn

Operator Description Example Output


ec

in Returns True if found a' in 'apple' TRUE


iT

not in Returns True if not found b' not in apple TRUE


ev

Example:
my_list = [1, 2, 3, 4]
M

print(3 in my_list)
print(5 not in my_list)

Output:
True
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

True

7. Identity Operators
Identity operators compare memory locations of two objects.

Example:

Operator Description Example Output

LP
is Returns True if same object x is y TRUE
is not Returns True if not same x is not y TRUE

sL
a =b =[1, 2, 3]

ie
c = [1, 2, 3,4]
og
print(a is b)
print(a is c)
ol

print(a is not c)
hn

Output:
ec

True
False
iT

True
ev

Summary
This chapter introduces Python operators and their applications in
M

performing various operations. Operators are essential in


programming and are used across a variety of scenarios. By
mastering them, you’ll be able to write powerful and efficient Python
code!

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

Chapter 6: Conditional Statements in Python

Conditional statements are a fundamental concept in programming,

LP
allowing a program to make decisions based on specific conditions.
Python offers several constructs to implement conditional logic in a

sL
program.

ie
6.1 What Are Conditional Statements?
Conditional statements are used to execute a block of code only if a
og
certain condition is met. They allow your program to react differently
depending on the input or situation.
ol

In Python, the main conditional statements are:


hn

• if
• else
ec

• elif (short for "else if")


iT

6.2 Syntax of Conditional Statements


ev

The general syntax of conditional statements in Python is:

if condition1:
M

Code block to execute if condition1 is true elif condition2:


Code block to execute if condition2 is true else:
Code block to execute if none of the conditions are
True

6.3 Understanding Conditions


www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

Conditions in Python are usually comparisons or logical expressions


that evaluate to True or
False.
Examples of conditions:

• x > 5 (Checks if x is greater than 5)


• y == 10 (Checks if y is equal to 10)
• z != 0 (Checks if z is not equal to 0)

LP
• a >= b and b < c (Checks multiple conditions with logical
operators)

sL
6.4 Types of Conditional Statements
6.4.1 The if Statement
ie
The if statement is used to test a condition. If the condition evaluates
og
to True, the indented code block under the if statement is executed.
Example:
ol

age = 18
hn

if age >= 18:


print("You are eligible to vote!")
ec
iT

6.4.2 The else Statement


The else statement provides an alternative block of code if the if
ev

condition evaluates to
False.
M

Example:

age = 16
if age >= 18:
print("You are eligible to vote!")

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

else:
print("You are not eligible to vote yet.")

6.4.3 The elif Statement

The elif statement allows for multiple conditions to be checked

LP
sequentially. It is used when you need to test more than one
condition.

sL
Example:

ie
marks = 85
og
if marks >= 90:
print("Grade: A+")
ol

elif marks >= 75:


hn

print("Grade: A")
elif marks >= 60:
ec

print("Grade: B")
iT

else:
print("Grade: C")
ev
M

6.5 Nested Conditional Statements


You can use one conditional statement inside another. This is called
nesting.

Example:
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

number = 10
if number > 0:
if number % 2 == 0:
print("The number is positive and even.")
else:
print("The number is positive but odd.")

LP
else:

sL
print("The number is not positive.")

ie
6.6 Logical Operators in Conditions
og
Logical operators can combine multiple conditions in a single
ol

statement.
hn

• and: Returns True if both conditions are true.


• or: Returns True if at least one condition is true.
ec

• not: Reverses the logical state of the condition.


iT

Example:
ev

age = 20
M

citizenship = "Indian"
if age >= 18 and citizenship == "Indian":
print("You are eligible to vote.")

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

6.7 The pass Statement in Conditional Statements


Sometimes, you may need a placeholder for a conditional block. The
pass statement does nothing and is used to avoid errors in empty
code blocks.

Example:

x = 10

LP
if x > 0:
pass

sL
Code to be written later

ie
og
ol

6.8 Practical Examples of Conditional Statements


hn

Example 1: Checking Even or Odd


ec

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


iT

if number % 2 == 0:
print("The number is even.")
ev

else:
print("The number is odd.")
M

Example 2: Simple Login System

username = input("Enter username: ")


password = input("Enter password: ")
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

if username == "admin" and password == "1234":


print("Login successful!")
else:
print("Invalid credentials!")

LP
Example 2: Grading System

sL
marks = int(input("Enter your marks: "))

ie
if marks >= 90:
og
print("Grade: A+")
elif marks >= 80:
ol

print("Grade: A")
hn

elif marks >= 70:


print("Grade: B")
ec

elif marks >= 60:


iT

print("Grade: C")
ev

else:
print("Grade: F")
M

6.9 Common Mistakes in Conditional Statements


• Indentation Errors: Make sure all code blocks under a
conditional statement are indented properly.
• Logical Errors: Ensure conditions are logically sound.
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

• Using Assignment (=) Instead of Equality (==): Remember, = is


for assignment, while == is for comparison.
Example of Mistake:
Incorrect: This will cause a syntax error

if x = 10:
print("x is 10")

LP
Correct

sL
if x == 10:

ie print("x is 10")
og
Key Takeaways
ol

• Conditional statements allow programs to make decisions based


hn

on conditions.
• Use if for a single condition, else for alternative actions, and elif
ec

for multiple conditions.


• Logical operators (and, or, not) help in combining conditions.
iT

• Always test and debug your conditions to ensure logical


correctness.
ev

Exercise:
M

1. Write a program to check whether a number is positive,


negative, or zero.
2. Create a program that asks for a user's age and prints whether
they are a child, teenager, adult, or senior citizen.

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

LP
sL
ie
og
ol

Chapter 7: Loops in Python


hn

In programming, loops are used to execute a block of code repeatedly


ec

as long as a specified condition is met. Python supports two primary


types of loops:
iT

1. for Loop: Iterates over a sequence (e.g., list, tuple, string).


ev

2. while Loop: Repeats as long as a condition is true.


M

This chapter explains both types in detail, including their syntax,


usage, and examples.

1. Why Use Loops?


Loops are used to:

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

• Avoid repetitive code.


• Perform operations on each item in a sequence.
• Simplify tasks like data processing, user input collection, or
iterations over files. For example:

Without a loop
print(1)
print(2)

LP
print(3)

sL
With a loop

ie
for i in range(1, 4):
og
print(i)
ol
hn

2. The for Loop


The for loop iterates over items in a sequence (list, tuple, string, etc.)
or uses the range()
ec

function for numerical iterations.


iT

Syntax:
ev

for variable in sequence: Code block


M

Example 1: Iterating Over a List

fruits = ["apple", "banana", "cherry"]


for fruit in fruits:
print(fruit)

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

Output:

apple
banana
cherry

Example 2: Using range()

LP
for i in range(5):
print(i)

sL
Output:

0 ie
og
1
2
ol

3
4
hn

Example 3: Iterating Over Strings


ec
iT

for char in "hello":


print(char)
ev

Output:
M

h
e
l
l
o

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

3. The while Loop


The while loop runs as long as its condition is true. It is suitable for
situations where the number of iterations is not predetermined.

Syntax:

while condition: Code block


Example 1: Basic Usage

LP
counter = 0

sL
while counter < 5:
print(counter)

ie
counter += 1
og
Output:
ol

0
hn

1
2
ec

3
4
iT

Example 2: User Input


ev

password = "python123"
M

user_input = ""
while user_input != password:
user_input = input("Enter password: ")
print("Access granted!")

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

4. Nested Loops
Loops can be nested, meaning one loop is inside another.

Example:

for i in range(1, 4):

LP
for j in range(1, 4):
print(f"i={i}, j={j}")

sL
Output:
ie
og
i=1, j=1 i=1, j=2 i=1, j=3 i=2, j=1
...
ol

5. Control Statements
hn

break
Exits the loop prematurely.
ec

for i in range(10):
iT

if i == 5:
ev

break
print(i)
M

Output:

0
1
2
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

3
4

continue
Skips the current iteration and moves to the next one.

for i in range(5):
if i == 2:

LP
continue

sL
print(i)

ie
Output:
og
0
ol

1
3
hn

4
ec

pass
Does nothing; acts as a placeholder.
iT

for i in range(3):
ev

pass
M

Problem 1: Multiplication Table

Write a program to print the multiplication table of a given


number.

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

Problem 2: Sum of First N Numbers

Write a program to calculate the sum of the first n numbers using a


while loop.

Problem 3: Nested Loops for Patterns

LP
Write a program to print a right-angled triangle pattern.

sL
while True in Python
The while True loop in Python is a special type of infinite loop that
ie
runs until it is explicitly stopped using a break statement or another
og
termination condition. This loop is useful in scenarios where you
need the program to keep running indefinitely until a specific event
ol

occurs, like user input, a condition being met, or external interaction.


hn

while True:
Code block if condition:
ec

break
iT

How It Works
1. Condition Check: The while loop checks the condition, which in
ev

this case is True. Since True is always True, the loop runs infinitely.
2. Execution of Code Block: The statements inside the loop are
M

executed repeatedly.
3. Termination: The loop is terminated when a break statement is
encountered or the program is stopped manually.

Example 1: Basic Infinite Loop

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

while True:
print("This will print endlessly unless we stop it.")

Example 2: User Input with Exit Condition

while True:

LP
user_input = input("Enter something (type 'exit' to quit): ")
if user_input.lower() == "exit":

sL
print("Exiting the loop. Goodbye!")
break
ie
print(f"You entered: {user_input}")
og
ol

Explanation:
hn

• The loop keeps asking for user input until the user types exit.
ec

• When exit is typed, the if condition becomes True, and the break
statement stops the loop.
iT

Sample Output:
ev

Enter something (type 'exit' to quit): Hello You entered: Hello


Enter something (type 'exit' to quit): Python You entered: Python
M

Enter something (type 'exit' to quit): exit Exiting the loop. Goodbye!

Example 3: Repeated Guessing Game

import random

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

Generate a random number between 1 and 10


number_to_guess = random.randint(1, 10)

while True:
guess = int(input("Guess the number (between 1 and 10): "))
if guess == number_to_guess:
print("Correct! You guessed the number!")

LP
break
elif guess < number_to_guess:

sL
print("Too low. Try again!")
else:
ie
og
print("Too high. Try again!")
ol

Explanation:
hn

• The program generates a random number.


ec

• The user is asked to guess the number repeatedly until they


guess correctly.
iT

• When the correct number is guessed, the break statement ends


the loop.
ev

Use Cases of while True


M

1. Menu-Driven Programs: Used to create menus that repeat until


the user exits.
2. Real-Time Systems: Continuously monitor inputs like sensors in
embedded systems or servers.
3. Error Handling Loops: Retry operations (e.g., asking for valid
input) until success.
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

4. Interactive Programs: Interactive games, chatbots, or


command-driven systems.

Precautions

1. Avoid Infinite Loops Without Exit Conditions: Ensure the loop


has a valid break
condition or user-interrupt mechanism.

LP
2. Resource Consumption: Infinite loops consume CPU resources.
Use them judiciously.

sL
3. Debugging Tips: If a while True loop doesn’t terminate as
expected, review the conditions leading to the break statement.

ie
og
Practice Problems
1. Write a while True loop that asks for a password. Break out of
ol

the loop when the correct password is entered.


2. Create a loop to simulate a basic ATM system where users can
hn

check their balance, deposit, or withdraw money until they choose to


exit.
ec
iT
ev
M

Chapter 8: Python Data Structures

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

Python provides a rich set of built-in data structures to manage and


organize data efficiently. In this chapter, we will explore lists, tuples,
sets, and dictionaries, along with their features, examples, and
methods. We'll also understand why certain data structures are
mutable, ordered, or unordered.

1. Lists
Definition:

LP
A list is an ordered collection of items that can hold elements of any
data type. Lists are mutable, meaning their contents can be changed

sL
after creation.

Characteristics:
• ie
Ordered: Elements maintain their insertion order.
og
• Mutable: Elements can be added, modified, or removed.
• Heterogeneous: Can store elements of different data types.
ol

Examples:
hn

#Creating a list
ec

fruits = ["apple", "banana", "cherry"]


iT

print(fruits) #Output: ['apple', 'banana', 'cherry']


ev

#Mixed data types


mixed = [1, "hello", 3.14]
M

print(mixed) #Output: [1, 'hello', 3.14]

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

Common Methods:

Method Description Example

append(elem Adds an element to the end of fruits.append("ora


ent) thefruits nge")

insert(index, Inserts an element at a specified fruits.insert(1,


element) index fruits "grape")

LP
pop([index]) Removes and returns an fruits.pop(2)
element at an index fruits

sL
remove(elem Removes the first occurrence of fruits.remove("ban
ent) a fruit ana")

sort() ie Sorts the list in ascending order fruits.sort()


og
fruits

reverse() Reverses the list order fruits fruits.reverse()


ol

len() Returns the number of elements len(fruits)


hn

in fruits
ec
iT

Why Mutable?
Lists are mutable because they allow in-place modifications, making
ev

them suitable for scenarios where the data needs to change


dynamically.
M

2. Tuples
Definition:
A tuple is an ordered collection of items similar to a list, but tuples
are immutable.

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

Characteristics:
• Ordered: Elements maintain their insertion order.
• Immutable: Cannot modify elements after creation.
• Heterogeneous: Can store elements of different data types.

LP
Examples:

sL
Creating a tuple
#Creating a list

ie
fruits = ["apple", "banana", "cherry"]
print(fruits) #Output: ['apple', 'banana', 'cherry']
og
ol

#Mixed data types


hn

mixed = [1, "hello", 3.14]


print(mixed) #Output: [1, 'hello', 3.14]
ec
iT

Common Methods:
ev

Method Description Example


M

count(value) Counts occurrences of a value tuple_example.cou


tuple_example nt("apple")

index(value) Returns the index of the value tuple_example.ind


tuple_example ex("banana")

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

Why Immutable?
Tuples are immutable to ensure data integrity, making them suitable
for fixed collections of data such as coordinates or configuration
values.

LP
3. Sets
Definition:

sL
A set is an unordered collection of unique elements.

ie
Characteristics:
og
• Unordered: Does not maintain any specific order.
• Mutable: Elements can be added or removed.
ol

• Unique: No duplicate elements.


hn
ec

Examples:
iT

#Creating a set
numbers = {1, 2, 3, 4, 5}
ev

print(numbers) #Output: {1, 2, 3, 4, 5}


M

#Adding an element
numbers.add(6)
print(numbers) #Output: {1, 2, 3, 4, 5, 6}

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

#Duplicate elements
unique_set = {1, 1, 2, 2, 3}
print(unique_set) #Output: {1, 2, 3}

Common Methods:

LP
Method Description Example
Adds a value to the
add(value) numbers.add(6)

sL
set
Removes a value;
remove(value
raises an error if numbers.remove(3)
)
ie missing
og
discard(value Removes a value
numbers.discard(7)
) without raising
ol

Returns a new set


union(set2) numbers.union({6, 7})
with all elements
hn

Returns common
intersection(s
elements between numbers.intersection({3,4})
et2)
ec

sets
iT

Why Unordered?
Sets are unordered because they are optimized for fast lookups and
ev

ensure uniqueness, making them ideal for membership tests.


M

4. Dictionaries
Definition:
A dictionary is an unordered collection of key-value pairs, where
each key is unique.

Characteristics:
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

• Unordered (Python < 3.7): Keys are not stored in any specific
order.
• Ordered (Python ≥ 3.7): Maintains insertion order.
• Mutable: Can add, modify, or delete key-value pairs.
• Unique Keys: Keys must be unique, but values can repeat.

Examples:

LP
#Creating a dictionary
person = {"name": "John", "age": 30, "city": "New York"}
print(person)

sL
#Output: {'name': 'John', 'age': 30, 'city': 'New York'}

ie
#Accessing values print(person["name"]) #Output: John
og
#Adding a new key-value pair
person["job"] = "Engineer"
ol

print(person)
#Output: {'name': 'John', 'age': 30, 'city': 'New York', 'job': 'Engineer'}
hn

Common Methods:
ec
iT

Method Description Example


get(key) Returns the value for the given key person.get("age"
ev

keys() Returns a list of all keys person.keys()


values() Returns a list of all values person.values()
M

items() Returns a list of key-value pairs person.items()


pop(key) Removes a key-value pair by key person.pop("age"

Why Mutable?
Dictionaries are mutable because they often store dynamic data that
may change during program execution.
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

Summary Table

LP
Feature List Tuple Set Dictionary
Ordered Yes Yes No Yes (Python ≥ 3.7)

sL
Mutable Yes No Yes Yes
Duplicate Not Keys: Not Allowed;
Values ie Allowed Allowed
Allowed Values: Allowed
og
Heterogeneous Yes Yes Yes Yes
ol

Conclusion
Understanding Python's built-in data structures is crucial for writing
hn

efficient and readable code. By leveraging the unique features of lists,


tuples, sets, and dictionaries, you can solve various programming
ec

problems effectively. Their characteristics—such as mutability, order,


and uniqueness—determine how and when to use them.
iT

Advanced Examples Combining Data Structures and the


ev

random Library
Here are some interesting programs that combine Python's data
M

structures with the random


library:

Example 1: Randomly Selecting Elements from a List

import random
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

#List of fruits
fruits = ["apple", "banana", "cherry", "date", "elderberry"]

#Select a random fruit


random_fruit = random.choice(fruits)

LP
print(f"Random fruit: {random_fruit}")
#Shuffle the list

sL
random.shuffle(fruits)
print(f"Shuffled fruits: {fruits}")

ie
og
Example 2: Creating a Dictionary with Random Values
ol

import random
hn

#Keys are letters, values are random integers


ec

random_dict = {chr(i): random.randint(1, 100) for i in range(65,


iT

71)} #A to F
print("Random dictionary:", random_dict)
ev
M

Example 3: Using a Set to Find Unique Random Numbers

import random

#Generate a set of unique random numbers

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

unique_numbers = set()
while len(unique_numbers) < 5:
unique_numbers.add(random.randint(1, 10))
print(f"Unique random numbers: {unique_numbers}")
Example 4: Nested Data Structures with Random Values

import random

LP
#Create a nested dictionary

sL
nested_dict = {f"list_{i}": [random.randint(1, 10) for _ in

ie
range(5)] for i in range(3)}
og
print("Nested dictionary with random values:")
ol

for key, value in nested_dict.items():


hn

print(f"{key}: {value}")
ec

Example 5: Simulating a Deck of Cards


iT

import random
ev
M

#Create a deck of cards


suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
values = ["2", "3", "4", "5", "6", "7", "8", "9", "10","Jack",
"Queen", "King", "Ace"]
deck = [f"{value} of {suit}" for suit in suits for value in

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

values]

#Shuffle the deck random.shuffle(deck)

#Draw 5 cards
hand = [deck.pop() for _ in range(5)]
print("Your hand:")

LP
for card in hand:

sL
print(card)

ie
og
Example 6: Grouping Randomly Generated Numbers
ol

import random
hn

#Generate random numbers and group them into even and


ec

odd numbers = [random.randint(1, 50) for _ in range(20)]


iT

even_numbers = [num for num in numbers if num % 2 == 0]


ev

odd_numbers = [num for num in numbers if num % 2 != 0]


M

print(f"Numbers: {numbers}")
print(f"Even numbers: {even_numbers}")
print(f"Odd numbers: {odd_numbers}")

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

These examples highlight the versatility of Python's data structures


and their seamless integration
with libraries like random. Feel free to modify and expand upon
them!

LP
sL
ie
Chapter 9: Python Functions
og
Functions are reusable blocks of code that perform a specific task.
ol

They help organize code, improve readability, and avoid


redundancy.
hn

1. What is a Function?
ec

A function is a block of code that runs only when it is called.


Functions allow us to pass data, known as parameters, and return
iT

data as a result.
ev

Syntax:
M

def function_name(parameters): #Code block


return value

Example:

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

def greet(name):
return f"Hello, {name}!"

Calling the function

greeting = greet("Alice")

LP
print(greeting) #Output: Hello, Alice!

sL
2. Types of Functions
2.1 Built-in Functions
ie
Python comes with many built-in functions, such as print(), len(),
og
sum(), etc. Example:
ol

numbers = [1, 2, 3, 4, 5]
hn

print(len(numbers)) #Output: 5
print(sum(numbers)) #Output: 15
ec
iT

2.2 User-defined Functions


These are functions you define yourself to perform specific tasks.
ev

Example:
M

def add_numbers(a, b):


return a + b

result = add_numbers(3, 7)
print(result) #Output: 10
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

2.3 Anonymous (Lambda) Functions


Lambda functions are small, one-line functions defined without a
name.
Syntax:
lambda arguments: expression
Example:

LP
square = lambda x: x ** 2

sL
print(square(5)) #Output: 25

3. ie
Function Arguments
og
Functions can accept arguments (inputs) to work with.
ol

3.1 Positional Arguments


hn

Arguments are matched to parameters based on their order.


Example:
ec

def describe_person(name, age):


iT

print(f"{name} is {age} years old.")


ev

describe_person("Alice", 30) #Output: Alice is 30 years old.


M

3.2 Keyword Arguments


Arguments are passed by parameter name, allowing flexibility in
order. Example:

def describe_person(name, age):


www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

print(f"{name} is {age} years old.")

describe_person(age=30, name="Alice") #Output: Alice is 30


years old.

3.3 Default Arguments


Default values can be set for parameters.

LP
Example:

sL
def greet(name="Guest"):
print(f"Hello, {name}!")

ie
greet() #Output: Hello, Guest!
og
greet("Alice") #Output: Hello, Alice!
ol

3.4 Variable-length Arguments


hn

Functions can accept a variable number of arguments using *args (for


positional arguments) or **kwargs (for keyword arguments).
ec

Example with *args:


iT

def add_all(*numbers):
ev

return sum(numbers)
print(add_all(1, 2, 3, 4)) #Output: 10
M

Example with **kwargs:

def print_details(**details):
for key, value in details.items():
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

print(f"{key}: {value}")
print_details(name="Alice", age=30, city="New York")

4. Returning Values
Functions can return a value using the return statement.
Example:

LP
def multiply(a, b):

sL
return a * b
result = multiply(4, 5)

ie
print(result) #Output: 20
og
ol

5. Scope of Variables
hn

5.1 Local Scope


Variables declared inside a function are local to that function.
ec

Example:
iT

def my_function():
local_var = 10
ev

print(local_var)
M

my_function() #Output: 10
print(local_var) #Error: local_var is not defined

5.2 Global Scope


www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

Variables declared outside any function are global and accessible


throughout the program.

Example:

global_var = 20
def my_function():
print(global_var)

LP
my_function() #Output: 20

sL
5.3 Using global Keyword
ie
To modify a global variable inside a function, use the global keyword.
og
Example:
ol

global_var = 20
hn

def modify_global():
global global_var
ec

global_var += 10
iT

modify_global()
print(global_var) #Output: 30
ev
M

6. Advanced Examples
Example 1: Factorial Function(with recursion)

def factorial(n):
if n == 0 or n == 1:
return 1
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

return n * factorial(n - 1)
print(factorial(5)) #Output: 120

Example 2: Fibonacci Sequence


def factorial(n):

LP
if n == 0 or n == 1:
return 1

sL
return n * factorial(n - 1)
print(factorial(5)) #Output: 120

ie
In the provided example, recursion is demonstrated through the
og
factorial function, which calls itself to calculate the factorial of a
number.
ol

● Base Case: If n is 0 or 1, the function returns 1 directly without


hn

further recursion. This stops the function from making infinite


recursive calls.
ec

● Recursive Case: For values of n greater than 1, the function


returns n * factorial(n - 1). Here, the function calls itself with a
iT

smaller value (n - 1) until the base case is reached.


ev

Step-by-Step Execution for factorial(5):

1. factorial(5) = 5 * factorial(4)
M

2. factorial(4) = 4 * factorial(3)
3. factorial(3) = 3 * factorial(2)
4. factorial(2) = 2 * factorial(1)
5. factorial(1) = 1 (base case reached)

The results propagate back as:

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

● factorial(2) = 2 * 1 = 2
● factorial(3) = 3 * 2 = 6
● factorial(4) = 4 * 6 = 24
● factorial(5) = 5 * 24 = 120

Recursion allows breaking the problem into smaller subproblems


and solving them step by step.

LP
Example 3: Palindrome Checker

sL
def is_palindrome(string):
return string == string[::-1]

ie
print(is_palindrome("radar")) #Output: True
og
print(is_palindrome("hello")) Output: False
ol
hn

Example 4: Using Functions with Random Library


ec

import random
iT

def generate_random_list(size, start, end):


return [random.randint(start, end) for _ in range(size)]
ev

random_list = generate_random_list(5, 1, 100)


print(random_list)
M

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

LP
sL
ie
og
ol
hn
ec
iT

Chapter 10: Exception Handling , Handling


ev

Files and Built In Modules


M

What is File Handling?

File handling in Python allows you to create, read, write,


and manipulate files stored on your system. It is done using

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

the built-in open() function, which opens a file and returns


a file object.

Syntax of open():

file_object = open(file_name, mode)

● file_name: Name (and path) of the file to open.

LP
● mode: Mode in which the file is opened (e.g., read,
write, append).

sL
Access Modes
ie
og
Mo Purpose Behavior
de
ol

'r' Read mode Opens the file for reading. File must
hn

exist, otherwise raises


FileNotFoundError.
ec

'w' Write Opens the file for writing. Creates a


iT

mode new file if it doesn't exist or truncates


it if it does.
ev

'a' Append Opens the file for appending. Creates


M

mode a new file if it doesn't exist.

'x' Exclusive Creates a new file. Raises


creation FileExistsError if the file already
mode exists.

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

'r+' Read and Opens the file for both reading and
write mode writing. File must exist.

'w+' Write and Opens the file for both writing and
read mode reading. Truncates the file if it exists.

'a+' Append Opens the file for appending and


and read reading. Creates a new file if it

LP
mode doesn't exist.

't' Text mode Opens the file in text mode.

sL
(default)

'b'
ie
Binary
mode
Opens the file in binary mode for
non-text files like images, videos, etc.
og
ol
hn

Basic Operations
1. Reading a File
ec

● Mode: 'r'
iT

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


ev

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

● Other Reading Methods:


○ file.readline(): Reads one line at a time.
○ file.readlines(): Reads all lines and returns a list.

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

2. Writing to a File

● Mode: 'w'

with open("example.txt", "w") as file:


file.write("This is a new line of text.")

● Behavior: Overwrites the content if the file already exists.

LP
3. Appending to a File

sL
● Mode: 'a'

with open("example.txt", "a") as file:


ie
file.write("\nThis is an appended line.")
og
ol

4. Creating a File
hn

● Mode: 'x'

try:
ec

with open("newfile.txt", "x") as file:


iT

file.write("This file was created with 'x' mode.")


except FileExistsError:
ev

print("File already exists!")


M

5. Reading and Writing

● Mode: 'r+'

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

print(file.read()) # Read the existing content


www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

file.write("\nAdding a new line!") # Append new content

6.Working with Binary Files

● Mode: 'rb', 'wb'

# Writing binary data

LP
with open("example.bin", "wb") as file:

sL
file.write(b"This is binary data.")

ie
og
# Reading binary data

with open("example.bin", "rb") as file:


ol
hn

binary_content = file.read()

print(binary_content)
ec
iT

Using with Statement

● Automatically closes the file when the block ends, even if an


ev

error occurs.

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


M

print(file.read())

# No need to call file.close()

Python Exception Handling Tutorial


www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

What is Exception Handling?

Exception handling in Python allows you to manage and handle


runtime errors gracefully, without halting the program's execution
abruptly. This is achieved using the try-except block.

Syntax

try:

LP
# Code that may raise an exception

except ExceptionType:

sL
# Code to handle the exception

else:
ie
og
# Code that runs if no exception occurs (optional)

finally:
ol

# Code that runs no matter what (optional)


hn

Common Exception Types in Python


ec
iT

Exception Description
ev

ZeroDivision Raised when division by zero is


M

Error attempted.

FileNotFound Raised when a file is not found.


Error

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

ValueError Raised when an operation receives


an invalid value.

TypeError Raised when an operation is applied


to the wrong type.

LP
IndexError Raised when accessing an invalid
index in a list.

sL
KeyError Raised when a dictionary key does

ie not exist.
og
ImportError Raised when an import fails.
ol
hn

IOError Raised for Input/Output operation


errors.
ec
iT

Basic Example
ev

try:
M

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

result = 10 / number

print(f"Result: {result}")

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

except ZeroDivisionError:

print("Error: Division by zero is not allowed.")

except ValueError:

print("Error: Invalid input, please enter a number.")

LP
Advanced Example

sL
Handling multiple exceptions:

try:
ie
og
with open("nonexistent_file.txt", "r") as file:

content = file.read()
ol
hn

print(content)

except FileNotFoundError:
ec

print("File not found! Please check the file path.")


iT

except IOError:
ev

print("An I/O error occurred.")


M

The else Block

The else block executes if no exception occurs.

try:

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

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

print(f"Square of the number is {number**2}")

except ValueError:

print("Invalid input! Please enter a valid number.")

else:

LP
print("Operation successful!")

sL
The finally Block

ie
The finally block executes regardless of whether an exception
occurred.
og
try:
ol

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


hn

content = file.read()
ec

print(content)
iT

except FileNotFoundError:
ev

print("File not found!")


M

finally:

print("Closing the file.")

file.close()

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

Raising Exceptions

You can raise exceptions manually using the raise keyword.

def check_age(age):
if age < 18:
raise ValueError("Age must be 18 or older.")
print("Age is valid.")

LP
try:

sL
check_age(21)
except ValueError as e:
print(e) ie
og
ol

Custom Exceptions
hn

You can define your own exceptions by creating a custom class that
inherits from Exception.
ec
iT

class CustomError(Exception):
pass
ev
M

try:
raise CustomError("This is a custom error.")
except CustomError as e:
print(e)

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

Example Program
# A program to demonstrate exception handling
def divide_numbers():
try:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

LP
result = num1 / num2
except ZeroDivisionError:

sL
print("Error: Division by zero is not allowed.")
except ValueError:

ie
print("Error: Please enter valid numbers.")
og
else:
print(f"The result is: {result}")
ol

finally:
hn

print("Execution complete.")
ec

divide_numbers()
iT

Key Tips
ev

1. Always use specific exceptions instead of a generic except to


M

handle known errors.


2. Use finally for cleanup tasks like closing files or releasing
resources.
3. Avoid suppressing exceptions without understanding their
root cause.

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

Practice Problems
This chapter provides a variety of practice problems for loops,
conditional statements, strings, and operators, along with a detailed
explanation of Python libraries like math, random, and more.

LP
Practice Problems
1. Guess the Number Game

sL
Write a program where the user has to guess a randomly generated
number between 1 and 100. The program should provide feedback if
ie
the guess is too high or too low and continue until the user guesses
og
correctly.

high or too low and continue until the user guesses correctly.
ol
hn

import random
number_to_guess = random.randint(1, 100)
ec

while True:
iT

guess = int(input("Guess the number (between 1 and 100):"))


if guess == number_to_guess:
ev

print("Congratulations! You guessed the correct number.")


M

break
elif guess < number_to_guess:
print("Too low! Try again.")
else:
print("Too high! Try again.")
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

Explanation:
• Uses the random library to generate a random number.
• Implements a while loop to repeatedly take guesses.
• Uses conditional statements to guide the user.

LP
sL
2. Palindrome Checker

Check if a given string is a palindrome.


ie
og
def is_palindrome(string):
string = string.lower().replace(" ", "")
ol

return string == string[::-1]


hn

user_input = input("Enter a string to check if it's a palindrome:


ec

")
iT

if is_palindrome(user_input):
ev

print("It's a palindrome!")
else:
M

print("Not a palindrome.")

Explanation:
• Converts the string to lowercase and removes spaces.

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

• Compares the string with its reverse using slicing.


• Uses an if statement to check the condition.

3. Multiplication Table
Print the multiplication table of a number provided by the user.

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


for i in range(1, 11):

LP
print(f"{number} x {i} = {number * i}")

sL
Explanation:

ie
Uses a for loop to iterate from 1 to 10.
og
• Prints the result of the multiplication using an f-string.
ol

4. Calculate Factorial
Calculate the factorial of a given number using a while loop.
hn

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


ec

result = 1
iT

while number > 1:


ev

result *= number
number -= 1
M

print(f"Factorial: {result}")

Explanation:
• Multiplies the number by decrementing it in a while loop.
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

• Stops when the number becomes 1.

5. Count Vowels in a String

Count the number of vowels in a given string.

string = input("Enter a string: ")

LP
vowels = "aeiouAEIOU"
count = 0

sL
for char in string:
if char in vowels:
ie
count += 1
og
print(f"Number of vowels: {count}")
ol

Explanation:
• Uses a for loop to iterate through the string.
hn

• Checks if each character is in the set of vowels.


ec

Exploring Libraries
1. Math Library
iT

The math library provides mathematical functions.


Example Functions:
ev

import math
M

#Square root
print(math.sqrt(16)) #Output: 4.0

#Power
print(math.pow(2, 3)) #Output: 8.0
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

#Trigonometric functions
print(math.sin(math.pi / 2)) #Output: 1.0

#Rounding
print(math.floor(4.7)) #Output: 4
print(math.ceil(4.3)) #Output: 5

LP
2. Random Module
The random library is used to generate random numbers and choices.

sL
Example Functions:
import random
ie
og
#Random integer
print(random.randint(1, 10)) #Random number between 1 and
10
ol
hn

#Random choice
colors = ["red", "blue", "green"]
ec

print(random.choice(colors))
iT

#Shuffle a list
numbers = [1, 2, 3, 4, 5] #random.shuffle(numbers)
ev

print(numbers)
M

#Random float
print(random.uniform(1.5, 3.5)) #Random float between 1.5 and
3.5

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

3. Time Module
The time library is used to manage time-related tasks.
Example Functions:

import time

#Current time in seconds since epoch

LP
print(time.time())
#Sleep for a few seconds

sL
print("Start")
#time.sleep(2)

ie
print("End after 2 seconds")
og
#Current local time
print(time.ctime())
ol
hn

4. OS Module
The os library provides a way to interact with the operating system.
ec

Example Functions:
iT

import os
#Get current working directory
ev

print(os.getcwd())
M

#List files in a directory


print(os.listdir("."))
#Create a new directory
os.mkdir("new_folder")

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

5. Sys Module
The sys module in Python provides access to system-specific
parameters, functions, and objects maintained by the Python runtime
environment. It is widely used to interact with the Python interpreter
and the system on which the Python program is running.

LP
Key Features of the sys Module

1. sys.version

sL
● Purpose: Returns the version of the Python interpreter being
used.
● Example:ie
og
import sys
ol

print(sys.version)
hn

This tells you:

● Python version: 3.11.5


ec

● Build date: Aug 23 2023


iT

● Compiler and architecture: MSC v.1939 64 bit (AMD64)


ev

2. sys.argv
M

● Purpose: Contains a list of command-line arguments passed to


the Python script.
○ sys.argv[0] is the name of the script being executed.
○ Additional arguments are included as subsequent
elements.
● Example:
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

import sys

print("Script name:", sys.argv[0]) # Name of the script

print("Arguments:", sys.argv[1:]) # List of arguments passed

This is useful for passing data or options to scripts from the


command line.

LP
3. sys.exit()

sL
● Purpose: Exits the Python interpreter with an optional exit code.
● Example:

import sys
ie
og
print("Program is running...")

sys.exit(0) # Graceful exit with code 0


ol

print("This will not be printed.")


hn

4. sys.path
ec

● Purpose: A list of directories that the Python interpreter searches


iT

for modules.
● Example:
ev

import sys
print(sys.path)
M

● Includes the directory of the current script and standard library


paths.
● You can add custom paths to sys.path to import modules from
non-standard locations.

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

5. sys.stdin, sys.stdout, sys.stderr


● Purpose: Standard input, output, and error streams.
● Examples:

import sys

sys.stdout.write("This is standard output.\n") # Output text

LP
sys.stderr.write("This is an error message.\n") # Output error

sL
6. re: Regular Expression Matching
ie
The re module allows you to work with regular expressions, which
og
are patterns used to match strings.
ol

Common Functions in re:


hn

1. re.search(): Searches for the first occurrence of the pattern in the


string.
ec

import re
iT

pattern = r"\d+" # Match one or more digits


ev

match = re.search(pattern, "The number is 42")


M

if match:

print(match.group()) # Output: 42

2. re.findall(): Finds all occurrences of the pattern.


www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

text = "My numbers are 123 and 456."

matches = re.findall(r"\d+", text)

print(matches) # Output: ['123', '456']

3. re.sub(): Replaces matches with a specified string.


text = "The color is blue."

LP
updated_text = re.sub(r"blue", "red", text)

sL
print(updated_text) # Output: The color is red.

ie
og
4. re.match(): Matches the pattern only at the beginning of the
string.
ol

text = "42 is the answer."


hn

match = re.match(r"\d+", text)


ec

if match:
iT

print(match.group()) # Output: 42
ev

Common Regular Expression Patterns with Python Syntax


M

Patt Description Python Example Matches


ern Syntax

\d Matches any r"\d" re.search(r"\d", 2


digit (0-9). "Age: 25")

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

\w Matches any r"\w" re.search(r"\w", H


word character "Hello_123")
(letters, digits,
_).

\s Matches any r"\s" re.search(r"\s", ""


whitespace "a b")

LP
(space, tab,
newline).

sL
. Matches any r"." re.search(r".", H
ie
character except "Hello")
og
a newline.
ol

^ Matches the r"^pattern" re.search(r"^Hell Hello


hn

start of the o", "Hello!")


string.
ec

$ Matches the end r"pattern$" re.search(r"Worl World


iT

of the string. d$", "Hello


World")
ev
M

[abc Matches any r"[abc]" re.findall(r"[aeio ['a', 'e']


] character in the u]", "apple")
brackets.

[^ab Matches any r"[^abc]" re.findall(r"[^aei ['p', 'p',

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

c] character not in ou]", "apple") 'l']


the brackets.

a* Matches zero or r"a*" re.search(r"a*", aaaa


more "aaaab")
occurrences of a.

LP
a+ Matches one or r"a+" re.search(r"a+", aaaa
more "aaaab")

sL
occurrences of a.

a? ie
Matches zero or r"a?" re.search(r"a?", ""
og
one occurrence "b")
of a.
ol
hn

a{2, Matches 2 to 4 r"a{2,4}" re.search(r"a{2,4} aaaa


4} occurrences of a. ", "aaaa")
ec
iT

`a b` Matches `r"a b"`


either a or b.
ev
M

Here’s the enhanced table with Python syntax for common regular
expression functions and their patterns:

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

Output
Function Purpose Python Example
Syntax

Searches for re.search(p re.search(r"\ <re.Match


re.search
the attern, d+", object;
span=(5, 7),
first match string) "Age: 25")
match='25'>

LP
of a pattern
in a string.

sL
Finds all re.findall(p re.findall(r"
re.findall ['12', '34']
ie matches of
attern, \d+",
og
a pattern in a string) "Numbers:
string as a 12 and 34")
ol

list.
hn

Matches a re.match(pa re.match(r"\ <re.Match


ec

re.match
ttern, w+", object;
pattern only
iT

span=(0, 5),
at the start of string) "Hello
the string. match='Hel
World")
ev

lo'>
M

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

Replaces re.sub(patte re.sub(r"cat "dog is


re.sub
matches rn, ",
cute"
of a pattern repl, "dog", "cat
with a string) is cute")
specified
string.

LP
Splits a re.split(patt re.split(r"\s ['split',
re.split
string ern, +", 'this',

sL
'string']
by matches string) "split this
of a pattern. string")

ie
og
Matches a re.fullmatc re.fullmatc <re.Match
re.fullmatc
ol

h(pattern, h(r"\d+", object;


h pattern
span=(0, 5),
hn

against the string) "12345")


whole string. match='123
45'>
ec
iT
ev
M

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

Compiles a pattern = pattern = <re.Match


re.compile
object;
regular
span=(5, 7),
expression re.compile( re.compile(
pattern for pattern) r"\d+"); match='25'>
repeated use. pattern.sear
ch("Age:
25")

LP
sL
Returns an re.finditer( matches =
re.finditer 123, 456
pattern,
iterator

ie yielding
match
string)
re.finditer(r
"\d+", "123
og
objects for and 456");
all matches. for m in
ol

matches:
hn

print(m.gro
ec

up())
iT

Escapes "a\\+b\\*c"
re.escape re.escape(st re.escape("a
ev

special
ring) +b*c")
characters
M

in a string to
be used in a
regex.

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

Here's a Python program to validate an email address using the re


module:

import re

def is_valid_email(email):

# Regular expression pattern for a valid email

LP
email_pattern =
r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'

sL
if re.fullmatch(email_pattern, email):

ie
return True
og
else:
ol

return False
hn
ec

# Test cases
iT

emails = [
ev

"test@example.com",
M

"invalid-email",

"user@domain.org",

"megha.b_s@company.co.in",

"no_at_symbol.com",
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

"@missinguser.com"

for email in emails:

if is_valid_email(email):

LP
print(f"'{email}' is a valid email address.")

sL
else:

ie
print(f"'{email}' is not a valid email address.")
og
ol

Explanation:
hn

Here’s a detailed breakdown of the regular expression:

python
ec

Copy code
iT

1. r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
ev
M

This pattern is designed to validate an email address. Let’s break it


down step by step:

1. ^

● Meaning: Matches the beginning of the string.


www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

● Purpose: Ensures that the pattern starts matching from the start
of the email string.

2. [a-zA-Z0-9._%+-]+

● Meaning: Matches one or more (+) characters from the set


[a-zA-Z0-9._%+-].
● Details:

LP
○ a-zA-Z: Matches any uppercase or lowercase English
letters.

sL
○ 0-9: Matches any digit.
○ ._%+-: Matches specific special characters (., _, %, +, -),

ie
which are allowed in the local part of an email.
● Purpose: Defines the local part (before the @) of an email
og
address.
ol

Examples of valid matches:

● john.doe
hn

● user_name
● user+123
ec
iT

3. @
ev

● Meaning: Matches the literal "@" character.


● Purpose: Separates the local part of the email from the domain
M

part. The "@" is a required character in all email addresses.

4. [a-zA-Z0-9.-]+

● Meaning: Matches one or more (+) characters from the set


www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

[a-zA-Z0-9.-].
● Details:
○ a-zA-Z: Matches any uppercase or lowercase English
letters.
○ 0-9: Matches any digit.
○ .-: Matches dots (.) or hyphens (-), which are valid in
domain names.
● Purpose: Defines the domain name (e.g., example in

LP
example.com).

Examples of valid matches:

sL
● example
● sub-domain
ie
og
5. \.
ol

● Meaning: Matches a literal dot (.).


● Purpose: Indicates the separator between the domain name and
hn

the top-level domain (TLD).


ec
iT

6. [a-zA-Z]{2,}$

● Meaning: Matches exactly 2 or more ({2,}) letters (a-zA-Z) at the


ev

end of the string ($).


● Purpose: Ensures a valid top-level domain (e.g., .com, .org,
M

.co.in).

Examples of valid matches:

● com
● org
● co.in (the . before in is matched earlier by \.).
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

7. $

● Meaning: Matches the end of the string.


● Purpose: Ensures the entire email matches the pattern, not just a
part of it.

LP
Putting It All Together

This regular expression ensures:

sL
1. The string starts with a valid local part (letters, digits, and
certain special characters).
ie
2. Contains exactly one @.
og
3. Is followed by a valid domain name (letters, digits, hyphens, and
dots).
ol

4. Ends with a valid top-level domain of at least 2 letters.


hn

Examples of Valid Emails


ec

● user.name@example.com
iT

● john_doe@sub.domain.org
● megha+test@company.co.in
ev

Examples of Invalid Emails


M

● user@.com → Domain cannot start with a dot.


● @domain.com → Missing local part.
● user@domain → Missing top-level domain.
● user@domain..com → Double dots are not allowed.

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

7. json: Working with JSON Data

The json module is used for encoding and decoding JSON (JavaScript
Object Notation) data, which is a lightweight format for storing and
transporting data.

Common Functions in json:

1. json.dumps(): Converts a Python object (e.g., dictionary) to a

LP
JSON string.

import json

sL
data = {"name": "Megha", "age": 27}

ie
json_data = json.dumps(data)
og
print(json_data) # Output: {"name": "Megha", "age": 25"}
ol
hn
ec

2.json.loads(): Parses a JSON string into a Python object.


iT

json_string = '{"name": "Megha", "age": 27}'

data = json.loads(json_string)
ev

print(data["name"]) # Output: Megha


M

3.Working with JSON files:


● Write to a file:

with open("data.json", "w") as file:

json.dump(data, file)
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

● Read from a file:

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

data = json.load(file)

print(data)

Practice Problems with builtin Modules

LP
1. Generate Random Password
Generate a random password with letters, digits, and symbols.

sL
import random
ie
import string
og
length = int(input("Enter password length: "))
ol

characters = string.ascii_letters + string.digits +


hn

string.punctuation
password = ''.join(random.choice(characters) for _ in
ec

range(length))
iT

print(f"Generated Password: {password}")


ev
M

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

LP
sL
ie
og
ol
hn
ec
iT
ev

Chapter 11: Object-Oriented Programming


M

(OOP) Concepts
Object-Oriented Programming (OOP) is a programming paradigm
that organizes code into objects and classes. The main concepts of
OOP include Classes, Objects, Methods, Inheritance, Polymorphism,
Encapsulation, and Abstraction.

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

1. Class
A class is like a blueprint or template for creating objects. It defines a
set of attributes and methods that the created objects will have.

Real-world example: Think of a "Car" class. The class defines


common attributes like color, brand, and speed, and behaviors like
drive and stop.

LP
Simple Example (without self and objects initially):

● A class is a blueprint or template that defines the structure and

sL
behavior of objects.
● It defines attributes (also known as properties or fields) and
methods (also known as behaviors or functions) that the
ie
objects of that class will have.
og
● The class does not hold actual data. It only defines how objects
of that class should behave.
ol

Real-world analogy: Think of a class as a blueprint for building


hn

houses. The blueprint defines the structure (number of rooms,


doors, windows), but it doesn't represent an actual house.
ec
iT

class Car:
ev

# Attributes (properties) without self

color = "Red"
M

brand = "Toyota"

# Method (behavior) without self


www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

def drive():

print("The car is driving.")

# Accessing class attributes directly using the class name

print(Car.color) # Outputs: Red

LP
Car.drive() # Outputs: The car is driving.

sL
ie
og
2. Object:
ol

● An object is an instance of a class. When we create an object, we


are instantiating a class and giving it actual data for its
hn

attributes.
● Each object created from the class can hold different values for
ec

its attributes (i.e., objects are independent of each other and can
have different states).
iT

● Objects use the methods defined in their class to perform actions


or behaviors.
ev

Real-world analogy: Using the blueprint of the house (the class), you
M

can construct actual houses (objects). Each house can have different
characteristics like different colors, number of rooms, etc.

Example:
# Creating an object (instance of the class)
my_car = Car()

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

your_car = Car()

# Accessing object attributes


my_car.color = "Blue" # Changing the color of my_car

# Calling object methods

LP
my_car.drive() # Outputs: The car is driving.
your_car.drive() # Outputs: The car is driving.

sL
Key Points in the Relationship:
ie
og
1. Class as a Template:
○ A class is like a template or blueprint, and it defines the
ol

structure and behavior (attributes and methods) that


objects of that class will have.
hn

○ For example, the Car class defines that every car will have a
color and a brand and a method to drive().
ec

2. Object as an Instance:
○ An object is an actual instance of a class. When you create
iT

an object, you are instantiating the class with specific values


for its attributes.
ev

○ Each object can have unique values for the attributes


defined in the class.
M

3. Independence of Objects:
○ Although objects of the same class share the same structure
and behavior, they can hold different data for their
attributes.
○ For example, my_car.color could be "Blue", and
your_car.color could be "Red", even though both objects
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

belong to the same Car class.


4. Interdependence:
○ The object relies on the class to define its structure and
behavior, and the class relies on objects to demonstrate its
functionality. The methods in a class are meant to act on the
specific attributes of the objects instantiated from it.

LP
sL
3.self and __init__ in Python Classes
ie
In Object-Oriented Programming (OOP), self and __init__ are key
og
concepts that allow objects to have their own state (attributes) and
behavior (methods). Let’s break down what each of these does:
ol
hn

1. self in Python Classes:


ec

● self refers to the current instance of the class. It allows you to


iT

access the instance's attributes and methods within the class.


● When you create an object (instance) of a class, self points to that
ev

specific object.
● It is the first parameter of any instance method in a class (not the
M

constructor). Although you don’t pass self explicitly when


calling the method, Python automatically passes it as the first
argument when the method is invoked.

Key Points about self:


● It is used to access the instance’s attributes (variables) and
methods.
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

● It is a convention to name the first parameter of instance


methods as self, though technically you can use any name.
However, using self is the standard.

Real-world analogy: Think of self as a reference to "this" specific


object. For example, if you have multiple cars, self helps each car
instance to know its own specific attributes (like color, brand) and
behaviors (like drive).

LP
Example with self:

sL
class Car:
def __init__(self, color, brand):

ie
self.color = color # Using self to assign instance attributes
og
self.brand = brand # Using self to assign instance attributes
ol

def drive(self): # Instance method


hn

print(f"The {self.color} {self.brand} car is driving.")


ec

# Creating objects (instances of the class)


iT

my_car = Car("Red", "Toyota")


your_car = Car("Blue", "Honda")
ev
M

# Calling methods
my_car.drive() # Outputs: The Red Toyota car is driving.
your_car.drive() # Outputs: The Blue Honda car is driving.

# Accessing attributes using self

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

print(my_car.color) # Outputs: Red


print(your_car.color) # Outputs: Blue

Explanation:

● self.color and self.brand are instance variables. Each instance

LP
(like my_car or your_car) has its own color and brand, which are
unique to that specific instance.
● self.drive(): The method drive() uses self to refer to the current

sL
instance, so when it is called on different objects, it prints the
corresponding car's color and brand.
ie
2. __init__ Method in Python Classes:
og
The __init__ method is a special method in Python classes. It is
ol

known as the constructor, and it is called automatically when a new


object (instance) of the class is created.
hn

● The __init__ method allows you to initialize the attributes of an


object when it is created. It's used to set the initial state of the
ec

object.
iT

● It always takes self as the first parameter (which refers to the


current instance) and any additional parameters needed to
ev

initialize the object.

Key Points about __init__:


M

● It is automatically called when you create a new instance of the


class.
● It allows you to set values for attributes when the object is
created.
● self allows __init__ to assign values to the object's attributes.

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

Real-world analogy: When you buy a new car, the __init__ method
can be thought of as the process where the car gets its initial features,
like color and brand, at the time of purchase.

Example with __init__:

class Car:
def __init__(self, color, brand):

LP
self.color = color # Initialize instance variable color
self.brand = brand # Initialize instance variable brand

sL
def drive(self): # Instance method
ie
print(f"The {self.color} {self.brand} car is driving.")
og
# Creating objects (instances of the class)
ol

my_car = Car("Red", "Toyota") # The __init__ method is called here


hn

your_car = Car("Blue", "Honda") # The __init__ method is called here


ec

# Accessing attributes and calling methods


iT

my_car.drive() # Outputs: The Red Toyota car is driving.


ev

your_car.drive() # Outputs: The Blue Honda car is driving.


M

Explanation:

● When we create an object like my_car = Car("Red", "Toyota"), the


__init__ method is automatically called.
● It initializes the object’s attributes, such as color and brand, with
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

the provided values "Red" and "Toyota".


● The drive method then uses those initialized values (the state of
the object) to perform an action.

4. Inheritance in Object-Oriented Programming (OOP)


Inheritance is one of the key features of Object-Oriented
Programming (OOP). It allows a class (called a child class or

LP
subclass) to inherit attributes and methods from another class (called
a parent class or superclass). This feature enables the child class to

sL
reuse the code from the parent class and also add its own unique
behavior or modify the inherited behavior.

ie
og
Key Concepts of Inheritance:
1. Parent Class (Superclass):
ol

○ A class that is being inherited from.


hn

○ It defines common attributes and methods that are shared


by all subclasses.
ec

2. Child Class (Subclass):


○ A class that inherits from another class.
iT

○ It can use the attributes and methods of the parent class,


but it can also add its own or modify the inherited ones.
ev

3. Reusability:
○ Inheritance allows for code reuse. A child class does not
M

need to rewrite the code from the parent class, making the
code more efficient and maintainable.
4. Overriding:
○ A child class can override methods from the parent class to
provide its own specific implementation.

Syntax of Inheritance:
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

class ParentClass:
# Parent class attributes and methods
def __init__(self):
self.parent_attribute = "This is a parent attribute"

def parent_method(self):

LP
print("This is a parent method.")

sL
# Child class inheriting from ParentClass

ie
class ChildClass(ParentClass):
og
# Child class can have its own attributes and methods
def __init__(self):
ol

super().__init__() # Calling the parent class constructor


hn

self.child_attribute = "This is a child attribute"


ec

def child_method(self):
iT

print("This is a child method.")


ev

# Method overriding (replacing parent method)


M

def parent_method(self):
print("This is an overridden method in the child class.")

1. Basic Inheritance Example:

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

# Parent Class
class Animal:
def __init__(self, name):
self.name = name

def speak(self):

LP
print(f"{self.name} makes a sound.")

sL
# Child Class
class Dog(Animal):

ie
def __init__(self, name, breed):
og
super().__init__(name) # Calling the parent class constructor
self.breed = breed
ol
hn

def speak(self): # Method overriding


print(f"{self.name} barks.")
ec
iT

# Creating an object of the Child class


dog = Dog("Buddy", "Golden Retriever")
ev

dog.speak() # Outputs: Buddy barks.


M

Explanation:

● Animal is the parent class with an attribute (name) and a


method (speak).
● Dog is the child class that inherits from Animal.
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

● The Dog class has an additional attribute (breed) and overrides


the speak method to provide a more specific implementation.
● The super().__init__(name) line in the child class constructor
calls the parent class constructor to initialize the name attribute.

2. Using super() to Access Parent Class Methods:


The super() function is used to call methods from the parent class. It
is commonly used in the constructor (__init__) of a child class to

LP
invoke the parent class’s constructor and initialize inherited
attributes.

sL
class Vehicle:
def __init__(self, brand, model):
ie
self.brand = brand
og
self.model = model
ol

def display_info(self):
hn

print(f"Brand: {self.brand}, Model: {self.model}")


ec

# Child class inheriting from Vehicle


iT

class Car(Vehicle):
ev

def __init__(self, brand, model, color):


super().__init__(brand, model) # Calling the parent class
M

constructor
self.color = color

def display_info(self): # Method overriding


super().display_info() # Calling the parent class method
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

print(f"Color: {self.color}")

# Creating an object of the Car class


car = Car("Toyota", "Corolla", "Red")
car.display_info()

LP
Explanation:

● Vehicle class has an __init__ constructor and a method

sL
display_info.
● Car class inherits from Vehicle, adds a new attribute (color), and

ie
overrides the display_info method.
● The super().__init__(brand, model) call invokes the parent class's
og
constructor to initialize the brand and model.
● super().display_info() is used to call the parent class's method
ol

and then add additional behavior (printing the color).


hn

3. Multilevel Inheritance:
ec

In multilevel inheritance, a class can inherit from another class,


which itself is a subclass of another class.
iT

class Animal:
ev

def __init__(self, name):


self.name = name
M

def speak(self):
print(f"{self.name} makes a sound.")

class Dog(Animal):
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

def __init__(self, name, breed):


super().__init__(name)
self.breed = breed

def speak(self):
print(f"{self.name} barks.")

LP
class Puppy(Dog):

sL
def __init__(self, name, breed, age):
super().__init__(name, breed)

ie
self.age = age
og
def speak(self):
ol

print(f"{self.name} barks and is {self.age} months old.")


hn

# Creating an object of the Puppy class


puppy = Puppy("Buddy", "Golden Retriever", 3)
ec

puppy.speak() # Outputs: Buddy barks and is 3 months old.


iT

Explanation:
ev

● Animal is the base class.


M

● Dog is a subclass of Animal.


● Puppy is a subclass of Dog, making it a subclass of Animal
indirectly (multilevel inheritance).
● Each class can override the speak method and add more
attributes as necessary.

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

4. Multiple Inheritance:
In multiple inheritance, a class can inherit from more than one
parent class.

class Engine:
def start(self):

LP
print("Engine started.")

sL
class Car:

ie
def drive(self):
print("Car is driving.")
og
ol

# Child class inheriting from both Engine and Car


hn

class HybridCar(Engine, Car):


def __init__(self, brand, model):
ec

self.brand = brand
iT

self.model = model
# Creating an object of the HybridCar class
ev

hybrid_car = HybridCar("Tesla", "Model X")


hybrid_car.start() # From Engine class
M

hybrid_car.drive() # From Car class

Explanation:

● HybridCar inherits from both Engine and Car, gaining access to


www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

methods from both classes.

Key Points about Inheritance:


● Single Inheritance: A child class inherits from one parent class.
● Multilevel Inheritance: A class inherits from another class,
which itself is a subclass of another class.
● Multiple Inheritance: A class can inherit from multiple parent
classes.

LP
● Method Overriding: The child class can override methods from
the parent class to provide its own implementation.

sL
● The super() Function: Used to call methods from the parent
class

ie
5. Polymorphism in Object-Oriented Programming (OOP)
og
Polymorphism is another fundamental concept of Object-Oriented
Programming (OOP). The word "polymorphism" comes from Greek,
ol

where "poly" means "many" and "morph" means "forms". In


programming, polymorphism allows objects of different classes to be
hn

treated as objects of a common superclass. It also allows methods to


have the same name but behave differently based on the object that is
ec

calling the method.


iT
ev

Key Concepts of Polymorphism:


1. Method Overloading: Multiple methods in the same class have
M

the same name but different parameters.


2. Method Overriding: A method in a subclass has the same name,
same parameters, and same signature as a method in its parent
class, but the subclass method provides its own implementation.
3. Dynamic Method Dispatch: In Python, method overriding
enables polymorphism by dynamically determining which
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

method to call based on the object type at runtime.

Types of Polymorphism:
1. Compile-time Polymorphism (Static Polymorphism): This is
achieved through method overloading and operator
overloading. Python does not support method overloading in
the traditional sense like languages such as Java or C++, but we
can achieve similar functionality with default arguments or

LP
variable-length arguments.
2. Runtime Polymorphism (Dynamic Polymorphism): This occurs

sL
when a method in a child class overrides a method in the parent
class. Python supports runtime polymorphism through method
overriding.
ie
og
ol
hn

1. Method Overloading (Compile-time Polymorphism):


ec

In languages like Java or C++, method overloading allows you to


define multiple methods with the same name but different
iT

parameters. However, Python does not support traditional method


overloading. Instead, you can use default arguments or
ev

variable-length arguments to simulate method overloading.

Example of method overloading using default arguments:


M

class Calculator:
def add(self, a, b=0, c=0): # Default parameters (simulate
overloading)
return a + b + c
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

calc = Calculator()
print(calc.add(5)) #5
print(calc.add(5, 10)) # 15
print(calc.add(5, 10, 20)) # 35

LP
Here, we are using default values for b and c to simulate method
overloading. The add method can take one, two, or three arguments,

sL
and the appropriate result will be computed based on the number of
arguments passed.

ie
og
2. Method Overriding (Runtime Polymorphism):
In method overriding, a subclass provides its own implementation of
ol

a method that is already defined in its superclass. The version of the


hn

method that gets called is determined at runtime, depending on the


type of the object (whether it's an instance of the parent class or the
subclass).
ec

Example of method overriding:


iT

class Calculator:
ev

def add(self, a, b=0, c=0): # Default parameters (simulate


overloading)
M

return a + b + c

calc = Calculator()
print(calc.add(5)) #5
print(calc.add(5, 10)) # 15
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

print(calc.add(5, 10, 20)) # 35

Here, we are using default values for b and c to simulate method


overloading. The add method can take one, two, or three arguments,
and the appropriate result will be computed based on the number of
arguments passed.

LP
4.2 Method Overriding (Runtime Polymorphism):

sL
In method overriding, a subclass provides its own implementation of
a method that is already defined in its superclass. The version of the

ie
method that gets called is determined at runtime, depending on the
type of the object (whether it's an instance of the parent class or the
og
subclass).
ol

Example of method overriding:


hn

# Parent class
class Animal:
ec

def speak(self):
iT

print("Animal makes a sound")


ev

# Child class
M

class Dog(Animal):
def speak(self):
print("Dog barks")

# Child class
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

class Cat(Animal):
def speak(self):
print("Cat meows")

# Creating objects of the classes


animal = Animal()

LP
dog = Dog()
cat = Cat()

sL
# Calling the speak method

ie
animal.speak() # Outputs: Animal makes a sound
og
dog.speak() # Outputs: Dog barks
cat.speak() # Outputs: Cat meows
ol

Explanation:
hn

● The speak() method in the Animal class is overridden by the


ec

Dog and Cat classes. Each subclass provides its own


implementation of speak().
iT

● When the speak() method is called on dog and cat objects, it calls
the overridden methods from their respective classes, not the
ev

Animal class method.


● Polymorphism allows us to use the same method name (speak)
M

on different objects, and Python dynamically determines which


version of the method to call based on the type of object at
runtime.

Real-world analogy of polymorphism:


www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

Imagine you have a remote control that can operate different devices:
a TV, a Fan, or an Air Conditioner. All devices have a method called
turn_on(). Even though the turn_on() method is the same for each
device, the action performed is different:

● turn_on() for the TV might turn the TV on.


● turn_on() for the Fan might turn the fan blades.
● turn_on() for the Air Conditioner might activate cooling.

LP
Even though you call turn_on() on any device, the action performed
depends on which device (object) you are controlling, and this is an

sL
example of runtime polymorphism.

ie
4.3 Polymorphism with a Common Interface:
og
Polymorphism allows us to treat different classes in the same way, as
long as they implement a common method. This is especially useful
ol

when working with a collection of objects from different classes that


hn

share a common behavior.

Example with a common interface:


ec
iT

class Shape:
def area(self):
ev

pass # Common interface, to be implemented by subclasses


M

class Circle(Shape):
def __init__(self, radius):
self.radius = radius

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

def area(self): # Implementing the common method


return 3.14 * self.radius ** 2

class Rectangle(Shape):
def __init__(self, length, width):
self.length = length

LP
self.width = width

sL
def area(self): # Implementing the common method
return self.length * self.width

ie
og
# Creating objects of different classes
shapes = [Circle(5), Rectangle(4, 6)]
ol
hn

# Calling the common method `area()` on each object


for shape in shapes:
ec

print(shape.area()) # Outputs the area of each shape


iT

Explanation:
ev

● Both Circle and Rectangle classes implement the common area()


method, though their implementations differ.
M

● A list of Shape objects (shapes) is created, consisting of both


Circle and Rectangle objects.
● The area() method is called on each object in the list. Thanks to
polymorphism, even though the objects are of different types
(circle and rectangle), we can call the same method (area) and
get the correct result for each type.
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

Summary of Polymorphism:
1. Polymorphism allows objects of different classes to be treated as
objects of a common superclass.
2. Method Overriding is a form of polymorphism where a method
in a child class provides a specific implementation of a method
that is already defined in the parent class.

LP
3. Method Overloading (not commonly used in Python) allows a
method to be called with different numbers of parameters,

sL
giving different behaviors based on the number or type of
arguments passed.
4. Polymorphism with a common interface allows us to use a
ie
common method across different classes, each of which provides
og
its own specific implementation.
ol

Real-world analogy:
hn

● Polymorphism is like the "open" command on different software


ec

programs. When you press "open", it opens a file. But for a text
editor, it opens a text file, for a media player, it opens a video or
iT

audio file, and for a web browser, it opens a web page. The
open() command behaves differently based on the program
ev

(object), but it's still the same command.


M

5. Encapsulation in Object-Oriented Programming (OOP)


Encapsulation is one of the core principles of Object-Oriented
Programming (OOP) that bundles data (attributes) and methods
(functions) that operate on the data into a single unit called a class. It

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

also restricts direct access to some of an object's attributes or methods,


which is a mechanism of hiding the internal state of the object from
the outside world. This is achieved by using access modifiers.

In simple terms, encapsulation protects the internal data of an object


by controlling access to it, allowing data to be accessed or modified
only through well-defined methods (getter and setter functions).

LP
Key Concepts of Encapsulation:

sL
1. Private Attributes: By convention, attributes are made private to
prevent direct access from outside the class.

ie
2. Public Methods: Provide methods (often called getters and
setters) to access and modify the private attributes.
og
3. Data Hiding: Restricts direct access to an object’s internal state
and allows only controlled access via methods.
ol

4. Control over Data: Encapsulation allows the class to maintain


control over how its attributes are accessed and modified,
hn

ensuring that the object remains in a valid state.


ec
iT

Benefits of Encapsulation:
1. Data Hiding: Prevents external code from changing an object’s
ev

internal state directly.


2. Modularity: By bundling the data and methods together, classes
M

are more self-contained.


3. Maintainability: Changes to the internal workings of a class can
be made without affecting other parts of the program.
4. Control: The class can ensure that its internal state is always
valid through validation in the setter methods.

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

How to Achieve Encapsulation in Python:


In Python, encapsulation is achieved by:

1. Making attributes private (prefixing them with an underscore _


or double underscore __).
2. Providing getter and setter methods to access and modify the

LP
private attributes.

sL
class Person:
# Private attribute (by convention)

ie
def __init__(self, name, age):
og
self.__name = name # Private attribute
self.__age = age # Private attribute
ol
hn

# Getter for name


def get_name(self):
ec

return self.__name
iT

# Setter for name


ev

def set_name(self, name):


M

if len(name) > 0:
self.__name = name
else:
print("Name cannot be empty.")

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

# Getter for age


def get_age(self):
return self.__age

# Setter for age


def set_age(self, age):

LP
if age >= 0:
self.__age = age

sL
else:
print("Age cannot be negative.")

ie
og
# Creating an object of Person class
person = Person("John", 30)
ol
hn

# Accessing private attributes using getters


print(person.get_name()) # Output: John
ec

print(person.get_age()) # Output: 30
iT

# Modifying private attributes using setters


ev

person.set_name("Alice")
M

person.set_age(25)

# Accessing updated values


print(person.get_name()) # Output: Alice
print(person.get_age()) # Output: 25
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

# Trying to set invalid values


person.set_age(-5) # Output: Age cannot be negative.

Explanation:

1. Private Attributes:

LP
○ In the Person class, the attributes __name and __age are
made private by prefixing them with two underscores (__).
○ This means these attributes cannot be directly accessed

sL
from outside the class.
2. Getter and Setter Methods:
ie
○ We provide getter and setter methods to access and modify
og
the private attributes. The getter methods (get_name() and
get_age()) return the values of __name and __age, while the
setter methods (set_name() and set_age()) allow us to
ol

modify those values, but only if the new value is valid.


hn

○ The set_name() method checks if the name is not empty,


and set_age() checks if the age is not negative.
ec

3. Encapsulation:
○ By using encapsulation, we ensure that the name and age
iT

attributes can only be accessed or modified in a controlled


manner. This protects the internal state of the object from
ev

being changed directly from outside the class, thus


maintaining data integrity.
M

Real-World Analogy of Encapsulation:


www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

Think of an ATM machine:

● The ATM has a card reader and a display screen, but the
internal details of how it processes the transaction (like
interacting with a bank's database) are hidden from the user.
● The user can only interact with the ATM through a pin and
transaction interface (getters and setters), not directly with the
internal mechanisms (private data).
● The ATM class hides its internal data and exposes a controlled

LP
way to access and modify it.

sL
Example with Python Property Decorators:

ie
In Python, you can use property decorators (@property,
og
@<attribute>.setter) to simplify getter and setter methods, making
them more elegant and easier to use.
ol

class Circle:
hn

def __init__(self, radius):


self.__radius = radius
ec
iT

# Getter for radius using property


@property
ev

def radius(self):
M

return self.__radius

# Setter for radius using property


@radius.setter
def radius(self, value):

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

if value > 0:
self.__radius = value
else:
print("Radius must be positive.")

# Property for calculating area

LP
@property
def area(self):

sL
return 3.14 * (self.__radius ** 2)

ie
# Creating an object of Circle class
og
circle = Circle(5)
ol

# Accessing the radius and area


hn

print(circle.radius) # Output: 5
print(circle.area) # Output: 78.5
ec
iT

# Modifying the radius using setter


circle.radius = 10
ev

print(circle.radius) # Output: 10
M

print(circle.area) # Output: 314.0

# Trying to set invalid radius


circle.radius = -5 # Output: Radius must be positive.

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

Explanation:

● The radius attribute is encapsulated using a property. We use


@property for the getter and @radius.setter for the setter,
allowing us to access radius directly without calling it like a
method.
● The area is a calculated property that provides the circle's area
based on the radius, which is automatically updated when the
radius is changed.

LP
● Using property, we can access and modify the attributes with
controlled behavior, all while keeping the data encapsulated.

sL
ie
6. Abstraction in Object-Oriented Programming (OOP)
og
Abstraction is an OOP principle that focuses on hiding the
implementation details of a class and showing only the essential
ol

features or functionalities to the user. It allows you to focus on what


an object does rather than how it does it.
hn

Abstraction can be achieved through:


ec

1. Abstract Classes: Classes that cannot be instantiated and are


iT

meant to be subclasses.
2. Interfaces (via Abstract Methods): Methods that must be
implemented by derived classes.
ev
M

Key Concepts of Abstraction:


1. Hiding Implementation:
○ Users interact with the object through a well-defined
interface without knowing the internal workings.
2. Emphasizing Essential Features:
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

○ It simplifies the complexity of a system by exposing only


the necessary details.
3. Achieved via Inheritance:
○ Abstract classes and methods enforce a contract that
derived classes must follow.

Benefits of Abstraction:

LP
1. Improves Code Maintainability: Changes to the
implementation details don't affect the users of the class.

sL
2. Increases Flexibility: Focus on functionality without being tied
to a specific implementation.

ie
3. Enhances Reusability: Provides a common interface for
different implementations.
og
ol

Example of Abstraction: Real-World Analogy


hn

Think of an electric appliance like a washing machine:


ec

● You press buttons to start, stop, or set a washing mode (what it


does).
iT

● You don't need to know how it spins the drum or heats the
water (how it does it).
ev
M

Abstract Classes and Methods in Python


Python provides the abc (Abstract Base Class) module to create
abstract classes and methods.

Abstract Class Example

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

from abc import ABC, abstractmethod

# Abstract Base Class


class Animal(ABC):
# Abstract Method
@abstractmethod

LP
def sound(self):
pass

sL
# Concrete Method

ie
def sleep(self):
og
print("This animal is sleeping.")
ol

# Derived Class 1
hn

class Dog(Animal):
def sound(self):
ec

print("Woof! Woof!")
iT

# Derived Class 2
ev

class Cat(Animal):
M

def sound(self):
print("Meow! Meow!")

# Instantiate objects of derived classes


dog = Dog()
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

cat = Cat()

# Accessing methods
dog.sound() # Output: Woof! Woof!
cat.sound() # Output: Meow! Meow!
dog.sleep() # Output: This animal is sleeping.

LP
cat.sleep() # Output: This animal is sleeping.

sL
Explanation:

ie
1. Abstract Base Class (Animal):
○ It cannot be instantiated directly.
og
○ It has an abstract method sound() that must be
implemented by all derived classes.
ol

2. Derived Classes (Dog and Cat):


hn

○ Each subclass provides its own implementation of the


sound() method.
ec

3. Concrete Method:
○ The sleep() method in the base class can be used directly by
iT

all subclasses.
ev

Example of Abstraction with Real-World Scenarios


M

Payment Gateway Abstraction


from abc import ABC, abstractmethod

class Payment(ABC):

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

@abstractmethod
def process_payment(self, amount):
pass

class CreditCardPayment(Payment):
def process_payment(self, amount):

LP
print(f"Processing credit card payment of ${amount}.")
class PayPalPayment(Payment):

sL
def process_payment(self, amount):
print(f"Processing PayPal payment of ${amount}.")

ie
og
# Client code
def make_payment(payment_method, amount):
ol

payment_method.process_payment(amount)
hn

# Using the abstraction


ec

credit_payment = CreditCardPayment()
iT

paypal_payment = PayPalPayment()
ev

make_payment(credit_payment, 100) # Output: Processing credit


M

card payment of $100.


make_payment(paypal_payment, 200) # Output: Processing PayPal
payment of $200.

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

Explanation:

1. Base Class (Payment):


○ Defines a contract for processing payments via the
process_payment method.
2. Derived Classes (CreditCardPayment, PayPalPayment):
○ Implement the process_payment method with specific
details for each payment type.
3. Client Code (make_payment):

LP
○ Interacts with the objects through the abstract base class,
without needing to know the specific implementation.

sL
Why Use Abstraction?

ie
● Focus on Functionality:
○ The user focuses on what an object does, not how it
og
achieves its functionality.
● Scalability:
ol

○ New implementations can easily be added by creating new


hn

derived classes without modifying existing code.


ec
iT
ev
M

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

LP
sL
ie
Chapter 12 Iterators , Generators and
og
Modules, Packages in Python
ol

1. What are Modules?


hn

A module is a Python file containing definitions and statements (e.g.,


functions, classes, and variables). Modules help organize code by
ec

grouping related functionality into a single file.


iT

● Example: A module named math_operations.py:

# math_operations.py
ev

def add(a, b):


M

return a + b

def subtract(a, b):


return a - b

● Using a module:
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

import math_operations

print(math_operations.add(5, 3)) # Output: 8


print(math_operations.subtract(5, 3)) # Output: 2

2. What are Packages?

LP
A package is a collection of related Python modules organized in a
directory. The directory must contain an __init__.py file, which can be

sL
empty or include initialization code.

● Directory structure of a package:

ie
my_package/
og
__init__.py

module1.py
ol

module2.py
hn

● Using a package:
ec

# my_package/module1.py
iT

def greet(name):
ev

return f"Hello, {name}!"


M

# main.py

from my_package import module1

print(module1.greet("Megha")) # Output: Hello, Megha!

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

Benefits of Modules and Packages


● Promote code reusability.
● Make code more readable and manageable.
● Allow for modular design in large projects.

Iterators and Generators

LP
1. What is an Iterator?

sL
An iterator is an object in Python that allows you to traverse through
all the elements of a collection (e.g., list, tuple) one element at a time.
It implements the __iter__() and __next__() methods.

● Example:ie
og
my_list = [1, 2, 3]
ol

iterator = iter(my_list) # Get an iterator for the list


hn

print(next(iterator)) # Output: 1
ec

print(next(iterator)) # Output: 2
iT

print(next(iterator)) # Output: 3
ev
M

● Custom Iterator:

class MyIterator:

def __init__(self, start, end):

self.current = start
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

self.end = end

def __iter__(self):

return self

def __next__(self):

if self.current >= self.end:

LP
raise StopIteration

sL
self.current += 1

ie
return self.current - 1
og
for number in MyIterator(1, 5):
ol

print(number)
hn
ec

2. What is a Generator?
iT

A generator is a special type of iterator, created using a function that


uses the yield keyword. It produces values lazily, meaning it
ev

generates items one at a time as required, which makes it


memory-efficient.
M

● Basic Generator:

def my_generator():

yield 1

yield 2
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP

yield 3

for value in my_generator():

print(value)

Benefits of Generators:

LP
● Memory-efficient: Only generates one item at a time.
● Easy to implement: Simplifies writing custom iterators.

sL
Example of a Generator for Fibonacci Sequence:

ie
def fibonacci(n):
og
a, b = 0, 1
ol

for _ in range(n):
hn

yield a
ec

a, b = b, a + b
iT
ev

for num in fibonacci(5):


M

print(num)

Differences Between Iterators and Generators

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com


Python Notes By Mevi Technologies LLP

Feature Iterators Generators

Definitio An object with __iter__() A function that uses


n and __next__() methods. yield to produce values
lazily.

LP
Syntax Requires implementing Uses a simple function
methods manually. and yield.

sL
Memory May consume more Memory-efficient
Usage
ie memory (stores all
elements).
(produces one value at a
time).
og
ol

Ease of Requires more boilerplate Simpler to implement.


Use code.
hn
ec
iT
ev
M

www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com

You might also like