Complete Python Notes
Complete Python Notes
What is a Program?
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
humans.
iT
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.
Examples of Programs
# Example in Python
LP
num2 = int(input("Enter second number: "))
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
What is an Application?
iT
Types of Applications
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
What is Software?
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
1. System Software
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
2. Application Software
iT
perform specific user tasks. They sit on top of system software and
depend on it to function.
M
LP
media).
○ Enterprise Applications: Cater to organizational needs,
sL
managing large-scale data or operations.
■ Examples: SAP (enterprise resource planning),
LP
sL
ie
What is ASCII?
og
ASCII (American Standard Code for Information Interchange) is a
ol
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
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
● 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
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
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
5. ASCII Mapping: The binary code is matched with its ASCII value
ev
the screen.
● 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
LP
sL
ie
og
ol
hn
ec
Step Description
ev
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
positional data.
iT
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
This means
hn
ec
Why 4 bytes?
iT
● Characters that are within the ASCII range (0-127) take 1 byte.
ev
● Characters that are outside the ASCII range, like emojis, take
M
UTF-16 Encoding:
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
UTF-32 Encoding:
M
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
0x0001F60A
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
Representation
😊
ec
😊
iT
Conclusion:
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
encoding scheme:
ec
UTF-8:
iT
Example:
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
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
Example:
0xDE0A).
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
Emoji
iT
LP
Summary of Size for Each Encoding:
sL
UTF-8: Uses 1 to 4 bytes depending on the character.
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
especially for English, since it uses only 1 byte for ASCII characters.
ev
What is a Compiler?
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP
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
(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?
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.
Ruby.
hn
ec
iT
ev
# Example in Python
LP
num1 = int(input("Enter first number: "))
sL
num2 = int(input("Enter second number: "))
ie
og
Code Explanation:
ol
result = num1 + num2: Adds num1 and num2, storing the result in
iT
result.
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
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
is a Python interpreter).
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
The PVM interprets the bytecode and translates it into machine code
that the computer's CPU can understand.
iT
Next, the bytecode LOAD_CONST 20 would load the value 20, and
ADD would add num1 and num2 together.
LP
LOAD_CONST 20 # Load constant 20
sL
BINARY_ADD # Add the two constants
ie
og
The CPU executes the machine-level instructions generated by the
ol
The print() function sends this value to the computer’s display screen.
Each character in the output (like "The result is: 30") is encoded using
ASCII (or Unicode) encoding.
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
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
tasks.
● Sublime Text: Known for its speed and simplicity, with many
iT
customizable features.
● Notepad++: A simple, free code editor for Windows that
ev
LP
sL
2. What is an IDE (Integrated Development Environment)?
● Code Editor: Like in a code editor, an IDE will have a text editor
with syntax highlighting, indentation, and auto-completion.
ev
LP
sL
Examples of IDEs:
Pros of IDEs:
M
Cons of IDEs:
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
● For Small Projects: Code editors are excellent for quick edits,
iT
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
LP
sL
ie
og
ol
hn
ec
iT
ev
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
(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
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
Multiple Variables:
x, y, z = 10, 20, 30
print(f"x = {x}, y = {y}, z = {z}")
LP
sL
ie
og
ol
hn
ec
iT
ev
M
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)
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
3. Complex (complex):
o Stores numbers with a real and imaginary part.
iT
o Example:
num = 4 + 3j
ev
print(type(num))
M
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
print(type(fruits))
Output: <class 'list'>
2. Tuple (tuple):
o An ordered collection of items, which cannot be modified
(immutable).
o Example:
person = {"name": "John", "age": 30}
print(type(person))
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
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))
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
x = 10
ev
print(type(x))
M
LP
2. Convert String to Integer:
x = "25"
sL
x_int = int(x)
print(type(x_int))
ie
og
Output: <class 'int'>
ol
unique_fruits = set(fruits)
ec
print(unique_fruits)
iT
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
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
In essence:
iT
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
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
1. Basic Example
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
Since the input() function returns a string, you need to convert it into
the desired numeric type (e.g., int, float) for mathematical operations.
LP
sL
Output:
Enter your age: 25
ie
Next year, you will be 26 years old.
og
Example: Converting Input to Float
ol
number = float(number)
print("Half of the number is", number / 2)
ec
iT
Output:
ev
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
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
Exercises
iT
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
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
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
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)
Example:
iT
string = "Python"
print(string[0:4])
ev
M
print(string[::2])
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.
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
string = "hello"
iT
print(string.upper())
Output: HELLO
ev
print(string.replace("World", "Python"))
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
print(string.find("World"))
M
Output: 7
print(string.startswith("Py"))
Output: True
LP
Output: True
sL
11. isalpha(): Checks if the string contains only alphabetic
characters.
ie
string = "Hello"
og
print(string.isalpha())
Output: True
ol
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)
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
."""
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
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
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
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
^ XOR 5^3 6
~ NOT ~5 -6
<< Left Shift 5 << 1 10
>> Right Shift 5 >> 1 2
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
Example:
x = 10
LP
x += 5
sL
print(x)
ie
Output: 15
og
6. Membership Operators
ol
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:
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
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
• if
• else
ec
if condition1:
M
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
condition evaluates to
False.
M
Example:
age = 16
if age >= 18:
print("You are eligible to vote!")
else:
print("You are not eligible to vote yet.")
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
print("Grade: A")
elif marks >= 60:
ec
print("Grade: B")
iT
else:
print("Grade: C")
ev
M
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
Example:
ev
age = 20
M
citizenship = "Indian"
if age >= 18 and citizenship == "Indian":
print("You are eligible to vote.")
Example:
x = 10
LP
if x > 0:
pass
sL
Code to be written later
ie
og
ol
if number % 2 == 0:
print("The number is even.")
ev
else:
print("The number is odd.")
M
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
print("Grade: C")
ev
else:
print("Grade: F")
M
if x = 10:
print("x is 10")
LP
Correct
sL
if x == 10:
ie print("x is 10")
og
Key Takeaways
ol
on conditions.
• Use if for a single condition, else for alternative actions, and elif
ec
Exercise:
M
LP
sL
ie
og
ol
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
Syntax:
ev
Output:
apple
banana
cherry
LP
for i in range(5):
print(i)
sL
Output:
0 ie
og
1
2
ol
3
4
hn
Output:
M
h
e
l
l
o
Syntax:
LP
counter = 0
sL
while counter < 5:
print(counter)
ie
counter += 1
og
Output:
ol
0
hn
1
2
ec
3
4
iT
password = "python123"
M
user_input = ""
while user_input != password:
user_input = input("Enter password: ")
print("Access granted!")
4. Nested Loops
Loops can be nested, meaning one loop is inside another.
Example:
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
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
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.
while True:
print("This will print endlessly unless we stop it.")
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): exit Exiting the loop. Goodbye!
import random
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
Precautions
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
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
Common Methods:
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")
in fruits
ec
iT
Why Mutable?
Lists are mutable because they allow in-place modifications, making
ev
2. Tuples
Definition:
A tuple is an ordered collection of items similar to a list, but tuples
are immutable.
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
Common Methods:
ev
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
Examples:
iT
#Creating a set
numbers = {1, 2, 3, 4, 5}
ev
#Adding an element
numbers.add(6)
print(numbers) #Output: {1, 2, 3, 4, 5, 6}
#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 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
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
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
random Library
Here are some interesting programs that combine Python's data
M
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"]
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
71)} #A to F
print("Random dictionary:", random_dict)
ev
M
import random
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
print(f"{key}: {value}")
ec
import random
ev
M
values]
#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
print(f"Numbers: {numbers}")
print(f"Even numbers: {even_numbers}")
print(f"Odd numbers: {odd_numbers}")
LP
sL
ie
Chapter 9: Python Functions
og
Functions are reusable blocks of code that perform a specific task.
ol
1. What is a Function?
ec
data as a result.
ev
Syntax:
M
Example:
def greet(name):
return f"Hello, {name}!"
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
Example:
M
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
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
LP
Example:
sL
def greet(name="Guest"):
print(f"Hello, {name}!")
ie
greet() #Output: Hello, Guest!
og
greet("Alice") #Output: Hello, Alice!
ol
def add_all(*numbers):
ev
return sum(numbers)
print(add_all(1, 2, 3, 4)) #Output: 10
M
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
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
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
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
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)
● factorial(2) = 2 * 1 = 2
● factorial(3) = 3 * 2 = 6
● factorial(4) = 4 * 6 = 24
● factorial(5) = 5 * 24 = 120
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
import random
iT
LP
sL
ie
og
ol
hn
ec
iT
Syntax of 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
'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.
LP
mode doesn't exist.
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
content = file.read()
print(content)
M
2. Writing to a File
● Mode: 'w'
LP
3. Appending to a File
sL
● Mode: 'a'
4. Creating a File
hn
● Mode: 'x'
try:
ec
● Mode: 'r+'
LP
with open("example.bin", "wb") as file:
sL
file.write(b"This is binary data.")
ie
og
# Reading binary data
binary_content = file.read()
print(binary_content)
ec
iT
error occurs.
print(file.read())
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
Exception Description
ev
Error attempted.
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
Basic Example
ev
try:
M
result = 10 / number
print(f"Result: {result}")
except ZeroDivisionError:
except ValueError:
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
except IOError:
ev
try:
except ValueError:
else:
LP
print("Operation successful!")
sL
The finally Block
ie
The finally block executes regardless of whether an exception
occurred.
og
try:
ol
content = file.read()
ec
print(content)
iT
except FileNotFoundError:
ev
finally:
file.close()
Raising Exceptions
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)
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
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
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
")
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.
3. Multiplication Table
Print the multiplication table of a number provided by the user.
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
result = 1
iT
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
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
Exploring Libraries
1. Math Library
iT
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
3. Time Module
The time library is used to manage time-related tasks.
Example Functions:
import time
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
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
2. sys.argv
M
import sys
LP
3. sys.exit()
sL
● Purpose: Exits the Python interpreter with an optional exit code.
● Example:
import sys
ie
og
print("Program is running...")
4. sys.path
ec
for modules.
● Example:
ev
import sys
print(sys.path)
M
import sys
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
import re
iT
if match:
print(match.group()) # Output: 42
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
if match:
iT
print(match.group()) # Output: 42
ev
LP
(space, tab,
newline).
sL
. Matches any r"." re.search(r".", H
ie
character except "Hello")
og
a newline.
ol
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
Here’s the enhanced table with Python syntax for common regular
expression functions and their patterns:
Output
Function Purpose Python Example
Syntax
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
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
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
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.
import re
def is_valid_email(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"
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
python
ec
Copy code
iT
1. r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
ev
M
1. ^
● Purpose: Ensures that the pattern starts matching from the start
of the email string.
2. [a-zA-Z0-9._%+-]+
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
● john.doe
hn
● user_name
● user+123
ec
iT
3. @
ev
4. [a-zA-Z0-9.-]+
[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).
sL
● example
● sub-domain
ie
og
5. \.
ol
6. [a-zA-Z]{2,}$
.co.in).
● 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. $
LP
Putting It All Together
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
● user.name@example.com
iT
● john_doe@sub.domain.org
● megha+test@company.co.in
ev
The json module is used for encoding and decoding JSON (JavaScript
Object Notation) data, which is a lightweight format for storing and
transporting data.
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
data = json.loads(json_string)
ev
json.dump(data, file)
www.mevitechnologies.com © 2024 Mevi Technologies LLP. All rights reserved. support@mevitechnologies.com
Python Notes By Mevi Technologies LLP
data = json.load(file)
print(data)
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
string.punctuation
password = ''.join(random.choice(characters) for _ in
ec
range(length))
iT
LP
sL
ie
og
ol
hn
ec
iT
ev
(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.
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.
LP
Simple Example (without self and objects initially):
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
class Car:
ev
color = "Red"
M
brand = "Toyota"
def drive():
LP
Car.drive() # Outputs: The car is driving.
sL
ie
og
2. Object:
ol
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
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()
your_car = Car()
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
○ 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
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
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
specific object.
● It is the first parameter of any instance method in a class (not the
M
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
# Calling methods
my_car.drive() # Outputs: The Red Toyota car is driving.
your_car.drive() # Outputs: The Blue Honda car is driving.
Explanation:
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
object.
iT
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.
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
Explanation:
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
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
def child_method(self):
iT
def parent_method(self):
print("This is an overridden method in the child class.")
# 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
Explanation:
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
class Car(Vehicle):
ev
constructor
self.color = color
print(f"Color: {self.color}")
LP
Explanation:
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
3. Multilevel Inheritance:
ec
class Animal:
ev
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 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
Explanation:
ev
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
self.brand = brand
iT
self.model = model
# Creating an object of the HybridCar class
ev
Explanation:
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
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
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
class Calculator:
ev
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
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
# Parent class
class Animal:
ec
def speak(self):
iT
# 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")
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
● When the speak() method is called on dog and cat objects, it calls
the overridden methods from their respective classes, not the
ev
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:
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
class Shape:
def area(self):
ev
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
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
Explanation:
ev
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
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
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
Benefits of Encapsulation:
1. Data Hiding: Prevents external code from changing an object’s
ev
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
return self.__name
iT
if len(name) > 0:
self.__name = name
else:
print("Name cannot be empty.")
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
print(person.get_age()) # Output: 30
iT
person.set_name("Alice")
M
person.set_age(25)
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
3. Encapsulation:
○ By using encapsulation, we ensure that the name and age
iT
● 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 radius(self):
M
return self.__radius
if value > 0:
self.__radius = value
else:
print("Radius must be positive.")
LP
@property
def area(self):
sL
return 3.14 * (self.__radius ** 2)
ie
# Creating an object of Circle class
og
circle = Circle(5)
ol
print(circle.radius) # Output: 5
print(circle.area) # Output: 78.5
ec
iT
print(circle.radius) # Output: 10
M
Explanation:
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
meant to be subclasses.
2. Interfaces (via Abstract Methods): Methods that must be
implemented by derived classes.
ev
M
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
● You don't need to know how it spins the drum or heats the
water (how it does it).
ev
M
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!")
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
3. Concrete Method:
○ The sleep() method in the base class can be used directly by
iT
all subclasses.
ev
class Payment(ABC):
@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
credit_payment = CreditCardPayment()
iT
paypal_payment = PayPalPayment()
ev
Explanation:
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
LP
sL
ie
Chapter 12 Iterators , Generators and
og
Modules, Packages in Python
ol
# math_operations.py
ev
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
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.
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
# main.py
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
print(next(iterator)) # Output: 1
ec
print(next(iterator)) # Output: 2
iT
print(next(iterator)) # Output: 3
ev
M
● Custom Iterator:
class MyIterator:
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):
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
● 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
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
print(num)
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