1.
if statement
The if statement executes a block of code only if a condition is true. If the
condition is false, the block is skipped.
Syntax:
if condition:
# code to execute if condition is True
Example:
age = 18
if age >= 18:
print("You are eligible to vote.")
Explanation:
The condition age >= 18 is True.
So, the print statement runs.
2. if-else statement
The if-else statement lets you execute one block of code if the condition is
true, and another if it is false.
Syntax:
if condition:
# code if condition is True
else:
# code if condition is False
Example:
age = 16
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
Explanation:
Condition is False (16 >= 18 is false)
The else block runs.
3. if-elif-else statement
elif stands for "else if". This statement allows checking multiple conditions.
Only the block for the first true condition will execute.
Syntax:
if condition1:
# code if condition1 is True
elif condition2:
# code if condition2 is True
elif condition3:
# code if condition3 is True
else:
# code if none of the above conditions are True
Example:
marks = 85
if marks >= 90:
print("Grade: A+")
elif marks >= 75:
print("Grade: A")
elif marks >= 60:
print("Grade: B")
else:
print("Grade: C")
Explanation:
The program checks each condition in order.
marks >= 90 is False.
marks >= 75 is True → prints "Grade: A" and skips the rest.
4. Nested if statements
You can place an if or if-else statement inside another if statement. This is
called a nested if.
Syntax:
if condition1:
if condition2:
# code if both condition1 and condition2 are True
Example:
num = 10
if num > 0:
print("Number is positive")
if num % 2 == 0:
print("Number is also even")
Explanation:
First, it checks if num > 0 → True
Then, it checks num % 2 == 0 → True
Both print statements execute.
5. Ternary (Conditional) Operator
Python also supports short-hand if-else using the ternary operator:
value_if_true if condition else value_if_false
Example:
age = 20
result = "Eligible" if age >= 18 else "Not Eligible"
print(result)
Explanation:
Condition age >= 18 is True, so result becomes "Eligible".
Loops in Python
A loop is used to repeat a block of code multiple times. Python mainly
supports two types of loops:
1. for loop – iterates over a sequence.
2. while loop – repeats as long as a condition is true.
Python also supports nested loops and loop control statements (break,
continue, pass).
1. The for loop
The for loop in Python is used to iterate over a sequence like a list, tuple,
string, or range.
Syntax:
for variable in sequence:
# code to execute
variable takes the value of each element in the sequence one by one.
The loop stops automatically at the end of the sequence.
Example 1: Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Example 2: Using range()
range() generates a sequence of numbers.
for i in range(5):
print(i)
Output:
0
1
2
3
4
range(5) generates numbers from 0 to 4.
You can also specify a start, stop, and step: range(start, stop, step)
for i in range(1, 10, 2):
print(i)
Output:
1
3
5
7
9
2. The while loop
The while loop repeats a block of code as long as a condition is True.
Syntax:
while condition:
# code to execute
Example 1: Basic while loop
i=1
while i <= 5:
print(i)
i += 1
Output:
1
2
3
4
5
Explanation:
The loop continues as long as i <= 5.
i += 1 increments i to eventually make the condition False.
Example 2: Infinite loop
while True:
print("This will print forever")
The loop never stops until we break it manually using break.
3. Nested Loops
A nested loop is a loop inside another loop.
Syntax:
for outer_variable in sequence:
for inner_variable in sequence:
# code to execute
Example: Nested for loop
for i in range(1, 4):
for j in range(1, 4):
print(i, j)
Output:
11
12
13
21
22
23
31
32
33
4. Loop Control Statements
Python provides statements to control the behavior of loops:
a) break
Exits the loop immediately.
for i in range(1, 6):
if i == 4:
break
print(i)
Output:
1
2
3
b) continue
Skips the current iteration and moves to the next one.
for i in range(1, 6):
if i == 3:
continue
print(i)
Output:
1
2
4
5
c) pass
Does nothing. Used as a placeholder.
for i in range(1, 6):
if i == 3:
pass
print(i)
Output:
1
2
3
4
5
5. else with loops
Python allows an else block with loops.
The else block executes only if the loop completes normally (no break).
for i in range(1, 6):
print(i)
else:
print("Loop completed successfully")
Output:
1
2
3
4
5
Loop completed successfully
If we add a break:
for i in range(1, 6):
if i == 3:
break
print(i)
else:
print("Loop completed successfully")
Output:
1
2
The else is skipped because the loop was broken.
Python control statements are broadly divided into three categories:
1. Decision-making statements – choose which block to execute.
2. Loop control statements – control loop execution.
3. Jump statements – alter the flow of execution abruptly.
1. Decision-Making Statements
These statements let the program choose actions based on conditions.
Types:
if
if-else
if-elif-else
Nested if
2. Loop Control Statements
Loop control statements alter the execution of loops (for and while).
a) break
Stops the loop immediately, even if the condition is True.
for i in range(1, 6):
if i == 4:
break
print(i)
Output:
1
2
3
b) continue
Skips the current iteration and moves to the next iteration of the loop.
for i in range(1, 6):
if i == 3:
continue
print(i)
Output:
1
2
4
5
c) pass
Does nothing, acts as a placeholder.
for i in range(1, 6):
if i == 3:
pass
print(i)
Output:
1
2
3
4
5
d) else with loops
Executes only if the loop was not terminated by a break.
for i in range(1, 6):
print(i)
else:
print("Loop completed successfully")
3. Jump Statements
Jump statements transfer control unconditionally to another part of the
program.
Types:
1. break – stops a loop (already explained).
2. continue – skips to the next iteration (already explained).
3. pass – does nothing (already explained).
Additional concept: return in functions:
return exits the function immediately and optionally returns a value.
def add(a, b):
return a + b
result = add(5, 3)
print(result)
Output:
8
Numbers in Python
Python supports numeric data types, which are used to store numeric values.
Main Numeric Types
1. int – Integer numbers
2. float – Floating-point numbers (decimals)
3. complex – Complex numbers (real + imaginary)
4. bool – Boolean (True/False) is a subclass of int
1. Integer (int)
Represents whole numbers (no fractional part).
Can be positive, negative, or zero.
Python integers can be arbitrarily large, unlike some other languages.
Examples:
a = 10 # positive integer
b = -25 # negative integer
c=0 # zero
Operations on Integers:
x = 10
y=3
print(x + y) # Addition → 13
print(x - y) # Subtraction → 7
print(x * y) # Multiplication → 30
print(x / y) # Division → 3.3333333333333335 (always float)
print(x // y) # Floor division → 3
print(x % y) # Modulus → 1 (remainder)
print(x ** y) # Exponent → 1000 (10^3)
2. Floating-Point (float)
Represents real numbers with a decimal point.
Can be positive, negative, or zero.
Examples:
a = 10.5
b = -3.14
c = 0.0
Operations on Float:
Works like integers, but results are usually floats.
x = 5.5
y = 2.0
print(x + y) # 7.5
print(x - y) # 3.5
print(x * y) # 11.0
print(x / y) # 2.75
3. Complex Numbers (complex)
Represents numbers in the form a + bj, where:
o a is the real part
o b is the imaginary part
j is used to denote the imaginary part (like i in math).
Examples:
a = 2 + 3j
b = 1 - 5j
Operations on Complex Numbers:
a = 2 + 3j
b = 1 - 5j
print(a + b) # 3 - 2j
print(a - b) # 1 + 8j
print(a * b) # 17 - 7j
print(a / b) # -0.5882352941176471 + 0.6470588235294118j
Accessing real and imaginary parts:
z = 4 + 5j
print(z.real) # 4.0
print(z.imag) # 5.0
4. Boolean (bool)
Represents True or False values.
Internally, True = 1 and False = 0.
Used in conditions and logical operations.
Examples:
a = True
b = False
print(a + 5) # 6 (True = 1)
print(b + 5) # 5 (False = 0)
5. Type Conversion (Casting)
Python allows conversion between numeric types.
x = 10 # int
y = float(x) # convert int to float → 10.0
z = complex(x) # convert int to complex → (10+0j)
f = 5.7
i = int(f) # 5 (fractional part removed)
6. Special Numeric Functions
Python provides built-in numeric functions:
x = -10
y = 3.5
print(abs(x)) # 10 → absolute value
print(round(y)) # 4 → rounded value
print(pow(2,3)) # 8 → exponent
print(divmod(10, 3)) # (3, 1) → quotient and remainder
ists in Python
A list is an ordered collection of items. It can contain elements of different
data types like integers, strings, floats, or even other lists.
Lists are mutable (you can change elements).
Lists are ordered (elements maintain their order).
Lists allow duplicate elements.
1. Creating a List
Syntax:
list_name = [element1, element2, element3, ...]
Examples:
# List of integers
numbers = [1, 2, 3, 4, 5]
# List of strings
fruits = ["apple", "banana", "cherry"]
# Mixed list
mixed = [1, "apple", 3.14, True]
# Empty list
empty_list = []
2. Accessing List Elements
Use indexing to access elements. Python indexes start at 0.
Negative indexing starts from -1 (last element).
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[1]) # banana
print(fruits[-1]) # cherry
3. Slicing Lists
Get a sublist using slicing: list[start:end]
start → starting index (inclusive)
end → ending index (exclusive)
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]
4. Modifying Lists
Lists are mutable, so you can change, add, or remove elements.
a) Changing elements
fruits = ["apple", "banana", "cherry"]
fruits[1] = "orange"
print(fruits) # ["apple", "orange", "cherry"]
b) Adding elements
append() → adds an element at the end
insert() → inserts an element at a specific position
extend() → adds multiple elements
fruits.append("mango")
fruits.insert(1, "grape")
fruits.extend(["kiwi", "melon"])
print(fruits)
Output:
['apple', 'grape', 'orange', 'cherry', 'mango', 'kiwi', 'melon']
c) Removing elements
remove() → removes first occurrence of value
pop() → removes element by index
del → removes element or entire list
clear() → removes all elements
fruits.remove("grape")
fruits.pop(2)
del fruits[0]
fruits.clear()
5. List Operations
Concatenation: +
Repetition: *
Membership: in, not in
a = [1, 2, 3]
b = [4, 5]
print(a + b) # [1, 2, 3, 4, 5]
print(a * 2) # [1, 2, 3, 1, 2, 3]
print(2 in a) # True
print(6 not in a) # True
6. List Functions
Function Description Example
len(list) Returns length of list len([1,2,3]) → 3
max(list) Returns maximum element max([1,5,2]) → 5
min(list) Returns minimum element min([1,5,2]) → 1
sum(list) Returns sum of elements (numbers only) sum([1,2,3]) → 6
sorted(list) Returns sorted list sorted([3,1,2]) → [1,2,3]
list(seq) Converts a sequence (tuple, string) to list list("abc") → ['a','b','c']
7. List Methods
Method Description
append(x) Adds element x at the end
Method Description
insert(i, x) Inserts element x at index i
extend(iterable) Adds all elements of an iterable at the end
remove(x) Removes first occurrence of x
pop([i]) Removes and returns element at index i (default last)
clear() Removes all elements
index(x) Returns index of first occurrence of x
count(x) Returns number of times x appears
sort() Sorts the list in ascending order
reverse() Reverses the list
copy() Returns a shallow copy of the list
8. Iterating Through Lists
fruits = ["apple", "banana", "cherry"]
# Using for loop
for fruit in fruits:
print(fruit)
# Using while loop
i=0
while i < len(fruits):
print(fruits[i])
i += 1
9. Nested Lists
A list can contain other lists (like a matrix).
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[1][2]) # 6
Key Points About Lists
1. Lists are ordered, mutable, and allow duplicates.
2. Elements can be of different types.
3. Supports indexing, slicing, and nested lists.
4. Python provides built-in functions and methods for lists.
5. Lists are versatile and widely used for storing sequences of data.
Tuples in Python
A tuple is an ordered collection of elements, similar to a list, but with one key
difference:
Tuples are immutable, meaning you cannot change, add, or remove
elements once the tuple is created.
Other characteristics:
Tuples are ordered → elements maintain their position.
Tuples can contain duplicate elements.
Tuples can contain different data types: int, float, string, list, etc.
1. Creating Tuples
Syntax:
tuple_name = (element1, element2, element3, ...)
Examples:
# Tuple of integers
numbers = (1, 2, 3, 4, 5)
# Tuple of strings
fruits = ("apple", "banana", "cherry")
# Mixed tuple
mixed = (1, "apple", 3.14, True)
# Empty tuple
empty_tuple = ()
# Single element tuple → comma is required
single = (5,)
Note: (5) is not a tuple, it’s just an integer. (5,) is a tuple with one element.
2. Accessing Tuple Elements
Tuples support indexing (start at 0) and negative indexing (-1 for last
element).
fruits = ("apple", "banana", "cherry")
print(fruits[0]) # apple
print(fruits[1]) # banana
print(fruits[-1]) # cherry
3. Slicing Tuples
Similar to lists, you can get a subset of elements.
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)
4. Modifying Tuples
Tuples are immutable, so you cannot change, add, or remove elements
directly.
numbers = (1, 2, 3)
# numbers[1] = 5 → This will give an error
Workarounds:
Convert tuple → list, modify, then convert back to tuple:
numbers = (1, 2, 3)
numbers_list = list(numbers)
numbers_list[1] = 5
numbers = tuple(numbers_list)
print(numbers) # (1, 5, 3)
5. Tuple Operations
Concatenation (+) → combines tuples
Repetition (*) → repeats tuples
Membership (in, not in) → checks for element
a = (1, 2, 3)
b = (4, 5)
print(a + b) # (1, 2, 3, 4, 5)
print(a * 2) # (1, 2, 3, 1, 2, 3)
print(2 in a) # True
print(6 not in a) # True
6. Tuple Functions
Function Description Example
len(tuple) Returns number of elements len((1,2,3)) → 3
max(tuple) Returns maximum element max((1,5,3)) → 5
min(tuple) Returns minimum element min((1,5,3)) → 1
sum(tuple) Returns sum (numbers only) sum((1,2,3)) → 6
tuple(seq) Converts a sequence (list, string) → tuple tuple([1,2,3]) → (1,2,3)
7. Tuple Methods
Tuples are immutable, so they have fewer methods than lists:
Method Description
count(x) Returns the number of times x appears
index(x) Returns the index of first occurrence of x
t = (1, 2, 3, 2, 2, 5)
print(t.count(2)) # 3
print(t.index(3)) # 2
8. Iterating Through Tuples
fruits = ("apple", "banana", "cherry")
# Using for loop
for fruit in fruits:
print(fruit)
# Using while loop
i=0
while i < len(fruits):
print(fruits[i])
i += 1
9. Nested Tuples
A tuple can contain other tuples:
nested = ((1, 2), (3, 4), (5, 6))
print(nested[1]) # (3, 4)
print(nested[1][0]) # 3
✅ Key Points About Tuples
1. Tuples are ordered, immutable, and allow duplicates.
2. Tuples can contain different data types.
3. Supports indexing, slicing, and nested tuples.
4. Tuples have fewer built-in methods than lists (count and index).
5. Use tuples when you want data that should not change, e.g., storing
coordinates.
6. Tuples are slightly faster than lists due to immutability.
Sets in Python
A set is an unordered collection of unique elements.
Unordered → elements do not have a fixed position.
Unique → duplicates are automatically removed.
Mutable → you can add or remove elements, but set itself cannot
contain mutable elements like lists or dictionaries.
Sets are often used for membership testing, removing duplicates, and
mathematical operations like union, intersection, etc.
1. Creating Sets
Syntax:
set_name = {element1, element2, element3}
Examples:
# Set of integers
numbers = {1, 2, 3, 4, 5}
# Set of strings
fruits = {"apple", "banana", "cherry"}
# Mixed set
mixed = {1, "apple", 3.14, True}
# Empty set
empty_set = set() # {} creates an empty dictionary
Note: {} creates an empty dictionary, so use set() for an empty set.
2. Properties of Sets
1. Unordered:
s = {1, 2, 3}
print(s) # Output could be {1, 2, 3} or {2, 1, 3}, order not guaranteed
2. Unique elements:
s = {1, 2, 2, 3, 3, 3}
print(s) # {1, 2, 3}
3. Mutable: You can add/remove elements, but elements themselves must
be immutable.
3. Accessing Set Elements
Sets are unordered, so you cannot access elements by index.
You can iterate through a set using a for loop:
fruits = {"apple", "banana", "cherry"}
for fruit in fruits:
print(fruit)
4. Adding and Removing Elements
Adding elements:
s = {1, 2, 3}
s.add(4) # Add single element
s.update([5, 6]) # Add multiple elements
print(s) # {1, 2, 3, 4, 5, 6}
Removing elements:
remove(x) → removes x, raises KeyError if not found
discard(x) → removes x, does not raise error if not found
pop() → removes and returns an arbitrary element
clear() → removes all elements
s = {1, 2, 3, 4}
s.remove(2) # {1, 3, 4}
s.discard(5) # no error
s.pop() # removes an arbitrary element
s.clear() # {}
5. Set Operations
Sets are perfect for mathematical operations:
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
Operation Syntax Example Result
Union `A B` `A
Intersection A&B A&B {3,4}
Difference A-B A-B {1,2}
Symmetric Difference A ^ B A^B {1,2,5,6}
Subset A <= B A <= B False
Superset A >= B A >= B False
Disjoint A.isdisjoint(B) True/False False
6. Set Methods
Method Description
add(x) Adds element x
update(iterable) Adds multiple elements
remove(x) Removes x, raises error if not found
discard(x) Removes x, no error if not found
pop() Removes and returns an arbitrary element
clear() Removes all elements
union(other) Returns union of sets
intersection(other) Returns intersection
difference(other) Returns difference
symmetric_difference(other) Returns symmetric difference
issubset(other) Checks if set is subset
Method Description
issuperset(other) Checks if set is superset
isdisjoint(other) Checks if sets have no elements in common
7. Iterating Through a Set
fruits = {"apple", "banana", "cherry"}
for fruit in fruits:
print(fruit)
Note: Order of elements is not guaranteed.
8. Frozen Sets
A frozen set is immutable.
Once created, you cannot add or remove elements.
fs = frozenset([1, 2, 3, 4])
print(fs) # frozenset({1, 2, 3, 4})
# fs.add(5) → Error
✅ Key Points About Sets
1. Sets are unordered, mutable, and contain unique elements.
2. Use sets for membership testing, duplicates removal, and
mathematical operations.
3. Sets cannot contain mutable elements (like lists or dictionaries).
4. Frozensets are immutable sets.
5. Set operations like union, intersection, difference are very fast in Python.
Dictionaries in Python
A dictionary is an unordered collection of key-value pairs.
Each key is unique.
Each key maps to a value.
Dictionaries are mutable, so you can change, add, or remove elements.
They are also called associative arrays or hash maps in other languages.
1. Creating Dictionaries
Syntax:
dict_name = {key1: value1, key2: value2, key3: value3}
Examples:
# Dictionary of student marks
marks = {"Alice": 85, "Bob": 92, "Charlie": 78}
# Mixed types
person = {"name": "John", "age": 25, "is_student": True}
# Empty dictionary
empty_dict = {}
# Nested dictionary
students = {
"Alice": {"math": 85, "science": 90},
"Bob": {"math": 92, "science": 88}
}
2. Accessing Dictionary Elements
Use keys to access values.
marks = {"Alice": 85, "Bob": 92}
print(marks["Alice"]) # 85
print(marks.get("Bob")) # 92
.get() is safer because it returns None if key does not exist instead of
raising an error.
print(marks.get("Charlie")) # None
3. Modifying Dictionaries
a) Changing values
marks = {"Alice": 85, "Bob": 92}
marks["Alice"] = 90
print(marks) # {"Alice": 90, "Bob": 92}
b) Adding key-value pairs
marks["Charlie"] = 78
print(marks) # {"Alice": 90, "Bob": 92, "Charlie": 78}
c) Removing elements
pop(key) → removes key and returns value
popitem() → removes last inserted item
del dict[key] → deletes specific key
clear() → removes all items
marks.pop("Bob") # removes Bob
marks.popitem() # removes last item
del marks["Alice"] # removes Alice
marks.clear() # {}
4. Dictionary Operations
a = {"x": 1, "y": 2}
b = {"y": 3, "z": 4}
# Keys
print(a.keys()) # dict_keys(['x', 'y'])
# Values
print(a.values()) # dict_values([1, 2])
# Items
print(a.items()) # dict_items([('x',1),('y',2)])
# Membership testing
print("x" in a) # True
print("z" in a) # False
5. Iterating Through a Dictionary
marks = {"Alice": 90, "Bob": 92, "Charlie": 78}
# Iterating through keys
for key in marks:
print(key)
# Iterating through values
for value in marks.values():
print(value)
# Iterating through key-value pairs
for key, value in marks.items():
print(key, value)
6. Nested Dictionaries
Dictionaries can contain other dictionaries.
students = {
"Alice": {"math": 85, "science": 90},
"Bob": {"math": 92, "science": 88}
}
print(students["Alice"]["math"]) # 85
print(students["Bob"]["science"]) # 88
7. Dictionary Methods
Method Description
clear() Removes all elements
copy() Returns a shallow copy
get(key) Returns value for key; returns None if key not found
items() Returns a view of key-value pairs
keys() Returns a view of keys
values() Returns a view of values
pop(key) Removes key and returns value
popitem() Removes and returns last inserted key-value pair
update(dict) Adds/updates elements from another dictionary
Returns value if key exists; otherwise inserts key with
setdefault(key, value)
value
8. Dictionary Comprehension
Similar to list comprehension, you can create dictionaries dynamically.
squares = {x: x**2 for x in range(1, 6)}
print(squares) # {1:1, 2:4, 3:9, 4:16, 5:25}
✅ Key Points About Dictionaries
1. Dictionaries are unordered, mutable, and indexed by keys.
2. Keys must be immutable types (strings, numbers, tuples).
3. Values can be any data type.
4. Useful for fast lookups, mappings, and storing structured data.
5. Supports nested dictionaries and comprehensions.
Strings in Python
A string is a sequence of characters enclosed in either:
Single quotes: 'Hello'
Double quotes: "Hello"
Triple quotes (for multi-line strings): '''Hello''' or """Hello"""
Strings are immutable, meaning once created, they cannot be changed.
1. Creating Strings
# Single and double quotes
s1 = 'Hello'
s2 = "World"
# Triple quotes for multi-line string
s3 = '''This is
a multi-line
string'''
# Empty string
s4 = ""
2. Accessing Strings
a) Indexing
Strings are sequences, so you can access characters by index.
Python uses 0-based indexing.
s = "Python"
print(s[0]) # 'P'
print(s[3]) # 'h'
print(s[-1]) # 'n' (last character)
print(s[-2]) # 'o'
b) Slicing
Extract a substring using string[start:end] (end excluded).
s = "Python"
print(s[0:4]) # 'Pyth'
print(s[:3]) # 'Pyt'
print(s[2:]) # 'thon'
print(s[-4:-1])# 'tho'
print(s[:]) # 'Python' (whole string)
3. String Operations
a) Concatenation (+)
s1 = "Hello"
s2 = "World"
s3 = s1 + " " + s2
print(s3) # 'Hello World'
b) Repetition (*)
s = "Hi! "
print(s * 3) # 'Hi! Hi! Hi! '
c) Membership (in, not in)
s = "Python"
print('P' in s) # True
print('z' not in s) # True
d) Iteration
s = "Python"
for char in s:
print(char)
4. String Methods
Python provides many built-in string methods. Some important ones:
Method Description
len(s) Returns length of string
s.upper() Converts to uppercase
s.lower() Converts to lowercase
s.capitalize() Capitalizes first character
s.title() Capitalizes first letter of each word
s.strip() Removes leading/trailing whitespaces
s.lstrip() Removes leading spaces
s.rstrip() Removes trailing spaces
s.replace(old, new) Replaces substring
s.split(sep) Splits string into list by separator
s.join(iterable) Joins iterable with string as separator
s.find(sub) Returns index of first occurrence, -1 if not found
Method Description
s.index(sub) Returns index of first occurrence, error if not found
s.count(sub) Counts occurrences of substring
s.startswith(sub) Checks if string starts with substring
s.endswith(sub) Checks if string ends with substring
s.isalpha() Checks if all characters are letters
s.isdigit() Checks if all characters are digits
s.isalnum() Checks if all characters are alphanumeric
s.isspace() Checks if all characters are whitespace
Examples:
s = " hello world "
print(s.upper()) # ' HELLO WORLD '
print(s.lower()) # ' hello world '
print(s.strip()) # 'hello world'
print(s.replace("world", "Python")) # ' hello Python '
print(s.split()) # ['hello', 'world']
5. String Formatting
a) Using f-strings (Python 3.6+)
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old")
b) Using format()
print("My name is {} and I am {} years old".format(name, age))
print("My name is {n} and I am {a} years old".format(n=name, a=age))
c) Using % formatting
print("My name is %s and I am %d years old" % (name, age))
6. String Escape Sequences
Special characters can be included using backslash \:
Escape Sequence Meaning
\' Single quote
\" Double quote
\\ Backslash
\n Newline
\t Tab
\r Carriage return
\b Backspace
s = "Hello\nWorld"
print(s)
# Output:
# Hello
# World
7. String Immutability
Strings cannot be changed after creation.
s = "Hello"
# s[0] = 'h' → Error
# Workaround: create new string
s = 'h' + s[1:]
print(s) # 'hello'
✅ Key Points About Strings
1. Strings are immutable sequences of characters.
2. Supports indexing, slicing, concatenation, repetition, and iteration.
3. Python provides rich built-in methods for manipulation and checking.
4. Can be formatted in multiple ways (f-strings, .format(), %).
5. Useful for text processing, data parsing, and user interaction.