Python conditional and iterative statements
if statement , if…elif statement , if….. elif…..else statment , nested if
1. if Statement.
The
ifstatement is the most basic decision-making statement.It checks whether a given condition is
True. If the condition evaluates toTrue, the indented block of code under theifstatement executes; otherwise, the block is skipped.Syntax:
if condition: # Code to execute if condition is True
The
conditionis a Boolean expression (i.e., it evaluates toTrueorFalse).If
conditionisTrue, the code inside theifblock executes.If
conditionisFalse, the code is skipped.
age = 20 if age >= 18: print("You are eligible to vote.") # This line executes if age is 18 or more
2. if...elif Statement.
The
if...elifstatement allows checking multiple conditions sequentially.If the first condition is
False, Python checks the nextelifcondition.- The first condition that evaluates to
Trueis executed, and the rest are ignored. Syntax
if condition1: # Code to execute if condition1 is True elif condition2: # Code to execute if condition1 is False and condition2 is True elif condition3: # Code to execute if both condition1 and condition2 are False, but condition3 is True
Only one condition is executed.
If
condition1isTrue, its block runs, and the rest are ignored.If
condition1isFalsebutcondition2isTrue, theelifblock runs.
Example:
marks = 85 if marks >= 90: print("Grade: A") elif marks >= 80: print("Grade: B") elif marks >= 70: print("Grade: C")
3. if...elif...else Statement.
This is similar to if...elif, but it also includes an else block that executes when none of the conditions are True.
Syntax.
if condition1: # Code to execute if condition1 is True elif condition2: # Code to execute if condition1 is False and condition2 is True else: # Code to execute if all conditions are False
The
elseblock always executes if no conditions areTrue.It acts as a “default” case.
temperature = 10 if temperature > 30: print("It's a hot day.") elif temperature > 15: print("The weather is pleasant.") else: print("It's cold outside.")
4. Nested if Statement.
A nested
ifstatement means writing anifstatement inside anotherifstatement.This allows checking multiple conditions in a hierarchical way.
Syntax:
if condition1: if condition2: # Code executes if both condition1 and condition2 are True
The inner
ifblock executes only if the outerifcondition isTrue.
Example:
num = 10 if num > 0: # Outer if statement print("Number is positive") if num % 2 == 0: # Inner if statement print("It is even")
Iterative statements.
While Loop and Control Statements.
1. while Loop
A while loop is used when we do not know the exact number of iterations beforehand. It keeps running as long as the condition is True.
Syntax:
while condition: # Code to execute while condition is True
The loop first checks the condition.
If the condition is
True, the block inside the loop executes.After execution, it checks the condition again and repeats if
True.If
False, the loop terminates.EXAMPLE
count = 1 while count <= 5: print("Count:", count) count += 1 # Increment count
2. Nested while Loop.
A nested loop means a while loop inside another while loop. The inner loop executes fully for each iteration of the outer loop.
Syntax:
while condition1: while condition2: # Code executes when both conditions are True
EXAMPLE
i = 1 while i <= 3: j = 1 while j <= 2: print(f"i={i}, j={j}") j += 1 i += 1
3. break Statement
The break statement stops the loop immediately, even if the condition is still True.
Example:
x = 1 while x <= 5: if x == 3: break # Loop stops when x = 3 print("x:", x) x += 1
4. continue Statement
The continue statement skips the current iteration and moves to the next iteration.
Example:
x = 0 while x < 5: x += 1 if x == 3: continue # Skip when x = 3 print("x:", x)
for Loop and Control Statements.
1. for Loop
A for loop is used when we know the number of iterations. It is commonly used for iterating over sequences like lists, strings, tuples, dictionaries, and ranges.
Syntax:
for variable in sequence: # Code executes for each item in sequence
EXAMPLE
for num in [1, 2, 3, 4, 5]: print("Number:", num)
2. range() Function.
The range() function generates a sequence of numbers.
Syntax:
range(start, stop, step)
start: (Optional) Starting value (default = 0).stop: End value (not included in range).step: (Optional) Difference between numbers (default = 1).
for i in range(1, 6): print(i)
3. break Statement in for Loop
Example:
for num in range(1, 6): if num == 3: break # Stop when num = 3 print(num)
4. continue Statement in for Loop
Example:
for num in range(1, 6): if num == 3: continue # Skip 3 print(num)
5. pass Statement
The pass statement is a placeholder that does nothing.
Example:
for num in range(1, 6): if num == 3: pass # Placeholder for future code print(num)
6. else with for Loop
The else block executes if the loop completes normally (i.e., without break).
Example:
for i in range(1, 4): print(i) else: print("Loop completed successfully!")
7. Nested for Loop
Example:
for i in range(1, 4): for j in range(1, 3): print(f"i={i}, j={j}")
Python Lists:
A list in Python is a built-in data structure used to store multiple items in a single variable.
It is one of the most commonly used data structures because of its flexibility and easy manipulation.
A list in Python is a mutable, ordered collection of elements that can store heterogeneous data types.
It is one of the most versatile data structures, widely used in programming for data storage and manipulation.
Key Characteristics of a List:
Ordered: Items maintain a specific order.
Mutable: Can be modified after creation.
Allows Duplicate Values: Elements can be repeated.
Can Store Different Data Types: Strings, integers, floats, and even other lists.
Why Use Lists?
✅ Store Multiple Items – Instead of creating separate variables, a list can store multiple values.
✅ Dynamic Size – Lists can grow and shrink dynamically.
✅ Mutable – Lists allow modification (adding, removing, updating items).
✅ Efficient Iteration – Easily loop over elements.
✅ Supports Various Data Types – Can hold numbers, strings, booleans, and even other lists.
1. Creating a List
Lists in Python are created using square brackets [ ], with elements separated by commas.
Syntax:
list_name = [item1, item2, item3, ...]
Examples.
# List of integers numbers = [10, 20, 30, 40, 50] # List of strings fruits = ["apple", "banana", "cherry"] # Mixed data types mixed_list = [1, "Hello", 3.14, True] # Empty list empty_list = [] # Nested list (list inside a list) nested_list = [[1, 2, 3], ["a", "b", "c"]] print(numbers) print(fruits) print(mixed_list) print(empty_list) print(nested_list)
2. Indexing in Lists
Each element in a list is assigned a numeric index that helps in accessing elements.
Indexing helps in retrieving specific elements from a list.
🔹 Positive Indexing (Starts from 0):
| Element | "apple" | "banana" | "cherry" |
|---|---|---|---|
| Index | 0 | 1 | 2 |
🔹 Negative Indexing (Starts from -1):
| Element | "apple" | "banana" | "cherry" |
|---|---|---|---|
| Index | -3 | -2 | -1 |
fruits = ["apple", "banana", "cherry"] print(fruits[0]) # First element print(fruits[-1]) # Last element using negative index print(fruits[1]) # Second element
📍 3. Accessing List Members
We can retrieve elements using indexing or iteration.
- We can access individual or multiple elements from a list.
🔹 Example:
numbers = [10, 20, 30, 40, 50] print(numbers[2]) # Accessing the third element (30) print(numbers[-1]) # Accessing the last element (50)
📍 4. Range in Lists (Slicing)
List slicing extracts a portion of the list.
SYNTAX.
list[start:end:step]
start: Beginning index (default is0).end: Ending index (exclusive).step: Skips elements (default is1).
EXAMPLE.
numbers = [10, 20, 30, 40, 50, 60, 70] print(numbers[1:4]) # Elements from index 1 to 3 print(numbers[:3]) # First 3 elements print(numbers[3:]) # Elements from index 3 to end print(numbers[::2]) # Every second element print(numbers[::-1]) # Reverse the list
📍 5. List Methods.
Python provides built-in methods to modify or manipulate lists.
1️⃣ append() – Add an Item to the End
fruits = ["apple", "banana"] fruits.append("cherry") print(fruits)
2️⃣ clear() – Remove All Items
fruits = ["apple", "banana"] fruits.clear() print(fruits)
3️⃣ copy() – Copy a List
original = [1, 2, 3] copy_list = original.copy() print(copy_list)
4️⃣ count() – Count Occurrences.
numbers = [1, 2, 2, 3, 4, 2] print(numbers.count(2))
5️⃣ index() – Find the Index of an Item
fruits = ["apple", "banana", "cherry"] print(fruits.index("banana"))
6️⃣ insert() – Insert at Specific Position
fruits = ["apple", "cherry"] fruits.insert(1, "banana") print(fruits)
7️⃣ pop() – Remove and Return an Item
fruits = ["apple", "banana", "cherry"] removed_item = fruits.pop(1) print(removed_item) print(fruits)
8️⃣ remove() – Remove by Value
numbers = [1, 2, 3, 2, 4] numbers.remove(2) print(numbers)
9️⃣ reverse() – Reverse a List
numbers = [1, 2, 3] numbers.reverse() print(numbers)
🔟 sort() – Sort a List
numbers = [5, 2, 8, 1] numbers.sort() print(numbers) numbers.sort(reverse=True) print(numbers)