Python O'Level
Python O'Level
Python एक high-level, interpreted programming language है जिसे Guido van Rossum ने 1991 में
develop किया था। यह अपने simple and readable syntax के लिए जाना जाता है , जो इसे beginners
औरexperienced programmers दोनों के लिएideal बनाता है।Python का use web development, data
analysis, artificial intelligence, machine learning, automation, औरscientific computing जैसे fields में
व्यापक(widely) used जाताहै। this is Fourth generation language.
1. Numeric Types
• int → Integer numbers (e.g., 10, -5, 1000)
• float → Floating-point numbers (e.g., 3.14, -0.5, 2.7e3)
• complex → Complex numbers (e.g., 3 + 4j, 2 - 7j)
2. Sequence Types
• str → String (e.g., 'Hello', "Python", "123")
• list → List (ordered, mutable collection) (e.g., [1, 2, 3], ['a', 'b', 'c'])
• tuple → Tuple (ordered, immutable collection) (e.g., (1, 2, 3), ('x', 'y',
'z'))
• range → Range of numbers (e.g., range(10), range(1, 5, 2))
3. Set Types
• set → Unordered collection of unique elements (e.g., {1, 2, 3}, {'apple',
'banana'})
• frozenset → Immutable version of a set (e.g., frozenset({1, 2, 3}))
4. Mapping Type
• dict → Dictionary (key-value pairs) (e.g., {'name': 'Alice', 'age': 25})
5. Boolean Type
• bool → Boolean values (True, False)
6. Binary Types
• bytes → Immutable sequence of bytes (e.g., b'hello')
• bytearray → Mutable sequence of bytes (e.g., bytearray(5))
• memoryview → A memory view object (e.g., memoryview(b'abc'))
7. None Type
• NoneType → Represents a null value (None)
Assembler, Compiler, and Interpreter: Differences & Explanation
These are three types of language processors used in programming to convert high-level or low-
level code into machine-readable instructions.
1️⃣ Assembler
🔹
🔹 Converts Assembly Language to Machine Code (Binary).
Assembly language is a human-readable version of machine code, using mnemonics like MOV,
🔹
ADD, SUB, etc.
✅
The assembler translates this into binary instructions that the CPU can execute directly.
✅
✅
Operating System Development
Microcontroller Programming
✅
Hardware Interfacing
✅
✅
Low-Level Language – Directly interacts with hardware.
Fast Execution – Runs faster than high-level languages.
✅
Platform Dependent – Works only for a specific processor architecture.
Example:
MOV AX, 5
ADD AX, 3
🔹
🔹
Creates an independent executable (.exe/.out) file.
Faster execution but requires compilation before running.
Examples: C, C++, Java (partially), Rust
✅ Example (C Language)
#include <stdio.h>
int main() {
printf("Hello, World!");
return 0;
}
3️⃣ Interpreter
🔹
🔹 Executes Code Line-by-Line Without Creating an Executable File.
🔹
🔹
Slower than compiled languages but easier for debugging.
Used in scripting and interactive environments.
Examples: Python, JavaScript, PHP, Ruby
✅
symbol references and links external libraries.
Key Functions of a Linker:
• Combines different object files (.o or .obj) into a single executable.
• Resolves function and variable references.
• Links standard and user-defined libraries.
• Removes duplicate code (if needed).
📌 Types of Linkers:
• Static Linker – Links all required libraries into the executable at compile time.
• Dynamic Linker – Links external libraries at runtime (e.g., .dll in Windows, .so in
Linux).
2. Loader
A loader is a system program that loads the executable file into memory and prepares it for
✅
execution. It is part of the operating system.
Key Functions of a Loader:
• Loads the executable file from disk to RAM.
• Allocates memory for program execution.
• Resolves dynamic library dependencies (if needed).
📌
• Starts the program execution.
Types of Loaders:
• Absolute Loader – Loads the program at a fixed memory location.
• Relocating Loader – Adjusts memory addresses dynamically.
• Dynamic Loading – Loads modules only when needed (saves memory).
🔹
Conclusion
🔹
🔹
Linker combines object files and libraries into a single executable.
Loader loads the executable into RAM and runs the program.
Both are crucial in converting source code into a running program
*Comment in python:
In Python, comments are used to explain code and are ignored by the interpreter. Here's
how to use them:
1. Single-line comments
2. Multi-line comments
•Python doesn’t have a dedicated syntax for multi-line comments, but you can use triple
quotes (''' or """). These are technically strings but work as comments if not assigned to a
variable.
'''
This is a multi-line "comment".
It spans multiple lines.
'''
print("Hello, World!")
•Triple quotes are also used for docstrings to document functions, classes, or modules.
They are placed immediately after the definition.
Strings in Python:
Strings are sequences of characters enclosed in quotes. They are immutable (cannot be
modified after creation) and support various operations. Here’s a breakdown of key
concepts
1. Creating Strings
•Use single quotes ('Hello'), double quotes ("Python"), or triple quotes for multi-line
strings:
s1 = 'Single quotes'
s2 = "Double quotes"
s3 = '''This is a
multi-line string'''
2. Escape Characters
3. String Operations
4. String Methods
Commonly used methods (strings are immutable, so methods return new strings):
Case Conversion:
s = "Hello"
print([Link]()) # "hello"
print([Link]()) # "HELLO"
Trimming Whitespace:
s = " Python "
print([Link]()) # "Python"
Replacing Substrings:
s = "I like Java"
print([Link]("Java", "Python")) # "I like Python"
5. String Formatting
format() Method:
print("{} + {} = {}".format(2, 3, 5)) # "2 + 3 = 5"
Old-style (% operator):
print("Value: %d, Text: %s" % (10, "Hi")) # "Value: 10, Text: Hi"
6. String Immutability
Iteration:
for char in "Python":
print(char)
Exam Tips
•Syntax: Remember quotes (', ", '''), escape characters (\n, \t), and raw strings (r"...").
•Immutability: Operations return new strings; original remains unchanged.
•Formatting: Focus on f-strings and format() for exams.
•Common Errors: Mixing quote types (e.g., 'He's here' is invalid; use "He's here").
Example Code
# Multi-line string with triple quotes
poem = '''Roses are red,
Violets are blue,
Python is awesome,
And so are you!'''
*Key Differences:
5. Bitwise Operators
6. Identity Operators
8. Ternary Operator
9. Increment/Decrement Operators
x += 1 # Increment by 1 (equivalent to x = x + 1)
x -= 1 # Decrement by 1
Example:
count = 5
count += 1 # 6
count -= 1 # 5
*Operator Precedence:
[Link] ()
[Link] **
[Link] NOT ~, Unary +, -
[Link] *, Division /, Floor //, Modulus %
[Link] +, Subtraction -
[Link] shifts <<, >>
[Link] AND &
[Link] XOR ^
[Link] OR |
[Link] (==, !=, >, <, etc.)
[Link] NOT not
[Link] AND and
[Link] OR or
Example:
result = 5 + 3 * 2 ** 2 # Evaluates to 5 + (3 * 4) = 17
Exam Tips
# Membership check
s = "Python"
print("th" in s) # True
# Bitwise operations
a = 5 # 0b101
b = 3 # 0b011
*Exchanging values of two variables:
a=5
b = 10
# Swap values
a, b = b, a
print(a) # Output: 10
print(b) # Output: 5
or
*To calculate the summation of a set of numbers in Python, you can use the
built-in sum() function:
Example:
Alternative Methods:
1. Using a for loop:
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
total += num
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda x, y: x + y, numbers)
1. Built-in Functions
The format() function allows flexible formatting (no prefixes, uppercase hex, padding,
etc.):
Syntax:
format(decimal_number, format_specifier)
import math
a = 48
b = 18
gcd_value = [Link](a, b)
print(gcd_value) # Output: 6
Features:
•Handles negative inputs by taking absolute values.
•Returns 0 if both inputs are 0.
Example with Edge Cases:
print([Link](-12, 18)) # Output: 6 (ignores negatives)
print([Link](0, 5)) # Output: 5
print([Link](0, 0)) # Output: 0
Iterative Approach:
Recursive Approach:
•gcd(48, 18):
•48 % 18 = 12 → gcd(18, 12)
•18 % 12 = 6 → gcd(12, 6)
•12 % 6 = 0 → GCD is 6.
Key Takeaways:
Example:
1) print(10 / 0) # ZeroDivisionError
2) num=10
text=”hello”
print(num+text) #TypeError unsupported operand
3) name = "Alice"
print(nam) # NameError: name 'nam' is not defined
4) my_list = [1, 2, 3]
print(my_list[3]) # IndexError: list index out of range
7) print("Hello")
print("World") # This line is indented unnecessarily
or
for i in range(10):
print(i) #IndentationError: expected an indented block
after 'for' statement on line 1
[Link] Errors :
Code runs but gives wrong results.
Example:
1) def multiply(a, b):
return a + b # Logical error (should be a * b)
2) def calculate_area(radius):
return 2 * 3.14 * radius # This is actually the formula for
circumference, not area.
Debugging Techniques
[Link] Print Statements:
Track variable values and flow.
Example:
print("Current value of x:", x)
[Link] Debugger (pdb):
Step through code line-by-line.
Example:
import pdb; pdb.set_trace() # Set a breakpoint
[Link] Tools :
Use debuggers in VS(Visual Studio) Code, PyCharm, IDLE, Spyder,
Jupyter Notebook, Thonny etc.
[Link] Error Trace backs :
Read error messages to locate issues.
Buggy Code:
a = 10
b=0
result = a / b # ZeroDivisionError
print(result)
Debugged Code:
a = 10
b=0
try:
result = a / b
except ZeroDivisionError:
result = "Undefined (Division by zero)"
print("Result:", result)
1. What is an Exception?
An exception is an error that occurs during the execution of a program that disrupts the normal
🔹
flow.
Common Exception Types in Python
Exception Description
ZeroDivisionError Dividing by zero (10 / 0)
ValueError Invalid value for a function (int("abc"))
TypeError Unsupported operation between data types ("hello" + 5)
Exception Description
IndexError Accessing an invalid list index (list[10])
KeyError Accessing a non-existent dictionary key (dict['key'])
FileNotFoundError Trying to open a non-existing file
AttributeError Calling a non-existent attribute or method
try:
result = 10 / 0 # This will cause ZeroDivisionError
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
try:
num = int(input("Enter a number: ")) # Might cause ValueError
result = 10 / num # Might cause ZeroDivisionError
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except ValueError:
print("Error: Invalid input! Please enter a number.")
✅
✅
Input: abc → Output: Error: Invalid input! Please enter a number.
Input: 0 → Output: Error: Cannot divide by zero!
try:
x = int("hello") # This will cause ValueError
except Exception as e:
print(f"An error occurred: {e}")
✅ Output: An error occurred: invalid literal for int() with base 10:
'hello'
5. Using else and finally
🔹
🔹
else executes if no exception occurs.
finally executes always (whether an error occurs or not).
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except ValueError:
print("Error: Invalid input!")
else:
print("Success! The result is:", result) # Runs if no error
finally:
print("Execution finished.") # Always runs
✅
✅
Input: 2 → Output: Success! The result is: 5.0
Input: 0 → Output: Error: Cannot divide by zero!
def check_age(age):
if age < 18:
raise ValueError("Error: Age must be 18 or above!")
print("Access granted.")
try:
check_age(16) # This will cause an error
except ValueError as e:
print(e)
class NegativeNumberError(Exception):
pass # Custom exception class
def check_positive(num):
if num < 0:
raise NegativeNumberError("Error: Negative numbers are not allowed!")
try:
check_positive(-5)
except NegativeNumberError as e:
print(e)
try:
file = open("non_existing_file.txt", "r")
content = [Link]()
[Link]()
except FileNotFoundError:
print("Error: File not found!")
Conclusion
✔ Exception Handling makes programs more reliable and user-friendly by preventing crashes.
✔ Always use try-except to handle errors gracefully.
✔ Use finally to ensure important cleanup (like closing a file).
✔ Custom exceptions improve error readability in complex programs.
Python की तकनीकी ताकत | Technical Strength of Python
Python एक शक्तिशाली और लोकप्रिय प्रोग्रामिंग भाषा है, जिसकी कई तकनीकी खूबियाँ (Technical
Strengths) हैं।
🔹
🔹
वेब डेवलपमेंट (Web Development): Django, Flask, FastAPI
स्क्रिप्टिंग और ऑटोमेशन (Scripting & Automation): Selenium, BeautifulSoup
नेटवर्किं ग (Networking): Scapy, Paramiko
निष्कर्ष | Conclusion
Python एक बहु-उद्दे श्यीय (Versatile), शक्तिशाली (Powerful), और सरल (Easy-to-Use) प्रोग्रामिंग
भाषा है, जो वेब डेवलपमेंट से लेकर आर्टिफिशियल इंटेलिजेंस तक कई क्षेत्रों में उपयोग की जाती है।
Literals in Python
What are Literals?
A literal in Python is a fixed value assigned to a variable or used directly in expressions. These
values do not change and represent constant values in the program.
1. String Literals
String literals are sequences of characters enclosed in single ('), double ("), or triple quotes ('''
✅
or """ """).
Examples:
single_quote = 'Hello, Python!'
double_quote = "Welcome to Python"
triple_single = '''This is
a multi-line string.'''
triple_double = """Another
multi-line string."""
2. Numeric Literals
✅
Numeric literals include integers, floating-point numbers, and complex numbers.
Examples:
# Integer Literal
integer_num = 100
# Floating-Point Literal
float_num = 10.5
3. Boolean Literals
✅
Boolean literals represent True or False values.
Examples:
is_python_fun = True
is_java_hard = False
🔹 Boolean literals internally store True as 1 and False as 0.
Example:
print(True + False) # Output: 1 (1 + 0)
✅
The None literal represents the absence of a value or a null value.
Example:
empty_value = None
print(empty_value) # Output: None
✅
Python supports collection literals:
Examples:
# List Literal
fruits = ["Apple", "Banana", "Cherry"]
# Tuple Literal
numbers = (1, 2, 3, 4, 5)
# Dictionary Literal
student = {"name": "Alice", "age": 20}
# Set Literal
unique_values = {1, 2, 3, 4, 5}
✅
Python provides escape sequences to represent special characters.
Common Escape Sequences:
✅
Python supports number literals in different bases:
Examples:
binary_num = 0b1010 # Binary (10 in decimal)
octal_num = 0o12 # Octal (10 in decimal)
hex_num = 0xA # Hexadecimal (10 in decimal)
Summary
Literal Type Example
String "Hello" 'Python' '''Multiline'''
Integer 100, -50
Float 10.5, -2.7
Complex 3 + 4j
Boolean True, False
None None
List [1, 2, 3]
Tuple (1, 2, 3)
Dictionary {"key": "value"}
Set {1, 2, 3}
Binary 0b1010 (Binary 10)
Octal 0o12 (Octal 10)
🔹
Hexadecimal 0xA (Hex 10)
Literals are fundamental building blocks of Python programming!
1. Integer (int)
✅
An integer is a whole number, either positive, negative, or zero, without a decimal point.
Example:
x = 10 # Positive Integer
y = -5 # Negative Integer
z = 0 # Zero
✅
A floating-point number (real number) contains a decimal point or is written in scientific notation.
Example:
x = 10.5 # Float number
y = -3.14 # Negative float
z = 2.0 # Float, even though it's a whole number
✅ Scientific Notation:
a = 1.2e3 # 1.2 × 10³ = 1200.0
b = 2.5e-4 # 2.5 × 10⁻⁴ = 0.00025
print(int_x) # Output: 10
✅
Python supports complex numbers, which consist of a real and an imaginary part.
Example:
c1 = 3 + 4j
c2 = 5 - 2j
✅
In Python, real numbers are represented using the float type.
Example:
x = 3.14159 # Real number (float)
y = -2.71828 # Real number (negative)
x = 4.5
print(isinstance(x, [Link])) # Output: True
5. Sets (set)
✅
A set is an unordered collection of unique elements.
Example:
s = {1, 2, 3, 3, 2, 1} # Duplicates are removed automatically
✅ Set Operations:
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
✅ Modifying Sets:
numbers = {1, 2, 3}
[Link](4) # Add element
[Link](2) # Remove element
Summary Table
Data Type Example Description
Integer (int) x = 10 Whole numbers
Float (float) x = 3.14 Real numbers (decimal values)
Complex (complex) c = 2 + 3j Numbers with real and imaginary parts
Real Numbers (float) x = 5.75 Subset of floats
Set (set) {1, 2, 3} Unordered collection of unique elements
Accepting Input from Console in Python
Python provides the input() function to take user input from the console. The input received is
always a string by default, but it can be converted into other data types like integers, floats, or lists.
✅
The input() function allows users to enter data during program execution.
Example:
name = input("Enter your name: ")
print("Hello,", name)
Output:
Enter your name: Alice
Hello, Alice
✅ Explanation:
• The input() function takes user input.
✅
Since input() always returns a string, we use int() to convert it into an integer.
Example:
age = int(input("Enter your age: "))
print("Your age is:", age)
Output:
Enter your age: 25
Your age is: 25
🚨 Note: If the user enters a non-numeric value, Python will raise an error.
✅
For decimal numbers, use float().
Example:
price = float(input("Enter the product price: "))
print("Price:", price)
Output:
Enter the product price: 99.99
Price: 99.99
✅
Python allows multiple inputs in one line using split().
Example:
x, y = input("Enter two numbers separated by space: ").split()
print("First Number:", x)
print("Second Number:", y)
Output:
Enter two numbers separated by space: 10 20
First Number: 10
Second Number: 20
🚀 Converting to Integers:
x, y = map(int, input("Enter two numbers: ").split())
print("Sum:", x + y)
Output:
Enter two numbers: 5 10
Sum: 15
✅
We can take multiple values and store them in a list.
Example:
numbers = list(map(int, input("Enter numbers separated by space: ").split()))
print("List of Numbers:", numbers)
Output:
Enter numbers separated by space: 1 2 3 4 5
List of Numbers: [1, 2, 3, 4, 5]
6. Accepting a String Input Without a Prompt
✅
If you don’t pass a prompt message in input(), it will still work.
Example:
data = input()
print("You entered:", data)
✅
use try-except to handle errors.
Example:
try:
num = int(input("Enter an integer: "))
print("You entered:", num)
except ValueError:
print("Invalid input! Please enter a valid integer.")
Output:
Enter an integer: abc
Invalid input! Please enter a valid integer.
✅
To take a complex number as input, convert it using complex().
Example:
c = complex(input("Enter a complex number (e.g., 3+4j): "))
print("Complex Number:", c)
✅
Since input() always returns a string, we can manually convert "True"/"False" to a Boolean.
Example:
bool_value = input("Enter True or False: ").strip().lower() == "true"
print("Boolean Value:", bool_value)
Output:
Enter True or False: True
Boolean Value: True
10. Accepting Input Without Pressing Enter (Advanced)
If you want to accept input without pressing Enter, use getch() from the msvcrt module
✅
(Windows).
Example (Windows only):
import msvcrt
print("Press any key: ")
key = [Link]()
print("You pressed:", [Link]())
Summary Table
Input Type Example Code Conversion
String Input name = input("Enter name: ") No conversion needed
num = int(input("Enter number:
Integer Input ")) int()
price = float(input("Enter
Float Input float()
price: "))
Multiple x, y = map(int, input().split()) map(int, input().split())
Inputs
nums = list(map(int, list(map(int,
List Input input().split())) input().split()))
Complex c = complex(input()) complex()
Number
bool_value =
Boolean Input input().strip().lower() == Custom conversion
"true"
Key Takeaways
✔ input() takes input as a string by default.
✔ Convert input to int (int()), float (float()), or other types as needed.
✔ Use split() and map() for multiple inputs.
✔ Handle errors using try-except.
Printing Statements in Python
Python provides the print() function to display output on the screen. It can print strings,
numbers, variables, multiple values, formatted text, and even special characters.
✅
The simplest way to print something in Python.
Example:
print("Hello, World!")
Output:
Hello, World!
2. Printing Variables
✅
We can print variables by passing them inside print().
Example:
name = "Alice"
age = 25
print(name)
print(age)
Output:
Alice
25
✅
We can print multiple values using commas , or string concatenation (+).
Output:
Name: Alice Age: 25
✅ Using string concatenation (+):
print("Name: " + name + ", Age: " + str(age))
Output:
Name: Alice, Age: 25
🚨 Note: If you use +, all values must be strings (str()). Otherwise, it will cause an error.
✅
The sep parameter controls how values are separated.
Example:
print("Apple", "Banana", "Cherry", sep=" - ")
Output:
Apple - Banana - Cherry
Output:
PythonProgramming
✅
The end parameter changes the default newline (\n) behavior.
Output:
Hello World!
Output:
Loading... Done!
6. Printing Using format()
✅
The .format() method allows formatted printing.
Example:
name = "Alice"
age = 25
Output:
My name is Alice and I am 25 years old.
Output:
My name is Alice and I am 25 years old.
✅
f-strings provide an easier way to format strings.
Example:
name = "Alice"
age = 25
Output:
My name is Alice and I am 25 years old.
Output:
Sum of 5 and 10 is 15
Output:
Hello World
✅ Backslash (\\):
print("This is a backslash: \\")
Output:
This is a backslash: \
✅ Quotes in Strings:
print("He said, \"Python is awesome!\"")
print('It\'s a great day!')
Output:
He said, "Python is awesome!"
It's a great day!
9. Printing in a Loop
✅ Example:
for i in range(1, 6):
print(f"Number {i}")
Output:
Number 1
Number 2
Number 3
Number 4
Number 5
10. Printing a Dictionary in a Pretty Format
✅
Python’s json module can print dictionaries in a structured format.
Example:
import json
print([Link](data, indent=4))
Output:
{
"name": "Alice",
"age": 25,
"city": "New York"
}
✅
By default, print() prints with a newline. We can avoid this using end="".
Example:
print("Hello", end=" ")
print("World!")
Output:
Hello World!
✅
Use the file parameter in print() to write output to a file.
Example:
with open("[Link]", "w") as file:
print("Hello, File!", file=file)
Summary Table
Feature Example Output
Basic Print print("Hello") Hello
Multiple Values print("A", "B", sep="-") A-B
No Newline print("Hello", end=" ") Hello
Format Strings print(f"My age is {age}") My age is 25
Escape Characters print("Line1\nLine2") Line1 Line2
Write to File print("Hello", file=file) (Saves to file)
Conclusion
🔹
🔹
print() is a powerful function for displaying output in Python.
🔹
You can customize it using sep (separator), end (end character), and file (file output).
Formatted printing is easier with f-strings, .format(), and escape characters (\n,
🔹
\t).
Python allows printing Unicode characters, writing to files, and structuring JSON data.
Assignment statement:
An assignment statement in Python is used to assign a value to a variable. It's one of the most
basic and important concepts in any programming language.
🔹 Syntax:
variable_name = value
🔹 Examples:
x = 10
name = "Ankit"
price = 19.99
🔹 Multiple Assignments:
We can assign values to multiple variables in a single line:
a, b, c = 1, 2, 3
🔹 Compound Assignment:
Python supports compound assignment operators to modify and assign in one step:
x = 5
x += 3 # Same as: x = x + 3 → x becomes 8
x *= 2 # Same as: x = x * 2 → x becomes 16
🔹 Dynamic Typing:
In Python, you don't need to declare a variable type. The type is determined automatically when you
assign a value:
x = 10 # x is an integer
x = "hello" # now x is a string
Conditional Statements:
Conditional statements let a program choose what to do based on certain conditions. Think of it
like giving the computer a choice:
“If this happens, do that. Otherwise, do something else.”
🔹 1. if Statement
It checks one condition. If it's true, it runs the code.
👉 Syntax:
if condition:
# code to run if condition is true
✅ Example:
age = 18
🔹 2. if-else Statement
Checks a condition. If it’s true, it runs one block of code.
If false, it runs a different block.
👉 Syntax:
if condition:
# code if true
else:
# code if false
✅ Example:
marks = 40
👉 Syntax:
if condition1:
# code if condition1 is true
elif condition2:
# code if condition2 is true
else:
# code if none are true
✅ Example:
score = 75
🔸 Examples:
Example 1: range(5)
for i in range(5):
print(i)
Output:
0
1
2
3
4
Example 2: range(1, 6)
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
Output:
1
3
5
7
9
Output:
10
9
8
7
6
5
4
3
2
1
• range(1, 6) gives: 1, 2, 3, 4, 5
Example:
text = "Python Programming"
print(text[0:6]) # Python
print(text[7:18]) # Programming
Shortcut Slices
Slice Meaning Example Output
text[:6] From start to index 5 'Python'
text[7:] From index 7 to the end 'Programming'
text[:] The whole string (copy) 'Python Programming'
Example:
text = "abcdefg"
Additionally, Python provides loop control statements such as break, continue, and pass to
manage loop execution.
1. for Loop
The for loop is primarily used to iterate over sequences like lists, tuples, dictionaries, sets, and
strings.
Basic Syntax:
for variable in sequence:
# Code to execute
Output:
apple
banana
cherry
Output:
0
1
2
3
4
Output:
Ankit scored 85
Pankaj scored 90
Kanchan scored 88
2. while Loop
The while loop is used when the number of iterations is unknown and depends on a condition.
Basic Syntax:
while condition:
# Code to execute
Output:
0
1
2
3
4
(This will keep asking for input until the correct password is entered.)
3. Loop Control Statements
Python provides special statements to control loops:
Output:
0
1
2
3
4
Output:
0
1
3
4
Output:
0
1
2
3
4
4. Nested Loops (Loop Inside Another Loop)
Python allows loops to be nested.
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")
Output:
i=0, j=0
i=0, j=1
i=1, j=0
i=1, j=1
i=2, j=0
i=2, j=1
for i in range(1,11):
for j in range(1,11):
print(i*j,end=" ")
print("\n")
Output:
0
1
2
Loop completed successfully!
Output:
0
1
2
Loop ended normally!
If the loop is interrupted using break, the else block will not execute.
What is assert
The assert statement is used to test if a condition is true.
🔹 Syntax:
assert condition
OR
assert condition, "Error message"
✅ Example 1:
x = 10
assert x > 0 # This will pass because x is 10
print("x is positive")
✔️Output:
x is positive
❌ Example 2:
x = -5
assert x > 0, "x is not positive"
print("x is positive")
❌ Output:
AssertionError: x is not positive
Real-life Example:
You're checking if a student has passed:
marks = 45
assert marks >= 40, "Student has failed"
print("Student has passed")
❌
✔️This works if marks are 40 or more.
If marks are less than 40, it will show an error.
String Slice:
A slice is a way to extract a part of a string using its index positions.
The basic syntax:
string[start:stop]
Example:
text = "Python Programming"
print(text[0:6]) # Python
print(text[7:18]) # Programming
Shortcut Slices
Slice Meaning Example Output
text[:6] From start to index 5 'Python'
text[7:] From index 7 to the end 'Programming'
text[:] The whole string (copy) 'Python Programming'
Example:
text = "abcdefg"
Syntax:
my_list = [1, 2, 3, 4, 5]
🔹 Creating a List
numbers = [1, 2, 3, 4]
names = ["Alice", "Bob", "Charlie"]
mixed = [1, "Hello", 3.14, True]
nested = [1, 2, [3, 4], 5]
empty = []
🔹 List Operations
1. Slicing
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4]) # [20, 30, 40]
print(numbers[:3]) # [10, 20, 30]
print(numbers[2:]) # [30, 40, 50]
print(numbers[-3:-1]) # [30, 40]
print(numbers[::2] # [10,30,50]
2. Modifying Elements
numbers[1] = 25
print(numbers) # [10, 25, 30, 40, 50]
🔹 List Methods
Here are some commonly used list methods:
Method Description
append() Adds an item to the end of the list
insert() Inserts an item at a specific index
remove() Removes the first occurrence of the specified item
pop() Removes the item at the specified index (or last item)
clear() Removes all items from the list
index() Returns the index of the first occurrence of an item
count() Returns the number of times an item appears
sort() Sorts the list in ascending order
reverse() Reverses the list
copy() Returns a shallow copy of the list
extend() Adds elements of another list to the end
Examples:
fruits = ["apple", "banana", "cherry"]
Or with index:
for i in range(len(fruits)):
print(i, fruits[i])
🔹 List Comprehension (Advanced but powerful)
Quick way to create a new list using a loop.
squares = [x**2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
With condition:
even = [x for x in range(10) if x % 2 == 0]
print(even) # [0, 2, 4, 6, 8]
🔹 Nested Lists
Lists within lists:
matrix = [
[1, 2],
[3, 4],
[5, 6]
]
print(matrix[1][0]) # 3
🔹 Copying Lists
Do not do this:
a = [1, 2, 3]
b = a # both point to same list
Do this instead:
b = [Link]() # or b = list(a)
✅ Syntax
my_tuple = (1, 2, 3)
Important:
For a single-element tuple, you must include a comma:
t = (5,) # This is a tuple
not_tuple = (5) # This is just an integer
🔹 Creating Tuples
# With parentheses
t1 = (1, 2, 3)
# Empty tuple
empty = ()
# Nested tuple
nested = (1, 2, (3, 4), 5)
🔹 Accessing Tuple Elements
Same as with lists:
t = (10, 20, 30, 40)
print(t[0]) # 10
print(t[-1]) # 40
🔹 Slicing Tuples
t = (1, 2, 3, 4, 5)
print(t[1:4]) # (2, 3, 4)
print(t[:3]) # (1, 2, 3)
print(t[2:]) # (3, 4, 5)
🔹 Tuple Unpacking
You can assign each element of a tuple to a variable:
person = ("Alice", 25, "India")
print(name) # Alice
print(age) # 25
print(country) # India
a, *b, c = numbers
print(a) # 1
print(b) # [2, 3, 4]
🔹
print(c) # 5
Tuple Methods
Tuples have only two built-in methods:
Method Description
count() Returns number of times a value appears
index() Returns the index of the first occurrence of a value
Example:
t = (1, 2, 2, 3, 4, 2)
print([Link](2)) # 3
print([Link](3)) # 3
🔹 Why Use Tuples?
• Faster than lists (better performance for fixed data)
• Immutable, so safer from unintended changes
• Can be used as dictionary keys
• Good for representing fixed collections like coordinates, RGB values, etc.
🔹 Tuple vs List
Feature List ([]) Tuple (())
Mutability Mutable (can change) Immutable (cannot change)
Syntax [] ()
Speed Slower Faster
Methods Many methods available Only count() & index()
Use Cases Dynamic data Fixed data
🔹 Dictionary:
A dictionary is an unordered, mutable collection of key-value pairs. Each value is accessed using
its key (not an index like in lists or tuples).
✅ Syntax
my_dict = {
"name": "Alice",
"age": 25,
"city": "Mumbai"
}
🔹 Key Characteristics
Feature Description
Key-Value Pairs Items are stored as key: value
Unordered (Python <3.7) Order of elements not guaranteed
Mutable Can be changed (add/update/delete)
Keys are unique No duplicate keys allowed
Keys are immutable Strings, numbers, tuples (not lists/dicts)
🔹 Creating Dictionaries
# Empty dictionary
empty = {}
# With values
student = {
"name": "John",
"age": 21,
"grades": [85, 90, 92]
}
🔹 Accessing Values
✅ Using the key
print(student["name"]) # John
print(student["grades"]) # [85, 90, 92]
🔹 Modifying Dictionary
✅ Changing existing value
student["age"] = 22
🔹 Removing Items
Method Description
pop(key) Removes item with the given key
popitem() Removes last inserted item
del Deletes item by key or entire dict
clear() Removes all items
Examples:
[Link]("age")
[Link]()
del student["name"]
[Link]()
🔹 Dictionary Methods
Method Description
keys() Returns a view of all keys
values() Returns a view of all values
items() Returns key-value pairs as tuples
update() Adds items from another dictionary
copy() Returns a shallow copy
Example:
person = {
"name": "Sam",
"age": 30
}
🔹 Nesting in Dictionaries
✅ Dictionary inside dictionary
students = {
"101": {"name": "Alice", "age": 21},
"102": {"name": "Bob", "age": 22}
}
print(students["101"]["name"]) # Alice
🔹 Dictionary Comprehension
A quick way to create a dictionary using loops:
squares = {x: x**2 for x in range(5)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
✅ ✅ ✅
Feature List Tuple Dictionary
✅ ❌ ✅
Ordered? (since Python 3.7)
Mutable?
❌
Access by Index Index Key
Duplicate keys? — —
🔹 Real-World Example
Counting word frequency in a sentence:
sentence = "hello world hello python"
words = [Link]()
count = {}
print(count)
# Output: {'hello': 2, 'world': 1, 'python': 1}
Sets:
A set in Python is an unordered collection of unique and immutable elements. Sets are mutable
(can be modified), but the elements they contain must be immutable (like integers, strings, or
tuples).
3. Checking Membership
if 3 in my_set:
print("3 is in the set")
4. Length of a Set
print(len(my_set)) # Returns number of elements
---
✅ Syntax:
b = bytes([65, 66, 67])
print(b) # Output: b'ABC'
print(b[0]) # Output: 65
Here, 65, 66, and 67 are ASCII values for 'A', 'B', and 'C'.
🔹 bytearray in Python
• Mutable version of bytes (you can modify it).
• Sequence of integers (0-255)
• Also stores a sequence of bytes.
• Useful when you need to change or manipulate binary data.
✅ Syntax:
ba = bytearray([65, 66, 67])
print(ba) # Output: bytearray(b'ABC')
# Modify a byte
ba[0] = 68
print(ba) # Output: bytearray(b'DBC')
❌ ✅
Syntax Example b = bytes([1,2]) ba = bytearray([1,2])
✅
Can be modified? No Yes
Memory efficient Yes (slightly) Slightly more usage
🔷 1. Concatenation of Lists
Lists can be easily concatenated using the + operator.
✅ Example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
🔷 2. Concatenation of Tuples
Tuples are immutable, but you can concatenate them using + (which returns a new tuple).
✅ Example:
tuple1 = (10, 20)
tuple2 = (30, 40)
🔷 3. Concatenation of Dictionaries
Dictionaries don’t use the + operator. Instead, you can use:
✅ update() method:
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
[Link](dict2)
print(dict1) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
✅ Summary Table
Type Operator / Method Notes
List +, .extend() Mutable, ordered
Tuple + Immutable
Dictionary .update(), {**d1, **d2}, ` `
🔷 Sequence data type:
In Python, a sequence is an ordered collection of items where each item is associated with an
index (position). You can access the items using their index.
Feature Description
Indexing Access elements by position (starting at 0)
Slicing Extract part of the sequence
Iteration Loop through elements using for loop
Length Use len() to get number of elements
Membership test Use in or not in to check for values
Concatenation Combine sequences using +
Repetition Repeat sequence using *
🔸 Indexing Example:
name = "Python"
print(name[0]) # P
print(name[-1]) # n
🔸 Slicing Example:
nums = [10, 20, 30, 40, 50]
print(nums[1:4]) # [20, 30, 40]
🔸 Length Example:
print(len(nums)) # 5
🔸 Membership Test:
print(30 in nums) # True
print("y" in "Python") # True
🔸 Concatenation:
print([1, 2] + [3, 4]) # [1, 2, 3, 4]
print("Py" + "thon") # Python
print((1, 2) + (3, 4)) # (1, 2, 3, 4)
🔸 Repetition:
print([1, 2] * 3) # [1, 2, 1, 2, 1, 2]
print("Hi! " * 2) # Hi! Hi!
✅ ❌
Examples list, bytearray tuple, str, range, bytes
Can be modified?
✅ 2. Tuple:
point = (10, 20)
# point[0] = 15 ❌ Not allowed
✅ 3. String:
text = "hello"
# text[0] = "H" ❌ Not allowed
✅ 4. Range:
r = range(1, 6)
print(list(r)) # [1, 2, 3, 4, 5]
✅ 5. Bytes and Bytearray (Advanced):
b = bytes([65, 66, 67]) # Immutable
ba = bytearray([65, 66, 67]) # Mutable
✅ Summary Table
✅ ✅ ✅
Sequence Type Mutable Ordered Indexed Use Case
❌ ✅ ✅
list General-purpose
❌ ✅ ✅
tuple Fixed data
❌ ✅ ✅
str Text data
❌ ✅ ✅
range Efficient looping
✅ ✅ ✅
bytes Binary data
bytearray Mutable binary data
🔷 Mutability:
In Python, mutability refers to whether or not an object can be changed (modified) after it is
created.
• Mutable objects can be changed
• Immutable objects cannot be changed
✅ ❌
Property Mutable Immutable
Can be changed Yes No
list, dict, set, int, float, str, tuple, frozenset,
Examples
bytearray bytes
🔹 Mutable Objects
These can be modified in-place without changing their identity (memory location).
my_dict = {"a": 1}
my_dict["b"] = 2
print(my_dict)
# ✅ allowed
# {'a': 1, 'b': 2}
my_set={1,2,3}
my_set.add(4)
print(my_set)
# ✅ allowed
#{1,2,3,4}
🔹 Immutable Objects
These cannot be changed once created. If you try to modify them, Python creates a new object.
name = "Alice"
name[0] = "M" # ❌ Error: strings are immutable
t = (1, 2, 3)
t[0] = 10 # ❌ Error: tuples are immutable
Identity Check Using id()
a = [1, 2, 3]
print(id(a)) # e.g., 140209932548416
[Link](4)
print(id(a)) # Same ID → modified in-place
b = "hello"
print(id(b)) # e.g., 140209932548752
b += " world"
print(id(b)) # Different ID → new object created
Summary
Term Meaning
Mutable Can change content after creation
Immutable Cannot change content once created
Why care? Prevent bugs, understand behavior
🔹 List of Numbers
✅
numbers = [10, 20, 30, 40, 50]
1. Find Maximum
Use the built-in max() function:
maximum = max(numbers)
print("Maximum:", maximum)
✅
# Output: Maximum: 50
2. Find Minimum
Use the built-in min() function:
minimum = min(numbers)
print("Minimum:", minimum)
✅
# Output: Minimum: 10
🔹
# Output: Mean: 30.0
maximum = max(numbers)
minimum = min(numbers)
mean = sum(numbers) / len(numbers)
print("Maximum:", maximum)
print("Minimum:", minimum)
🔹
print("Mean:", mean)
print("Max:", max(numbers))
print("Min:", min(numbers))
print("Mean:", sum(numbers)/len(numbers))
Linear Search:
Linear search is a simple search algorithm that:
• Checks each element in the sequence one by one.
• Stops when the target value is found.
• Works for unsorted data.
# Example usage:
nums = [5, 10, 15, 20, 25]
target = 15
# Example:
nums = (3, 6, 9, 12)
target = 9
Output Example
If you search for 15 in [5, 10, 15, 20, 25], it prints:
Found at index 2
If you search for a number not in the list, like 30, it prints:
Not found
Key points:
•Time Complexity: O(n) - Checks each element once in the worst case.
•Space Complexity: O(1)/O(k) - Uses constant extra space.
•Works for both lists and tuples since they are iterable and indexable.
•Returns the first occurrence's index if duplicates exist.
•Returns -1 if the target is not found.
Counting the frequency of elements in a list using a dictionary:
print(frequency)
🧠 Output:
{1: 2, 2: 3, 3: 1, 4: 1}
🔸 Explanation:
• The key in the dictionary is the element from the list.
• The value is how many times that element appears.
print(frequency)
data = [1, 2, 2, 3, 1, 4, 2]
frequency = Counter(data)
print(frequency)
Output:
Counter({2: 3, 1: 2, 3: 1, 4: 1})
1. Defining a Function
A function in Python is defined using the def keyword.
Syntax:
def function_name(parameters):
# Function body (code block)
return value # (Optional)
Output:
Hello, welcome to Python!
greet("Ankit")
greet("Pankaj")
Output:
Hello, Ankit!
Hello, Pankaj!
Example: Function with Multiple Parameters
def add(a, b):
result = a + b
print("Sum:", result)
add(5, 10)
add(3, 7)
Output:
Sum: 15
Sum: 10
result = square(4)
print("Square:", result)
Output:
Square: 16
Output:
Addition: 12, Subtraction: 8, Multiplication: 20, Division: 5.0
Example:
def greet(name="Guest"):
print(f"Hello, {name}!")
6. Keyword Arguments
Python allows passing arguments using keywords (named arguments).
Example:
def student_info(name, age):
print(f"Name: {name}, Age: {age}")
student_info(age=20, name="Pankaj")
Output:
Name: Pankaj, Age: 20
print(add_numbers(2, 4, 6))
print(add_numbers(1, 3, 5, 7, 9))
Output:
12
25
Output:
name: Ankit
age: 22
course: Python
Syntax:
lambda arguments: expression
Example:
square = lambda x: x * x
print(square(5))
Output:
25
Output:
10
9. Recursive Functions
A function can call itself, which is called recursion.
print(factorial(5)) # 5 * 4 * 3 * 2 * 1 = 120
Output:
120
example()
# print(x) # This would cause an error because x is local to the function.
def example():
print("Inside function:", x)
example()
print("Outside function:", x)
Output:
Inside function: 10
Outside function: 10
def modify():
global x
x = 20
modify()
print(x) # Output: 20
Conclusion
Functions make Python programs modular, organized, and reusable.
• Use parameters for inputs.
• Use return for outputs.
• Use default arguments and keyword arguments for flexibility.
• Use *args and **kwargs for dynamic input.
• Use lambda functions for simple one-line functions.
• Use recursion for solving problems like factorials.
• Understand scope to manage variables properly.
**input(): is a built-in function
Syntax:
input(prompt)
• prompt (optional): A string that is displayed to the user before input is taken.
How it works:
• When input() is called, the program pauses and waits for the user to type something.
• After the user types input and presses Enter, the input is returned as a string.
Example:
name = input("Enter your name: ")
print("Hello,", name)
Important Points:
1. Always returns a string
If you want a number, you need to convert it:
age = int(input("Enter your age: "))
2. Can be used for any kind of user input, such as strings, numbers, etc., depending on how
you process the result.
**Eval(): is a built-in function that takes a string and evaluates it as a Python expression, then
returns the result.
📘 Syntax:
eval(expression, globals=None, locals=None)
• globals and locals (optional): Dictionaries used to define global and local variables.
🔹 Basic Example:
result = eval("3 + 4")
print(result) # Output: 7
The string "3 + 4" is evaluated as a real Python expression.
🔹 With Variables:
x = 10
y = 5
print(eval("x * y")) # Output: 50
**print(): function in Python is a built-in function used to display output on the screen.
📘 Syntax:
print(*objects, sep=' ', end='\n', file=[Link], flush=False)
Output:
Hello, world!
🔹 Key Parameters:
Parameter Description
*objects One or more values to print
sep String inserted between values (default is a space)
end What to print at the end (default is newline \n)
file Where to send the output (default is the screen)
flush Whether to force the output to be written immediately
🔹 Examples:
Multiple values:
print("Name:", "Alice")
# Output: Name: Alice
Custom separator:
print("2025", "05", "24", sep="-")
# Output: 2025-05-24
🔹 Print Variables:
name = "Bob"
print("Hello,", name)
# Output: Hello, Bob
** count():
The count() method returns the number of non-overlapping times a substring appears in a
string.
📘 Syntax:
[Link](substring, start=0, end=len(string))
🔸 Case-sensitive:
text = "Hello hello"
print([Link]("hello")) # Output: 1 (does NOT count "Hello")
📌 Key Points:
• count() is case-sensitive.
** find():
The find() method returns the index of the first occurrence of a substring in a string. If the
substring is not found, it returns -1.
📘 Syntax:
[Link](substring, start=0, end=len(string))
🔸 Case-sensitive:
text = "Hello"
print([Link]("h")) # Output: -1 (because "h" ≠ "H")
🆚 find() vs index():
• find() returns -1 if not found.
**rfind():
The rfind() method searches for a substring in a string from the right (end) and returns the
highest index where the substring is found.
If the substring is not found, it returns -1.
📘 Syntax:
[Link](substring, start=0, end=len(string))
Example:
text = "hello hello"
print([Link]("l")) # Output: 2
print([Link]("l")) # Output: 9
**capitalize():
The capitalize() method returns a new string with the first character in uppercase and the
rest in lowercase.
📘 Syntax:
[Link]()
**title():
The title() method returns a new string where the first letter of every word is capitalized,
and all other letters are lowercase.
📘 Syntax:
[Link]()
• No parameters.
• Returns a new string (does not change the original).
**lower():
The lower() method returns a new string where all uppercase letters are converted to
lowercase.
📘 Syntax:
[Link]()
• No arguments.
• Does not modify the original string (strings are immutable).
• Returns a new string in all lowercase.
⚡ Use case:
• Useful for case-insensitive comparisons:
user_input = "YES"
if user_input.lower() == "yes":
print("User agreed!")
**upper():
The upper() method returns a new string with all characters converted to uppercase.
📘 Syntax:
[Link]()
• No arguments.
• Does not change the original string.
• Returns a new string with all uppercase letters.
⚡ Use Case:
• Helpful for case-insensitive comparison or formatting:
user_input = "yes"
if user_input.upper() == "YES":
print("User agreed!")
**swapcase():
The swapcase() method switches the case of each letter in a string:
📘 Syntax:
[Link]()
• No parameters.
• Returns a new string with cases swapped.
• Does not modify the original string.
**islower():
The islower() method checks if all the alphabetic characters in the string are lowercase.
📘 Syntax:
[Link]()
• Returns False if there are any uppercase letters or no alphabetic characters at all.
✅ Example 1: All lowercase letters
text = "hello world"
print([Link]()) # Output: True
**isupper():
The isupper() method checks if all the alphabetic characters in the string are uppercase.
📘 Syntax:
[Link]()
• Returns False if there are any lowercase letters or no alphabetic characters at all.
📘 Syntax:
[Link]()
⚠️Notes:
• Only alphabetic characters affect the result.
• Words are separated by spaces or non-letter characters.
• Words like "It's" become title case if "I" and "T" are uppercase, but "It's" is
considered title case by istitle() because of how Python treats apostrophes.
**replace():
The replace() method returns a new string where all occurrences of a specified substring are
replaced with another substring.
📘 Syntax:
[Link](old, new, count=-1)
⚠️Important:
• replace() does not change the original string (strings are immutable).
• You must assign the result to a new variable or overwrite the original string if you want to
keep the changes.
text = "hello"
text = [Link]("l", "r")
print(text) # Output: herro
**strip():
The strip() method removes whitespace (spaces, tabs, newlines) from the beginning and end
of a string.
📘 Syntax:
[Link](chars=None)
• chars (optional): A string specifying the set of characters to remove from both ends. If
omitted, it removes whitespace by default.
⚠️Notes:
• Only removes characters from start and end of the string, not inside.
• Does not modify the original string; returns a new one.
Related methods:
• lstrip() — removes from left/start only.
📘 Syntax:
[Link](chars=None)
• chars (optional): A string of characters to remove from the start. If not provided, it
removes whitespace by default.
⚠️Notes:
• Only affects the start of the string.
• Characters inside or at the end remain unchanged.
• Returns a new string; original string is unchanged.
**rstrip():
The rstrip() method removes whitespace or specified characters from the right (end) of a
string.
📘 Syntax:
[Link](chars=None)
• chars (optional): A string of characters to remove from the end. If not provided, it removes
whitespace by default.
⚠️Notes:
• Only removes characters from the end of the string.
• Characters at the start or inside the string stay the same.
• Returns a new string, original string stays unchanged.
**split():
The split() method splits a string into a list of substrings based on a separator (delimiter).
📘 Syntax:
[Link](separator=None, maxsplit=-1)
• separator (optional): The delimiter to split on. Default is any whitespace (spaces, tabs,
newlines).
• maxsplit (optional): Maximum number of splits to do. Default is -1 (no limit).
**partition():
The partition() method splits a string into three parts based on the first occurrence of a
specified separator.
📘 Syntax:
[Link](separator)
**rpartition():
The rpartition() method splits a string into three parts based on the last occurrence of a
specified separator.
📘 Syntax:
[Link](separator)
**join():
The join() method combines (concatenates) elements of an iterable (like a list or tuple) into a
single string, with a specified separator between them.
📘 Syntax:
[Link](iterable)
⚠️Important:
• The iterable must contain only strings; otherwise, it raises a TypeError.
**isspace():
The isspace() method checks if all characters in the string are whitespace characters
(spaces, tabs, newlines, etc.).
📘 Syntax:
[Link]()
• Returns True if the string contains only whitespace characters and is not empty.
⚡ Use case:
• Useful to check if a string is blank or contains only spaces/tabs/newlines before processing.
**isalpha():
The isalpha() method checks if all characters in the string are alphabetic letters (A-Z or a-z)
and the string is not empty.
📘 Syntax:
[Link]()
• Returns True if all characters are letters (no numbers, spaces, or symbols).
⚡ Use case:
• Useful to validate that a string contains only letters, like checking names or words.
**isdigit():
The isdigit() method checks if all characters in the string are digits (0–9) and the string is not
empty.
📘 Syntax:
[Link]()
• Returns False if there's anything else: letters, symbols, spaces, or the string is empty.
🔸 Note:
• isdigit() checks only standard digits (0–9).
• If you want to handle numbers from other languages or numeral systems, you can use
isnumeric().
**isalnum():
The isalnum() method checks if all characters in a string are either letters (A–Z, a–z) or digits
(0–9), and the string is not empty.
📘 Syntax:
[Link]()
text = "Hello!"
print([Link]()) # Output: False
**startswith():
The startswith() method checks if a string starts with a specified prefix (substring).
📘 Syntax:
[Link](prefix, start=0, end=len(string))
⚠️Notes:
• It's case-sensitive.
• Often used to validate file types, command inputs, prefixes, etc.
**endswith():
The endswith() method checks if a string ends with a specified suffix (substring).
📘 Syntax:
[Link](suffix, start=0, end=len(string))
✅ Example 2: Case-sensitive
text = "[Link]"
print([Link](".pdf")) # Output: False
⚠️Notes:
• endswith() is case-sensitive.
**encode():
The encode() method is used to convert a string (text) into bytes, using a specified encoding
format (like UTF-8).
📘 Syntax:
[Link](encoding='utf-8', errors='strict')
🔹
encoding (like 'utf-8').
📘 Syntax:
[Link](encoding='utf-8', errors='strict')
• errors (optional):
🔄 Summary:
Action Method Result Type
String → Bytes .encode() bytes
Bytes → String .decode() str
**Slicing:
String slicing means extracting a part (or "slice") of a string using index positions.
📘 Syntax:
string[start:end:step]
📌
• step – (Optional) Step size or direction
🔹 Basic Slicing:
print(text[0:6]) # Output: Python
print(text[7:18]) # Output: Programming
🔹 Step value:
print(text[::2]) # Every 2nd character → Pto rgamn
print(text[::-1]) # Reversed string → gnimmargorP nohtyP
⚠️Out-of-range indexes:
Python handles them gracefully — no error!
print(text[0:100]) # Output: entire string
**Membership Operators:
Membership operators are used to check whether a character or substring is present in a string.
🔑 Operators:
Operator Meaning
in Returns True if found
not in Returns True if not found
✅ Example:
text = "Python is fun"
🔍 Common Uses:
• Searching in strings
• Validating input
• Conditionals (if, while, etc.)
🔁 With if statement:
user_input = "hello world"
if "world" in user_input:
print("Word found!")
else:
print("Not found!")
**Pattern Matching:
In Python, pattern matching refers to checking whether a string matches a specific format,
structure, or pattern. This is commonly done using:
📘
The re module is used for complex pattern matching.
if [Link](pattern, email):
print("Valid email")
else:
print("Invalid email")
📘 Syntax:
eval(expression)
⚠️Warning:
• eval() can be dangerous if used with untrusted input.
✅ Use Case:
Useful for evaluating numeric input, calculator-like programs, and dynamic expressions — but
always with caution.
**max():
The max() function returns the largest item from an iterable (like a list, tuple) or the largest of
two or more arguments.
📘 Syntax:
1. With iterable:
max(iterable, *[, key, default])
⚠️Notes:
• Raises ValueError if called on an empty iterable without a default.
**min():
The min() function returns the smallest item from an iterable (like a list, tuple) or the smallest of
two or more arguments.
📘 Syntax:
1. With iterable:
min(iterable, *[, key, default])
⚠️Notes:
• Raises ValueError if called on an empty iterable without a default.
**pow():
The pow() function calculates the power of a number, i.e., it raises a base number to the
exponent.
📘 Syntax:
pow(base, exponent, mod=None)
⚠️Notes:
• pow() is faster than using ** operator especially with the mod argument.
**round():
The round() function rounds a floating-point number to a specified number of decimal places.
📘 Syntax:
round(number, ndigits=0)
• ndigits (optional): Number of decimal places to round to. Defaults to 0 (round to nearest
integer).
⚠️Notes:
• If ndigits is omitted or zero, returns an int.
• Rounding behavior: Python rounds ties to the nearest even number (bankers rounding).
**int():
The int() function converts a value to an integer.
📘 Syntax:
int(x=0, base=10)
• x (optional): The value to convert (string, float, etc.). Defaults to 0.
• base (optional): Number base if x is a string (like 2 for binary, 16 for hex). Defaults to 10.
⚠️Notes:
• int() truncates towards zero when converting floats.
**random():
The random() function is part of the random module and returns a random float number
between 0.0 (inclusive) and 1.0 (exclusive).
📘 How to use:
import random
value = [Link]()
print(value) # Output: a random float like 0.37444887175646646
Key points:
• Returns a float x such that 0.0 <= x < 1.0.
value = [Link]() * 10
print(value) # e.g., 7.3456789 (float between 0 and 10)
**ceil():
The ceil() function returns the smallest integer greater than or equal to a given number (i.e.,
it rounds a number up).
📘 Usage:
• ceil() is part of the math module.
result = [Link](4.2)
print(result) # Output: 5
✅ Examples:
import math
print([Link](3.1)) # 4
print([Link](7.9)) # 8
print([Link](-2.3)) # -2 (rounds up towards positive infinity)
🔍 Difference from floor():
• ceil() rounds up
**floor():
The floor() function returns the largest integer less than or equal to a given number (i.e., it
rounds a number down).
📘 Usage:
• floor() is part of the math module.
result = [Link](4.7)
print(result) # Output: 4
✅ Examples:
import math
print([Link](3.9)) # 3
print([Link](7.1)) # 7
print([Link](-2.3)) # -3 (rounds down towards negative infinity)
• ceil() rounds up
** sqrt():
The sqrt() function calculates the square root of a number.
📘 Usage:
• sqrt() is part of the math module.
result = [Link](16)
print(result) # Output: 4.0
✅ Examples:
import math
print([Link](25)) # 5.0
print([Link](2)) # 1.4142135623730951 (approximate)
print([Link](0)) # 0.0
⚠️Note:
• sqrt() only works with non-negative numbers.
1. datetime module
Common classes:
• [Link] — Represents a date (year, month, day)
• [Link] — Represents time (hour, minute, second)
✅ Examples:
from datetime import datetime, date, time
Date arithmetic:
from datetime import timedelta
today = [Link]()
tomorrow = today + timedelta(days=1)
print(tomorrow) # Tomorrow's date
2. time module
• Deals mostly with timestamps and delays.
import time
3. calendar module
• Provides calendar-related functions.
import calendar
print([Link](2025, 5))
# Prints the calendar for May 2025
**Recursion:
Recursion is a programming technique where a function calls itself to solve smaller instances of
the same problem until it reaches a base case.
Key Points:
• Every recursive function needs a base case to stop.
• Each recursive call should move towards that base case.
• Useful for problems like factorial, Fibonacci, tree traversals, etc.
How it works:
• factorial(5) calls factorial(4)
print(fibonacci(6)) # Output: 8
Important Notes:
• Recursive calls can be expensive in terms of time and memory.
• Use recursion when it makes the solution simpler and clearer.
• For large inputs, consider iterative solutions or memoization (caching results).