UNIT-4: Python conditional and iterative statements

UNIT-4: Python conditional and iterative statements

4.1 Conditional Statements in Python

  • Conditional statements in Python allow decision-making in programs.
  • The if, if-elif, if-elif-else, and nested if statements help execute specific blocks of code based on conditions.

4.1.1 If Statement

  • The if statement checks a condition. If the condition is True, the block of code inside if executes.

Syntax:

if condition: # Code block to execute if condition is True

Example:

num = 10 if num > 5: print("The number is greater than 5")
✅ Since num is 10 (greater than 5), the condition is True, so the print statement executes.

4.1.2 If…Elif Statement

  • The if-elif statement is used when multiple conditions need to be checked one after another.

Syntax:

if condition1: # Code block if condition1 is True elif condition2: # Code block if condition2 is True

Example.

marks = 75 if marks >= 90: print("Grade: A") elif marks >= 75: print("Grade: B")
✅ Since marks = 75, the first condition (marks >= 90) is False, but the second (marks >= 75) is True, so "Grade: B" prints.

4.1.3 If…Elif…Else Statement

  • The if-elif-else statement provides a default block (else) that executes if none of the conditions are True.

Syntax:

if condition1: # Executes if condition1 is True elif condition2: # Executes if condition2 is True else: # Executes if none of the conditions are True

Example:

temperature = 15 if temperature > 30: print("It's hot outside.") elif temperature > 20: print("The weather is warm.") else: print("It's cold.")

✅ Since temperature = 15, both conditions are False, so the else block executes.

4.1.4 Nested If Statement

  • A nested if is an if statement inside another if statement.

Syntax:

if condition1: if condition2: # Executes if both condition1 and condition2 are True

Example:

age = 20 has_id = True if age >= 18: if has_id: print("You are allowed to enter.") else: print("You need an ID.") else: print("You are underaged.")
✅ Since age = 20 (≥ 18) and has_id = True, both conditions are True, so "You are allowed to enter." prints.

4.2 Iterative Statements in Python.

  • Iterative statements (loops) repeat a block of code multiple times until a certain condition is met. Python provides two types of loops:
  1. while loop
  2. for loop
  • Additionally, Python has control statements like break, continue, and pass to manage loops.

4.2.1 While Loop

  • A while loop executes repeatedly as long as a given condition is True.

Syntax:

while condition: # Code to execute

Example: While Loop

count = 1 while count <= 5: print("Count:", count) count += 1
✅ The loop runs until count becomes 6, which makes the condition False.

Nested While Loop

  • A nested while loop is a loop inside another while loop.

Example:

i = 1 while i <= 3: j = 1 while j <= 2: print(f"i={i}, j={j}") j += 1 i += 1
✅ The inner loop (j) runs twice for each iteration of the outer loop (i).

Break and Continue Statements in While Loop

  • break → Stops the loop immediately.
  • continue → Skips the rest of the loop and moves to the next iteration.
num = 1 while num <= 5: if num == 3: break # Exit loop when num is 3 print("Number:", num) num += 1
✅ The loop stops when num reaches 3 due to break.
Example: Continue Statement:
num = 0 while num < 5: num += 1 if num == 3: continue # Skip iteration when num is 3 print("Number:", num)
✅ When num = 3, continue skips the print statement.

4.2.2 For Loop

  • A for loop is used to iterate over sequences (like lists, tuples, strings, and ranges).

Syntax:

for variable in sequence: # Code to execute

Example: For Loop

for num in range(1, 6): print("Number:", num)
✅ The loop iterates over the sequence 1, 2, 3, 4, 5.

Using range() in a For Loop

  • The range() function generates a sequence of numbers.
Syntax Description Example
range(n) Generates numbers from 0 to n-1 range(5) → 0,1,2,3,4
range(start, end) Generates numbers from start to end-1 range(2,6) → 2,3,4,5
range(start, end, step) Generates numbers with a step range(1,10,2) → 1,3,5,7,9

Example:

for num in range(2, 10, 2): print(num)
✅ The loop prints even numbers from 2 to 8.

Break and Continue in For Loop

  • Similar to while, break and continue can be used in for loops.
Example: Break Statement
for num in range(1, 6): if num == 4: break print(num)
✅ The loop stops when num reaches 4.
Example: Continue Statement
for num in range(1, 6): if num == 3: continue # Skip 3 print(num)
✅ The number 3 is skipped.

Using pass in a Loop

  • The pass statement is a placeholder for future code.
Example:
for num in range(5): pass # Placeholder
✅ The loop runs but does nothing.

Else with For Loop

  • The else block runs after the loop completes normally (without break).

Example:

for num in range(1, 4): print(num) else: print("Loop completed successfully!")
✅ The else block executes only if the loop is not broken.
Example: Break with Else
for num in range(1, 4): print(num) if num == 2: break else: print("Loop completed!")
✅ The else block does not execute because the loop breaks early.

Nested For Loop

  • A for loop inside another for loop is called a nested loop.

Example:

for i in range(1, 3): for j in range(1, 4): print(f"i={i}, j={j}")
✅ The inner loop (j) runs three times for each iteration of the outer loop (i).

4.3 List in Python.

  • A list in Python is a mutable, ordered collection that can store multiple items of different types (integers, floats, strings, etc.).
  • Lists allow easy modifications, such as adding, removing, and sorting elements.

4.3.1 Creating a List

A list is defined using square brackets [], with elements separated by commas.

Example:

# Creating a list with different data types fruits = ["Apple", "Banana", "Cherry"] numbers = [10, 20, 30, 40] mixed = [1, "Hello", 3.5, True] print(fruits) print(numbers) print(mixed)

4.3.2 Indexing in a List

Each element in a list has an index, starting from 0 for the first item.
List Item "A" "B" "C" "D"
Index 0 1 2 3
Negative Index -4 -3 -2 -1
letters = ["A", "B", "C", "D"] # Accessing elements using positive index print(letters[0]) # Output: A print(letters[2]) # Output: C # Accessing elements using negative index print(letters[-1]) # Output: D print(letters[-3]) # Output: B

4.3.3 Accessing List Members

Lists can be accessed using indexing, slicing, and loops.

Using Indexing

colors = ["Red", "Green", "Blue"] print(colors[1]) # Output: Green

Using Slicing

  • Slicing extracts a portion of a list using [start:end:step].
numbers = [10, 20, 30, 40, 50, 60] print(numbers[1:4]) # Output: [20, 30, 40] print(numbers[:3]) # Output: [10, 20, 30] (Start from index 0) print(numbers[2:]) # Output: [30, 40, 50, 60] (Till last index) print(numbers[::2]) # Output: [10, 30, 50] (Skip every 2nd element)

Using a Loop.

animals = ["Cat", "Dog", "Rabbit"] for animal in animals: print(animal)

4.3.4 Range in List

  • We can use the range() function to generate a sequence of numbers for indexing and slicing.
Example:
numbers = list(range(1, 11)) # Generates numbers from 1 to 10 print(numbers)

4.3.5 List Methods

  • Python provides built-in methods to manipulate lists.

1. append() – Adds an element to the end of the list.

fruits = ["Apple", "Banana"] fruits.append("Cherry") print(fruits) # Output: ['Apple', 'Banana', 'Cherry']

2. clear() – Removes all elements from the list.

numbers = [1, 2, 3, 4] numbers.clear() print(numbers) # Output: []

3. copy() – Creates a copy of the list.

original = [10, 20, 30] copy_list = original.copy() print(copy_list) # Output: [10, 20, 30]

4. count() – Counts the occurrences of an element

nums = [1, 2, 3, 1, 2, 1] print(nums.count(1)) # Output: 3

5. index() – Finds the index of the first occurrence of an element.

colors = ["Red", "Green", "Blue", "Green"] print(colors.index("Green")) # Output: 1

6. insert() – Inserts an element at a specific index

languages = ["Python", "Java"] languages.insert(1, "C++") print(languages) # Output: ['Python', 'C++', 'Java']

7. pop() – Removes and returns the last element (or a specified index)

numbers = [10, 20, 30, 40] print(numbers.pop()) # Output: 40 (removes last element) print(numbers.pop(1)) # Output: 20 (removes element at index 1) print(numbers) # Output: [10, 30]

8. remove() – Removes the first occurrence of a specified element

fruits = ["Apple", "Banana", "Cherry"] fruits.remove("Banana") print(fruits) # Output: ['Apple', 'Cherry']

9. reverse() – Reverses the order of elements

nums = [1, 2, 3, 4] nums.reverse() print(nums) # Output: [4, 3, 2, 1]

10. sort() – Sorts the list in ascending (default) or descending order

numbers = [40, 10, 30, 20] numbers.sort() # Sort in ascending order print(numbers) # Output: [10, 20, 30, 40] numbers.sort(reverse=True) # Sort in descending order print(numbers) # Output: [40, 30, 20, 10]

Leave a Reply

Your email address will not be published. Required fields are marked *

sign up!

We’ll send you the hottest deals straight to your inbox so you’re always in on the best-kept software secrets.