0% found this document useful (0 votes)
3 views

Unit- 3 Python conditional and iterative statements

Unit 3 covers Python conditional and iterative statements, explaining how to use if, elif, and else statements for decision-making in code. It also introduces iterative statements like while and for loops, detailing their syntax and usage for executing code multiple times. Additionally, the document discusses lists in Python, including their creation, indexing, and slicing techniques.

Uploaded by

Dipak Yadav
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Unit- 3 Python conditional and iterative statements

Unit 3 covers Python conditional and iterative statements, explaining how to use if, elif, and else statements for decision-making in code. It also introduces iterative statements like while and for loops, detailing their syntax and usage for executing code multiple times. Additionally, the document discusses lists in Python, including their creation, indexing, and slicing techniques.

Uploaded by

Dipak Yadav
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 41

Unit- 3 Python conditional

and iterative statements

Createrd by: Priti Dhimmar


Conditional statements
• Conditional statements are used in programming to make decisions based on
certain conditions. These statements allow the execution of different code blocks
depending on whether a condition evaluates to True or False.

• The if statement is one of the fundamental conditional statements in programming. It


allows a program to execute a block of code only if a specified 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.")
• Else:
• Print(“you are not eligible to vote.”)
• Output: You are eligible to vote.
If..elif Statement
• The if..elif statement is used when multiple conditions need to be checked. If
the first condition is False, it checks the next condition using elif.
• syntax: if condition1:
• # Code to execute if condition1 is True
• elif condition2:
• # Code to execute if condition2 is True
Advantages
✔ Makes decision-making clear and structured.
✔ Reduces redundant code.
✔ Easy to read and maintain.
❌ Disadvantages
❌ Too many elif statements can make the code long and hard to
read.
❌ Nested conditions can become complex and difficult to debug.
if-elif statement example1
• marks = 75
• if marks >= 90:
• print("Grade: A")
• elif marks >= 75:
• print("Grade: B")
• Output: Grade: B
if-elif statement example2

• 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.

• The if..elif..else statement is used in programming to make


decisions based on multiple conditions. It allows a program to
evaluate different conditions one by one and execute the
corresponding code block for the first condition that is 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 marks >= 90:


• print("Grade: A")
• elif marks >= 80:
• print("Grade: B")
• elif marks >= 70:
• print("Grade: C")
• else:
• print("Grade: D")
• Output: Grade: C
Nested If Statement
• A nested if statement is when an if statement is placed inside another if
statement. This is useful when multiple levels of conditions need to be checked.
• A nested if statement is an if statement that appears inside another if
statement. This allows for multiple levels of condition checking, meaning
that a second condition is checked only if the first condition is True.

When to Use Nested If Statements?


•When you need to check multiple conditions sequentially.
•When a decision depends on another condition being True first.
•When there are multiple levels of filtering required.
• syntax:
• if condition1:
• # Executes if condition1 is True
• if condition2:
• # Executes if condition2 is also True
• statement
•The outer if statement checks the first condition.

•If the first condition is True, the inner if statement is evaluated.

•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"

• if age >= 18:


• print("You are an adult.")
• if gender == "Female":
• print("You are eligible for the women's scholarship.")
• Output: You are an adult.
• You are eligible for the women's scholarship.
• Nested if statements allow for more complex decision-making structures but
should be used carefully to keep the code readable.
.

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.

•sequence: The collection we are iterating over.



•Code block: The indented statements that execute in each iteration.
Example for loop
• fruits = ["apple", "banana", "cherry"]
• for fruit in fruits:
• print(fruit)
• Output:
• apple
• banana
• cherry
.

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.

You might also like