Unit- 3 Python conditional and iterative statements
Unit- 3 Python conditional and iterative statements
• letter = "A"
• if letter == "B":
• print("letter is B")
• elif letter == "C":
• print("letter is C")
• elif letter == "A":
• print("letter is A")
• else:
• print("letter isn't A, B or C")
If..elif..else Statement
• The if..elif..else statement includes a final else block that
executes when none of the previous conditions are True.
•
syntax
• if condition1:
• # Executes if condition1 is True
• elif condition2:
• # Executes if condition1 is False and condition2 is True
• elif condition3:
• # Executes if both condition1 and condition2 are False and
condition3 is True
• else:
• # Executes if all the above conditions are False
example1
• num = -5
• if num > 0:
• print("Positive number")
• elif num < 0:
• print("Negative number")
• else:
• print("Zero")
• Output: Negative number
ex2
• marks = 75
•If the inner condition is also True, the block inside it executes.
•If either condition is False, the corresponding block does not execute.
• Advantages of Nested If Statements
• ✅ Allows complex decision-making.
✅ Ensures that conditions are checked in a logical order.
✅ Helps implement multi-level filtering.
Disadvantages of Nested If Statements
❌ Can make the code harder to read if deeply nested.
❌ Increases complexity, making debugging difficult.
❌ Better alternatives, like using elif or logical operators (and),
may exist in some cases.
example
• age = 20
• citizenship = "Indian"
• if age >= 18:
• print("You are an adult.")
• if citizenship == "Indian":
• print("You are eligible to vote in India.")
• Output: You are an adult.
• You are eligible to vote in India.
• The first if checks if age is 18 or above. If True, it prints "You are an
adult."
•Then, the nested if checks if citizenship is "Indian". If True, it prints
"You are eligible to vote in India.
example
• age = 20
• gender = "Female"
Iterative Statements
Iterative statements, also known as loops, are used in programming to
execute a block of code multiple times until a specified condition is met. The
primary types of loops in most programming languages include the while
loop, for loop, and do-while loop.
While Loop:
A while loop is an entry-controlled loop, meaning the condition is checked before
executing the loop body. If the condition is true, the statements inside the loop
execute. If it is false, the loop terminates
Syntax:
while condition:
# Statements to be executed
• condition: This is a Boolean expression that determines
whether the loop continues.
•If the condition evaluates to True, the loop body executes.
•If the condition evaluates to False, the loop terminates.
• Example 1: Print numbers from 1 to 5
•i=1
while i <= 5:
print(i)
i += 1
• i=1
• while i <= 5:
• print(i)
• i += 1
• output:
• 1
• 2
• 3
• 4
• 5
Nested while loop
A nested while loop means a while loop inside another while loop. It is used
when we need to repeat a process multiple times within another repeating
process.
Step-by-Step Execution
1.The outer loop starts and checks its condition.
2.If the condition is True, the inner loop starts.
3.The inner loop executes until its condition becomes False.
4.After the inner loop ends, the control goes back to the outer loop.
5.The outer loop updates and repeats the process until its condition
becomes False.
• i = 1 # Outer loop counter
• while i <= 3: # Outer loop runs 3 times
• j = 1 # Inner loop counter
• while j <= 3: # Inner loop runs 3 times for each outer loop iteration
• print(f"i={i}, j={j}")
• j += 1 # Increment inner loop counter
• i += 1 # Increment outer loop counter
For loop
• A for loop is used to iterate over sequences such as lists, tuples,
dictionaries, sets, and strings. It repeatedly executes a block of code
for each item in the sequence.
• Syntax:
• for variable in sequence:
• # Code block to execute
•variable: A temporary variable that holds the current item of the sequence.
Explanation:
•The loop iterates through fruits.
•The fruit variable takes values "apple", "banana", and "cherry" in each
iteration.
•print(fruit) prints the current value
For loop with a string
• word = "Python"
• for letter in word:
• print(letter)
• Output:
• P
• y
• t
• h
• o
• n
For loop with Range() function
• The range(start, stop, step) function generates a sequence of numbers.
• Printing numbers 1 to 5
• for i in range(1, 6): # Starts from 1, stops at 5 (not 6)
• print(i)
• Output:
• 1
• 2
• 3
• 4
• 5
Using range() with different steps
• for i in range(1, 10, 2): # Start at 1, end before 10, step by 2
• print(i)
• output:
• 1 # if we write (1,10,3=> o/p like 1 4 7)
•3
•5
•7
•9
For loop with break statement
• The break statement stops the loop immediately.
• for i in range(1, 6):
• if i == 3:
• break # Loop stops when i == 3
• print(i)
• Output
• 1
• 2
• The loop stops at i == 3 and does not print 3, 4, 5.
for Loop with continue Statement
• The continue statement skips the current iteration and moves to the next.
• Eg:
• for i in range(1, 6):
• if i == 3:
• continue # Skips printing 3
• print(i)
• Output:
• 1
• 2
• 4
• 5
For loop with pass statement
The pass statement is a placeholder when a loop is required but no action
needs to be taken.
for i in range(1, 6):
if i == 3:
pass # Does nothing, just a placeholder
print(i)
Output:
1
2
3
4
5
Else with for loop
The else block executes when the loop completes normally (without a
break).
for i in range(1, 4):
print(i)
else:
print("Loop completed successfully!")
Output:
1
2
3
Loop completed successfully!
If break is used wont execute
• for i in range(1, 4):
• if i == 2:
• break
• print(i)
• else:
• print("Loop completed successfully!") # Won't execute
• Output:
•1
The break statement is used to exit a loop prematurely when a certain
condition is met.
for num in range(1, 10):
if num == 5:
print("Breaking the loop at", num)
break # Exits the loop immediately
print(num)
Output: 1
2
3
4
Breaking the loop at 5
continue Statement
The continue statement skips the current iteration and moves to the next
iteration of the loop.
for num in range(1, 10):
if num == 5:
print("Skipping", num)
continue # Skips this iteration and moves to the next
print(num)
• 1
•2
•3
•4
• Skipping 5
•6
•7
•8
•9
.
List in python
• A list in Python is a collection that is ordered, changeable (mutable), and allows
duplicate elements. Lists are one of the most commonly used data structures in
Python.
Creating a List
A list can be created using square brackets [] and can contain elements of
different data types
# Creating lists
empty_list = [] # Empty list
numbers = [1, 2, 3, 4, 5] # List of integers
mixed = [1, "hello", 3.14, True] # List with multiple data types
nested_list = [[1, 2], [3, 4]] # Nested list
print(numbers)
Indexing in Lists
• Indexing is used to access elements in a list. Indexing in Python starts
from 0.
• fruits = ["apple", "banana", "cherry"]
• print(fruits[0]) # Output: apple
• print(fruits[1]) # Output: banana
• print(fruits[2]) # Output: cherry
• print(fruits[-1]) # Output: cherry (negative index starts from the end)
Accessing List Members
• You can access single or multiple elements of a list using indexing and slicing.
• numbers = [10, 20, 30, 40, 50]
• print(numbers[2]) # Output: 30
• print(numbers[-2]) # Output: 40 (Negative indexing)
• Indexing allows us to access individual elements of a list. Python uses
zero-based indexing, meaning the first element is at index 0, the second at
index 1, and so on. We can also use negative indexing to count from the end
of the list.
•Use indexing to access single elements (list[index]).
•Use negative indexing to access elements from the end (list[-
1]).
•Use slicing to access multiple elements (list[start:stop:step]).
•Nested lists require multiple indexes (list[row][column]).
•Use the in keyword to check if an element exists in a list.
•Use loops to iterate over lists.
• Range in List (Slicing) – Detailed Explanation
• Slicing in Python allows us to extract a subset of elements from a list. The syntax
for slicing is:
• list[start:stop:step]
• start → The index where slicing starts (inclusive).
•stop → The index where slicing stops (exclusive).
•step → (Optional) Specifies the interval between elements.