Python Programming
Unit-2: Program Flow Control
BCS302/BCC302 - AKTU University
3rd Semester
Comprehensive Study Material
rk
A
ic
Topics Covered:
m
de
• Conditional Blocks: if, else, else if
ca
• Simple For Loops
A
• For Loops with Ranges, Strings, Lists, and Dictionaries
• While Loops
• Loop Manipulation: pass, continue, break, else
• Programming using Conditional and Loop Blocks
AcademicArk
[Link]
October 30, 2025
AKTU Python Programming BCS302/BCC302 - Unit 2
Contents
1 Introduction to Program Flow Control 4
1.1 What is Program Flow Control? . . . . . . . . . . . . . . . . . . . . . . . 4
1.2 Types of Flow Control Structures . . . . . . . . . . . . . . . . . . . . . . 4
2 Conditional Statements: if, else, elif 5
2.1 The if Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.1.1 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.1.2 How if Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.1.3 Example 1: Simple if Statement . . . . . . . . . . . . . . . . . . . 5
2.1.4 Example 2: if with Compound Conditions . . . . . . . . . . . . . 6
2.2 The if-else Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.2.1 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.2.2 Flow Diagram for if-else . . . . . . . . . . . . . . . . . . . . . . . 6
2.2.3 Example 3: Simple if-else . . . . . . . . . . . . . . . . . . . . . . . 7
2.2.4 Example 4: Check Passing Grade . . . . . . . . . . . . . . . . . . 7
2.3 The if-elif-else Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.3.1 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.3.2 Key Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.3.3 Example 5: Grade Determination with Multiple Conditions . . . . 8
rk
2.3.4 Example 6: Traffic Light System . . . . . . . . . . . . . . . . . . 9
A
2.3.5 Example 7: Age Category Classification . . . . . . . . . . . . . . 9
ic
2.3.6 Nested if-elif-else . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
m
3 Simple For Loops in Python 10
de
3.1 Understanding For Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
ca
3.1.1 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
A
3.1.2 How For Loop Works . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.2 Simple For Loop Examples . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.2.1 Example 1: Print Numbers 1 to 5 . . . . . . . . . . . . . . . . . . 11
3.2.2 Example 2: Print Strings from a List . . . . . . . . . . . . . . . . 11
3.2.3 Example 3: Sum of Numbers . . . . . . . . . . . . . . . . . . . . 12
4 For Loops with Ranges, Strings, Lists, and Dictionaries 12
4.1 For Loop with range() . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
4.1.1 Syntax and Variations . . . . . . . . . . . . . . . . . . . . . . . . 12
4.1.2 Example 4: Print Numbers Using range() . . . . . . . . . . . . . . 13
4.1.3 Example 5: range() with Start and Stop . . . . . . . . . . . . . . 13
4.1.4 Example 6: range() with Step . . . . . . . . . . . . . . . . . . . . 13
4.1.5 Example 7: Multiplication Table Using range() . . . . . . . . . . 14
4.2 For Loop with Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
4.2.1 Example 8: Iterate Through Characters in a String . . . . . . . . 14
4.2.2 Example 9: Count Vowels in a String . . . . . . . . . . . . . . . . 15
4.2.3 Example 10: Print Characters with Positions . . . . . . . . . . . . 15
4.3 For Loop with Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
4.3.1 Example 11: Iterate Through a List of Numbers . . . . . . . . . . 16
4.3.2 Example 12: Filter List Items . . . . . . . . . . . . . . . . . . . . 16
4.3.3 Example 13: Using enumerate() with Lists . . . . . . . . . . . . . 16
1
AKTU Python Programming BCS302/BCC302 - Unit 2
4.4 For Loop with Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . 17
4.4.1 Methods to Iterate Dictionary . . . . . . . . . . . . . . . . . . . . 17
4.4.2 Example 14: Iterate Through Dictionary Keys . . . . . . . . . . . 17
4.4.3 Example 15: Iterate Through Dictionary Values . . . . . . . . . . 17
4.4.4 Example 16: Iterate Through Key-Value Pairs . . . . . . . . . . . 18
4.4.5 Example 17: Process Dictionary Data . . . . . . . . . . . . . . . . 18
5 While Loops in Python 19
5.1 Understanding While Loops . . . . . . . . . . . . . . . . . . . . . . . . . 19
5.1.1 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
5.1.2 Key Characteristics . . . . . . . . . . . . . . . . . . . . . . . . . . 19
5.1.3 While Loop Flow Diagram . . . . . . . . . . . . . . . . . . . . . . 20
5.2 While Loop Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
5.2.1 Example 18: Simple While Loop - Counting . . . . . . . . . . . . 20
5.2.2 Example 19: Sum of Numbers Using While Loop . . . . . . . . . 21
5.2.3 Example 20: Multiplication Table Using While Loop . . . . . . . 21
5.2.4 Example 21: User Input Validation . . . . . . . . . . . . . . . . . 22
5.2.5 Example 22: Number Guessing Game . . . . . . . . . . . . . . . . 22
5.2.6 Example 23: Factorial Calculation . . . . . . . . . . . . . . . . . . 23
5.2.7 Example 24: Reverse a Number . . . . . . . . . . . . . . . . . . . 23
rk
6 Loop Manipulation: break, continue, pass, and else 23
A
6.1 The break Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
ic
6.1.1 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
m
6.1.2 When to Use break . . . . . . . . . . . . . . . . . . . . . . . . . . 24
6.1.3 Example 25: Find a Number in a List . . . . . . . . . . . . . . . . 24
de
6.1.4 Example 26: Exit Loop Based on User Input . . . . . . . . . . . . 25
ca
6.1.5 Example 27: Finding First Even Number . . . . . . . . . . . . . . 25
A
6.2 The continue Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
6.2.1 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
6.2.2 When to Use continue . . . . . . . . . . . . . . . . . . . . . . . . 25
6.2.3 Example 28: Skip Even Numbers . . . . . . . . . . . . . . . . . . 26
6.2.4 Example 29: Skip Negative Numbers . . . . . . . . . . . . . . . . 27
6.2.5 Example 30: Skip Invalid Input . . . . . . . . . . . . . . . . . . . 28
6.3 The pass Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
6.3.1 When to Use pass . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
6.3.2 Example 31: pass as Placeholder . . . . . . . . . . . . . . . . . . 29
6.3.3 Example 32: pass in Conditional Statements . . . . . . . . . . . . 29
6.4 The else Clause in Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
6.4.1 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
6.4.2 How Loop-else Works . . . . . . . . . . . . . . . . . . . . . . . . . 30
6.4.3 Example 33: Loop-else for Search . . . . . . . . . . . . . . . . . . 30
6.4.4 Example 34: Loop-else for Successful Search . . . . . . . . . . . . 31
6.4.5 Example 35: Loop-else with While Loop . . . . . . . . . . . . . . 31
6.4.6 Example 36: Detecting Prime Numbers . . . . . . . . . . . . . . . 32
2
AKTU Python Programming BCS302/BCC302 - Unit 2
7 Nested Loops 32
7.1 Understanding Nested Loops . . . . . . . . . . . . . . . . . . . . . . . . . 32
7.1.1 Nested For Loop Syntax . . . . . . . . . . . . . . . . . . . . . . . 32
7.1.2 Example 37: Print Multiplication Table . . . . . . . . . . . . . . . 32
7.1.3 Example 38: Print Pattern Using Nested Loops . . . . . . . . . . 33
7.1.4 Example 39: 2D List Processing . . . . . . . . . . . . . . . . . . . 33
8 Comprehensive Programming Examples 34
8.1 Example 40: Temperature Classification Program . . . . . . . . . . . . . 34
8.2 Example 41: Student Grading System . . . . . . . . . . . . . . . . . . . . 35
8.3 Example 42: Pyramid Pattern Generator . . . . . . . . . . . . . . . . . . 36
8.4 Example 43: Data Analysis Program . . . . . . . . . . . . . . . . . . . . 36
9 Common Mistakes and Best Practices 37
9.1 Common Mistakes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
9.1.1 Example: Infinite Loop . . . . . . . . . . . . . . . . . . . . . . . . 37
9.2 Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
10 Summary and Key Takeaways 38
10.1 Key Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
10.2 When to Use Each Structure . . . . . . . . . . . . . . . . . . . . . . . . . 38
rk
A
ic
m
de
ca
A
3
AKTU Python Programming BCS302/BCC302 - Unit 2
1 Introduction to Program Flow Control
1.1 What is Program Flow Control?
[title=Definition: Program Flow Control] Program flow control refers to the mech-
anisms and structures that allow a programmer to control the order in which state-
ments are executed in a program. These structures enable us to make decisions
(conditional statements) and repeat blocks of code (loops) based on certain condi-
tions.
Without flow control, programs would execute linearly from top to bottom. Flow
control structures enable us to:
• Make decisions based on conditions (if-else statements)
• Repeat operations multiple times (loops)
• Skip certain statements (break, continue)
• Execute alternate code blocks
1.2 Types of Flow Control Structures
rk
Flow control structures in Python can be categorized into two main types:
A
ic
1. Conditional Statements: Control execution based on conditions
m
• if statement
de
• if-else statement
ca
• if-elif-else statement
A
2. Loop Statements: Repeat code blocks
• for loop
• while loop
• Nested loops
Program Start
Condition?
True False
Execute Block 1 Execute Block 2
Continue
4
AKTU Python Programming BCS302/BCC302 - Unit 2
2 Conditional Statements: if, else, elif
2.1 The if Statement
[title=Definition: if Statement] The if statement is used to execute a block of code
only if a specified condition is True. The condition is evaluated and if it evaluates
to True, the code block is executed; otherwise, it is skipped.
2.1.1 Syntax
1 if condition :
2 # Code block executes if condition is True
3 statement1
4 statement2
5 # Code outside if block ( always executes )
Listing 1: Basic if Statement Syntax
2.1.2 How if Works
rk
[title=Key Points about if Statement]
A
ic
• The condition must evaluate to a Boolean value (True or False)
m
• Indentation is mandatory in Python
de
ca
• Comparison operators: ==, !=, ¡, ¿, ¡=, ¿=
A
• Logical operators: and, or, not
• The colon (:) is required at the end of the if statement
2.1.3 Example 1: Simple if Statement
[title=Example 1: Check if a Number is Positive]
1 # Program to check if a number is positive
2 number = 15
3
4 if number > 0:
5 print ( " The number is positive " )
6
7 # Output : The number is positive
5
AKTU Python Programming BCS302/BCC302 - Unit 2
2.1.4 Example 2: if with Compound Conditions
[title=Example 2: Check Age for Movie Rating]
1 age = 16
2 rating = " PG -13 "
3
4 if age >= 13 and rating == " PG -13 " :
5 print ( " You can watch this movie " )
6 print ( " Parental guidance may be appropriate " )
7
8 # Output :
9 # You can watch this movie
10 # Parental guidance may be appropriate
2.2 The if-else Statement
[title=Definition: if-else Statement] The if-else statement allows us to execute one
block of code if a condition is True, and a different block if the condition is False.
This provides two alternative paths of execution.
rk
A
2.2.1 Syntax
ic
m
1 if condition :
de
2 # Code block executes if condition is True
ca
3 statement1
else :
A
5 # Code block executes if condition is False
6 statement2
Listing 2: if-else Statement Syntax
2.2.2 Flow Diagram for if-else
Condition?
True False
if Block else Block
Continue
6
AKTU Python Programming BCS302/BCC302 - Unit 2
2.2.3 Example 3: Simple if-else
[title=Example 3: Check if Number is Even or Odd]
1 number = 10
2
3 if number % 2 == 0:
4 print ( " The number is even " )
5 else :
6 print ( " The number is odd " )
7
8 # Output : The number is even
2.2.4 Example 4: Check Passing Grade
[title=Example 4: Student Grade Determination]
1 marks = 45
2
3 if marks >= 40:
4 print ( " You have passed the exam " )
k
5 else :
Ar
6 print ( " Sorry , you have failed " )
ic
7 print ( " Please work harder for the next exam " )
8
em
9 # Output :
ad
10 # You have passed the exam
Ac
2.3 The if-elif-else Statement
[title=Definition: if-elif-else Statement] The if-elif-else statement allows us to
check multiple conditions sequentially. If the first condition is False, the elif (else
if) condition is checked. This process continues until a True condition is found or
the else block is reached.
2.3.1 Syntax
1 if condition1 :
2 # Code block executes if condition1 is True
3 statement1
4 elif condition2 :
5 # Code block executes if condition1 is False and condition2
is True
6 statement2
7 elif condition3 :
8 # Code block executes if condition1 and condition2 are False
and condition3 is True
7
AKTU Python Programming BCS302/BCC302 - Unit 2
9 statement3
10 else :
11 # Code block executes if all conditions are False
12 statement4
Listing 3: if-elif-else Statement Syntax
2.3.2 Key Points
[title=Important Points about if-elif-else]
• You can have multiple elif blocks
• Only one block will execute
• Once a condition is True, remaining conditions are not checked
• The else block is optional
• elif must come between if and else
rk
2.3.3 Example 5: Grade Determination with Multiple Conditions
A
ic
[title=Example 5: Assign Letter Grades Based on Marks]
m
marks = 78
de
2
ca
3 if marks >= 90:
A
4 grade = " A "
5 elif marks >= 80:
6 grade = " B "
7 elif marks >= 70:
8 grade = " C "
9 elif marks >= 60:
10 grade = " D "
11 else :
12 grade = " F "
13
14 print ( f " Your grade is : { grade } " )
15
16 # Output : Your grade is : C
8
AKTU Python Programming BCS302/BCC302 - Unit 2
2.3.4 Example 6: Traffic Light System
[title=Example 6: Traffic Light Decision Making]
1 light_color = " yellow "
2
3 if light_color == " red " :
4 print ( " STOP " )
5 elif light_color == " yellow " :
6 print ( " PREPARE TO STOP " )
7 elif light_color == " green " :
8 print ( " GO " )
9 else :
10 print ( " Invalid light color " )
11
12 # Output : PREPARE TO STOP
2.3.5 Example 7: Age Category Classification
[title=Example 7: Classify Age into Categories]
rk
1 age = 25
A
2
ic
3 if age < 13:
m
4 category = " Child "
elif age < 18:
de
6 category = " Teenager "
ca
7 elif age < 60:
A
8 category = " Adult "
9 else :
10 category = " Senior "
11
12 print ( f " Age category : { category } " )
13
14 # Output : Age category : Adult
2.3.6 Nested if-elif-else
[title=Definition: Nested Conditional Statements] Nested conditionals are condi-
tional statements inside other conditional statements. They allow for more complex
decision-making logic.
9
AKTU Python Programming BCS302/BCC302 - Unit 2
[title=Example 8: Nested Conditions - User Validation]
1 username = " john123 "
2 password = " secure123 "
3
4 if username == " john123 " :
5 if password == " secure123 " :
6 print ( " Login successful " )
7 else :
8 print ( " Incorrect password " )
9 else :
10 print ( " Username not found " )
11
12 # Output : Login successful
3 Simple For Loops in Python
3.1 Understanding For Loops rk
[title=Definition: For Loop] A for loop is used to iterate over a sequence (such
as a list, tuple, string, or range) and execute a block of code repeatedly for each
A
item in the sequence. It eliminates the need to manually handle loop counters and
ic
conditions.
m
de
ca
3.1.1 Syntax
A
1 for variable in sequence :
2 # Code block executes for each item in sequence
3 statement1
4 statement2
5 # Code outside loop ( executes after loop completes )
Listing 4: Basic For Loop Syntax
3.1.2 How For Loop Works
• The loop starts with the first item in the sequence
• The variable takes the value of each item
• The code block executes
• This continues until all items are processed
• Control passes to statements after the loop
10
AKTU Python Programming BCS302/BCC302 - Unit 2
Get next item
More items?
Yes
Execute Block
No
Exit Loop
3.2 Simple For Loop Examples
3.2.1 Example 1: Print Numbers 1 to 5
[title=Example 1: Simple Counting Loop]
1 for i in [1 , 2 , 3 , 4 , 5]:
print ( i )
rk
2
3
A
4 # Output :
ic
5 # 1
m
6 # 2
de
7 # 3
8 # 4
ca
9 # 5
A
3.2.2 Example 2: Print Strings from a List
[title=Example 2: Iterate Over a List of Fruits]
1 fruits = [ " apple " , " banana " , " cherry " , " date " ]
2
3 for fruit in fruits :
4 print ( f " I like { fruit } " )
5
6 # Output :
7 # I like apple
8 # I like banana
9 # I like cherry
10 # I like date
11
AKTU Python Programming BCS302/BCC302 - Unit 2
3.2.3 Example 3: Sum of Numbers
[title=Example 3: Calculate Sum Using For Loop]
1 numbers = [10 , 20 , 30 , 40 , 50]
2 total = 0
3
4 for num in numbers :
5 total = total + num
6
7 print ( f " Sum of numbers : { total } " )
8
9 # Output : Sum of numbers : 150
4 For Loops with Ranges, Strings, Lists, and Dictio-
naries
4.1 For Loop with range()
rk
[title=Definition: range() Function] The range() function generates a sequence of
A
numbers. It is commonly used with for loops to iterate a specific number of times.
ic
The range() function is memory-efficient as it generates numbers on-the-fly.
m
de
4.1.1 Syntax and Variations
ca
A
1 # range ( stop ) - generates numbers from 0 to stop -1
2 range (5) # Generates : 0 , 1 , 2 , 3 , 4
3
4 # range ( start , stop ) - generates numbers from start to stop -1
5 range (2 , 7) # Generates : 2 , 3 , 4 , 5 , 6
6
7 # range ( start , stop , step ) - generates with step interval
8 range (1 , 10 , 2) # Generates : 1 , 3 , 5 , 7 , 9
Listing 5: range() Function Syntax Variations
12
AKTU Python Programming BCS302/BCC302 - Unit 2
4.1.2 Example 4: Print Numbers Using range()
[title=Example 4: Simple range() Loop]
1 # Print numbers 0 to 4
2 for i in range (5) :
3 print ( i )
4
5 # Output :
6 # 0
7 # 1
8 # 2
9 # 3
10 # 4
4.1.3 Example 5: range() with Start and Stop
[title=Example 5: range(start, stop)]
1 # Print numbers 3 to 7
2 for i in range (3 , 8) :
rk
3 print (i , end = " " )
A
4
ic
5 # Output : 3 4 5 6 7
m
de
ca
4.1.4 Example 6: range() with Step
A
[title=Example 6: range() with Step Value]
1 # Print even numbers from 0 to 10
2 for i in range (0 , 11 , 2) :
3 print (i , end = " " )
4
5 # Output : 0 2 4 6 8 10
13
AKTU Python Programming BCS302/BCC302 - Unit 2
4.1.5 Example 7: Multiplication Table Using range()
[title=Example 7: Print Multiplication Table of 5]
1 n = 5
2
3 print ( f " Multiplication Table of { n }: " )
4 for i in range (1 , 11) :
5 print ( f " { n } x { i } = { n * i } " )
6
7 # Output :
8 # Multiplication Table of 5:
9 # 5 x 1 = 5
10 # 5 x 2 = 10
11 # 5 x 3 = 15
12 # ... ( up to 5 x 10 = 50)
4.2 For Loop with Strings
[title=String Iteration] Strings in Python are sequences of characters. A for loop
rk
can iterate through each character in a string one by one.
A
ic
4.2.1 Example 8: Iterate Through Characters in a String
m
de
[title=Example 8: Print Each Character]
ca
1 word = " PYTHON "
A
3 for char in word :
4 print ( char )
5
6 # Output :
7 # P
8 # Y
9 # T
10 # H
11 # O
12 # N
14
AKTU Python Programming BCS302/BCC302 - Unit 2
4.2.2 Example 9: Count Vowels in a String
[title=Example 9: Vowel Counter]
1 sentence = " Python is awesome "
2 vowels = " aeiouAEIOU "
3 count = 0
4
5 for char in sentence :
6 if char in vowels :
7 count += 1
8
9 print ( f " Number of vowels : { count } " )
10
11 # Output : Number of vowels : 5
4.2.3 Example 10: Print Characters with Positions
[title=Example 10: Character Index and Value]
1 text = " HELLO "
rk
2
A
3 for index , char in enumerate ( text ) :
ic
4 print ( f " Index { index }: { char } " )
m
# Output :
de
7 # Index 0: H
ca
8 # Index 1: E
A
9 # Index 2: L
10 # Index 3: L
11 # Index 4: O
4.3 For Loop with Lists
[title=List Iteration] Lists are ordered collections of items. For loops iterate
through each item in a list sequentially, accessing one item per iteration.
15
AKTU Python Programming BCS302/BCC302 - Unit 2
4.3.1 Example 11: Iterate Through a List of Numbers
[title=Example 11: Process List Elements]
1 numbers = [5 , 10 , 15 , 20 , 25]
2
3 print ( " Numbers squared : " )
4 for num in numbers :
5 print ( f " { num }^2 = { num **2} " )
6
7 # Output :
8 # 5^2 = 25
9 # 10^2 = 100
10 # 15^2 = 225
11 # 20^2 = 400
12 # 25^2 = 625
4.3.2 Example 12: Filter List Items
[title=Example 12: Find Numbers Greater Than 15]
rk
1 numbers = [8 , 12 , 18 , 22 , 5 , 30 , 10]
A
2 large_numbers = []
ic
3
m
4 for num in numbers :
if num > 15:
de
6 large_numbers . append ( num )
ca
7
A
8 print ( " Numbers greater than 15: " , large_numbers )
9
10 # Output : Numbers greater than 15: [18 , 22 , 30]
4.3.3 Example 13: Using enumerate() with Lists
[title=Example 13: Access Index and Value with enumerate()]
1 students = [ " Alice " , " Bob " , " Charlie " , " Diana " ]
2
3 for index , student in enumerate ( students ) :
4 print ( f " { index + 1}. { student } " )
5
6 # Output :
7 # 1. Alice
8 # 2. Bob
9 # 3. Charlie
10 # 4. Diana
16
AKTU Python Programming BCS302/BCC302 - Unit 2
4.4 For Loop with Dictionaries
[title=Dictionary Iteration] Dictionaries store key-value pairs. For loops can iterate
through keys, values, or both items in a dictionary using different methods.
4.4.1 Methods to Iterate Dictionary
[title=Dictionary Iteration Methods]
1. Iterate through keys: for key in dictionary
2. Iterate through values: for value in [Link]()
3. Iterate through key-value pairs: for key, value in
[Link]()
4.4.2 Example 14: Iterate Through Dictionary Keys
[title=Example 14: Access Dictionary Keys]
rk
1 student_marks = { " Alice " : 85 , " Bob " : 78 , " Charlie " : 92}
A
3 for name in student_marks :
ic
4 print ( f " Student : { name } " )
m
5
de
6 # Output :
# Student : Alice
ca
8 # Student : Bob
A
9 # Student : Charlie
4.4.3 Example 15: Iterate Through Dictionary Values
[title=Example 15: Access Dictionary Values]
1 student_marks = { " Alice " : 85 , " Bob " : 78 , " Charlie " : 92}
2
3 for marks in student_marks . values () :
4 print ( f " Marks : { marks } " )
5
6 # Output :
7 # Marks : 85
8 # Marks : 78
9 # Marks : 92
17
AKTU Python Programming BCS302/BCC302 - Unit 2
4.4.4 Example 16: Iterate Through Key-Value Pairs
[title=Example 16: Access Both Key and Value]
1 student_marks = { " Alice " : 85 , " Bob " : 78 , " Charlie " : 92}
2
3 for name , marks in student_marks . items () :
4 print ( f " { name }: { marks } " )
5
6 # Output :
7 # Alice : 85
8 # Bob : 78
9 # Charlie : 92
4.4.5 Example 17: Process Dictionary Data
[title=Example 17: Calculate Average and Show Grades]
1 student_marks = { " Alice " : 85 , " Bob " : 78 , " Charlie " : 92}
2 total = 0
3
rk
4 for name , marks in student_marks . items () :
A
5 total += marks
ic
6 if marks >= 85:
m
7 grade = " A "
elif marks >= 70:
de
9 grade = " B "
ca
10 else :
A
11 grade = " C "
12 print ( f " { name }: { marks } - Grade { grade } " )
13
14 average = total / len ( student_marks )
15 print ( f " \\ nClass Average : { average :.2 f } " )
16
17 # Output :
18 # Alice : 85 - Grade A
19 # Bob : 78 - Grade B
20 # Charlie : 92 - Grade A
21 # Class Average : 85.00
18
AKTU Python Programming BCS302/BCC302 - Unit 2
5 While Loops in Python
5.1 Understanding While Loops
[title=Definition: While Loop] A while loop repeatedly executes a block of code
as long as a specified condition is True. Unlike for loops that iterate a fixed number
of times, while loops continue until the condition becomes False.
5.1.1 Syntax
1 while condition :
2 # Code block executes as long as condition is True
3 statement1
4 statement2
5 # Important : Update condition to eventually become False
6 # Code outside loop
Listing 6: While Loop Syntax
rk
5.1.2 Key Characteristics
A
ic
[title=Important Points about While Loops]
m
• The condition is checked before each iteration
de
• If the condition is False initially, the loop body never executes
ca
A
• The loop continues until the condition becomes False
• You must ensure the condition eventually becomes False (avoid infinite loops)
• The counter/condition variable must be updated inside the loop
19
AKTU Python Programming BCS302/BCC302 - Unit 2
5.1.3 While Loop Flow Diagram
Check Condition
Condition True?
Yes
ExecuteNo
Block
Exit Loop
5.2 While Loop Examples
5.2.1 Example 18: Simple While Loop - Counting
rk
[title=Example 18: Count from 1 to 5]
A
1 count = 1
ic
2
m
3 while count <= 5:
de
4 print ( count )
5 count = count + 1
ca
6
A
7 print ( " Loop finished " )
8
9 # Output :
10 # 1
11 # 2
12 # 3
13 # 4
14 # 5
15 # Loop finished
20
AKTU Python Programming BCS302/BCC302 - Unit 2
5.2.2 Example 19: Sum of Numbers Using While Loop
[title=Example 19: Calculate Sum of First N Numbers]
1 n = 5
2 sum_value = 0
3 i = 1
4
5 while i <= n :
6 sum_value += i
7 i += 1
8
9 print ( f " Sum of first { n } numbers : { sum_value } " )
10
11 # Output : Sum of first 5 numbers : 15
5.2.3 Example 20: Multiplication Table Using While Loop
[title=Example 20: Print Multiplication Table]
1 number = 7
rk
2 multiplier = 1
A
3
ic
4 print ( f " Multiplication Table of { number }: " )
m
while multiplier <= 10:
de
7 print ( f " { number } x { multiplier } = { number * multiplier } "
ca
)
A
8 multiplier += 1
9
10 # Output :
11 # Multiplication Table of 7:
12 # 7 x 1 = 7
13 # 7 x 2 = 14
14 # ... ( up to 7 x 10 = 70)
21
AKTU Python Programming BCS302/BCC302 - Unit 2
5.2.4 Example 21: User Input Validation
[title=Example 21: Validate User Input with While Loop]
1 password = " "
2 correct_password = " python123 "
3
4 while password != correct_password :
5 password = input ( " Enter password : " )
6 if password != correct_password :
7 print ( " Incorrect password . Try again . " )
8
9 print ( " Password correct ! Welcome ! " )
10
11 # This program keeps asking until correct password is
entered
5.2.5 Example 22: Number Guessing Game
[title=Example 22: Simple Number Guessing Game]
rk
1 secret_number = 42
A
2 guess = 0
ic
3 attempts = 0
m
while guess != secret_number :
de
6 guess = int ( input ( " Guess the number : " ) )
ca
7 attempts += 1
A
9 if guess < secret_number :
10 print ( " Too low ! Try again . " )
11 elif guess > secret_number :
12 print ( " Too high ! Try again . " )
13 else :
14 print ( f " Correct ! You guessed it in { attempts }
attempts . " )
15
16 # Program continues until correct number is guessed
22
AKTU Python Programming BCS302/BCC302 - Unit 2
5.2.6 Example 23: Factorial Calculation
[title=Example 23: Calculate Factorial Using While Loop]
1 number = 5
2 factorial = 1
3 i = 1
4
5 while i <= number :
6 factorial *= i
7 i += 1
8
9 print ( f " Factorial of { number } is : { factorial } " )
10
11 # Output : Factorial of 5 is : 120
5.2.7 Example 24: Reverse a Number
[title=Example 24: Reverse Number Using While Loop]
1 number = 12345
k
2 reversed_number = 0
Ar
3
ic
4 while number > 0:
5 digit = number % 10
em
6 reversed_number = reversed_number * 10 + digit
ad
7 number = number // 10
Ac
9 print ( f " Reversed number : { reversed_number } " )
10
11 # Output : Reversed number : 54321
6 Loop Manipulation: break, continue, pass, and
else
6.1 The break Statement
[title=Definition: break Statement] The break statement is used to terminate a
loop prematurely. When a break statement is encountered, the loop stops imme-
diately and control passes to the statement following the loop.
6.1.1 Syntax
1 for / while condition :
2 if some_condition :
3 break # Exits the loop immediately
23
AKTU Python Programming BCS302/BCC302 - Unit 2
4 # Other statements
Listing 7: break Statement Usage
6.1.2 When to Use break
• When a specific condition is met and we want to exit the loop
• In search operations when the target is found
• In error handling when an invalid input is encountered
• When we want to stop processing and move to the next task
6.1.3 Example 25: Find a Number in a List
[title=Example 25: Search and Exit with break]
1 numbers = [5 , 10 , 15 , 20 , 25 , 30]
2 search_number = 20
3 found = False
rk
4
5 for num in numbers :
A
6 if num == search_number :
ic
7 print ( f " Found { search_number }! " )
m
8 found = True
de
9 break
10 print ( f " Checking { num }... " )
ca
11
A
12 if not found :
13 print ( f " { search_number } not found . " )
14
15 # Output :
16 # Checking 5...
17 # Checking 10...
18 # Checking 15...
19 # Found 20!
24
AKTU Python Programming BCS302/BCC302 - Unit 2
6.1.4 Example 26: Exit Loop Based on User Input
[title=Example 26: break with While Loop and Input]
1 while True :
2 command = input ( " Enter ’ quit ’ to exit : " )
3 if command == " quit " :
4 print ( " Exiting program ... " )
5 break
6 print ( f " You entered : { command } " )
7
8 # Continues until user enters ’ quit ’
6.1.5 Example 27: Finding First Even Number
[title=Example 27: break in Search Operation]
1 numbers = [11 , 13 , 15 , 8 , 20 , 9]
2
3 for num in numbers :
4 if num % 2 == 0:
rk
5 print ( f " First even number : { num } " )
A
6 break
ic
7 else :
m
8 print ( " No even numbers found " )
de
10 # Output : First even number : 8
ca
A
6.2 The continue Statement
[title=Definition: continue Statement] The continue statement skips the current
iteration of the loop and continues with the next iteration. The rest of the code in
the current iteration is skipped, but the loop continues.
6.2.1 Syntax
1 for / while condition :
2 if some_condition :
3 continue # Skips current iteration
4 # Other statements ( skipped if continue is executed )
Listing 8: continue Statement Usage
6.2.2 When to Use continue
• Skip certain iterations based on a condition
25
AKTU Python Programming BCS302/BCC302 - Unit 2
• Process only specific items and skip others
• Avoid executing certain code for specific values
• In data filtering operations
6.2.3 Example 28: Skip Even Numbers
[title=Example 28: Use continue to Skip Values]
1 numbers = [1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10]
2
3 print ( " Odd numbers only : " )
4 for num in numbers :
5 if num % 2 == 0:
6 continue # Skip even numbers
7 print ( num )
8
9 # Output :
10 # Odd numbers only :
11 # 1
12 # 3
rk
13 # 5
14 # 7
A
15 # 9
ic
m
de
ca
A
26
AKTU Python Programming BCS302/BCC302 - Unit 2
6.2.4 Example 29: Skip Negative Numbers
[title=Example 29: Filter Out Negative Numbers]
1 values = [5 , -3 , 8 , -1 , 0 , 12 , -7 , 15]
2
3 print ( " Processing positive values : " )
4 total = 0
5
6 for value in values :
7 if value < 0:
8 continue # Skip negative numbers
9 total += value
10 print ( f " Added { value } , Running total : { total } " )
11
12 print ( f " Final total : { total } " )
13
14 # Output :
15 # Processing positive values :
16 # Added 5 , Running total : 5
17 # Added 8 , Running total : 13
18 # Added 0 , Running total : 13
rk
19 # Added 12 , Running total : 25
# Added 15 , Running total : 40
A
20
21 # Final total : 40
ic
m
de
ca
A
27
AKTU Python Programming BCS302/BCC302 - Unit 2
6.2.5 Example 30: Skip Invalid Input
[title=Example 30: continue with Input Validation]
1 scores = [85 , " invalid " , 92 , 78 , " error " , 88]
2
3 total = 0
4 count = 0
5
6 for score in scores :
7 if not isinstance ( score , int ) :
8 print ( f " Skipping invalid score : { score } " )
9 continue
10 total += score
11 count += 1
12
13 average = total / count if count > 0 else 0
14 print ( f " Average : { average :.2 f } " )
15
16 # Output :
17 # Skipping invalid score : invalid
18 # Skipping invalid score : error
rk
19 # Average : 85.75
A
ic
m
6.3 The pass Statement
de
ca
[title=Definition: pass Statement] The pass statement is a null operation. When
executed, nothing happens. It is used as a placeholder when a statement is required
A
syntactically but no action needs to be taken.
6.3.1 When to Use pass
[title=Common Uses of pass Statement]
• As a placeholder in empty code blocks
• In incomplete function or class definitions
• When writing stub code for later implementation
• In exception handling for ignored exceptions
• In loops when certain conditions don’t require action
28
AKTU Python Programming BCS302/BCC302 - Unit 2
6.3.2 Example 31: pass as Placeholder
[title=Example 31: Using pass in Loop]
1 numbers = [1 , 2 , 3 , 4 , 5]
2
3 for num in numbers :
4 if num == 3:
5 pass # Do nothing for number 3
6 else :
7 print ( f " Number : { num } " )
8
9 # Output :
10 # Number : 1
11 # Number : 2
12 # Number : 4
13 # Number : 5
6.3.3 Example 32: pass in Conditional Statements
[title=Example 32: pass in if-else]
k
Ar
1 age = 15
ic
3 if age >= 18:
em
4 print ( " You are an adult " )
ad
5 else :
Ac
6 pass # No action needed for minors currently
7
8 # Program continues ...
6.4 The else Clause in Loops
[title=Definition: else with Loops] Python allows an else clause with both for and
while loops. The else block executes when the loop completes normally (without
encountering a break statement). If break is executed, the else block is skipped.
6.4.1 Syntax
1 for variable in sequence :
2 if some_condition :
3 break
4 else :
5 # Executes if loop completes without break
6 statement
7
8 while condition :
29
AKTU Python Programming BCS302/BCC302 - Unit 2
9 if some_condition :
10 break
11 else :
12 # Executes if loop completes without break
13 statement
Listing 9: Loop with else Clause
6.4.2 How Loop-else Works
• If the loop completes normally, the else block executes
• If break is encountered, the else block is skipped
• The else clause is optional
• It’s useful for detecting whether a condition was found or not
6.4.3 Example 33: Loop-else for Search
[title=Example 33: Using else with For Loop]
rk
1 numbers = [2 , 4 , 6 , 8 , 10]
A
2 target = 7
ic
3
m
4 for num in numbers :
de
5 if num == target :
6 print ( f " Found { target } " )
ca
7 break
A
8 else :
9 print ( f " { target } not found in the list " )
10
11 # Output : 7 not found in the list
30
AKTU Python Programming BCS302/BCC302 - Unit 2
6.4.4 Example 34: Loop-else for Successful Search
[title=Example 34: Loop completes without break]
1 numbers = [2 , 4 , 6 , 8 , 10]
2 target = 6
3
4 for num in numbers :
5 if num == target :
6 print ( f " Found { target }! " )
7 break
8 else :
9 print ( f " { target } not found in the list " )
10
11 # Output : Found 6!
6.4.5 Example 35: Loop-else with While Loop
[title=Example 35: else with While Loop]
1 count = 1
rk
2
A
3 while count <= 3:
ic
4 print ( f " Iteration { count } " )
m
5 count += 1
else :
de
7 print ( " Loop completed successfully " )
ca
8
A
9 # Output :
10 # Iteration 1
11 # Iteration 2
12 # Iteration 3
13 # Loop completed successfully
31
AKTU Python Programming BCS302/BCC302 - Unit 2
6.4.6 Example 36: Detecting Prime Numbers
[title=Example 36: Prime Number Check Using Loop-else]
1 number = 17
2
3 for i in range (2 , number ) :
4 if number % i == 0:
5 print ( f " { number } is not prime " )
6 break
7 else :
8 print ( f " { number } is prime " )
9
10 # Output : 17 is prime
7 Nested Loops
7.1 Understanding Nested Loops
[title=Definition: Nested Loops] Nested loops are loops within loops. The inner
rk
loop executes completely for each iteration of the outer loop. Nested loops are
A
useful for working with multi-dimensional data or creating patterns.
ic
m
de
7.1.1 Nested For Loop Syntax
ca
1 for variable1 in sequence1 :
A
2 # Outer loop
3 for variable2 in sequence2 :
4 # Inner loop
5 statement
6 # Back to outer loop
Listing 10: Nested For Loop Syntax
7.1.2 Example 37: Print Multiplication Table
[title=Example 37: Multiplication Table Using Nested Loops]
1 print ( " Multiplication Tables 1 -3: " )
2 for i in range (1 , 4) :
3 print ( f " \\ nTable of { i }: " )
4 for j in range (1 , 6) :
5 print ( f " { i } x { j } = { i * j } " )
6
7 # Output shows 3 multiplication tables
32
AKTU Python Programming BCS302/BCC302 - Unit 2
7.1.3 Example 38: Print Pattern Using Nested Loops
[title=Example 38: Star Pattern]
1 rows = 5
2
3 for i in range (1 , rows + 1) :
4 for j in range ( i ) :
5 print ( " * " , end = " " )
6 print ()
7
8 # Output :
9 # *
10 # * *
11 # * * *
12 # * * * *
13 # * * * * *
7.1.4 Example 39: 2D List Processing rk
[title=Example 39: Process 2D List with Nested Loops]
A
1 matrix = [
ic
2 [1 , 2 , 3] ,
m
3 [4 , 5 , 6] ,
[7 , 8 , 9]
de
5 ]
ca
6
A
7 print ( " Matrix elements : " )
8 for row in matrix :
9 for element in row :
10 print ( element , end = " " )
11 print ()
12
13 # Output :
14 # 1 2 3
15 # 4 5 6
16 # 7 8 9
33
AKTU Python Programming BCS302/BCC302 - Unit 2
8 Comprehensive Programming Examples
8.1 Example 40: Temperature Classification Program
[title=Example 40: Complete Program with Conditionals and Loops]
1 temperatures = [15 , 25 , 5 , 32 , 28 , 8 , 35]
2
3 print ( " Temperature Classification Report : " )
4 print ( " -" * 40)
5
6 for temp in temperatures :
7 if temp < 0:
8 classification = " Freezing "
9 elif temp < 15:
10 classification = " Cold "
11 elif temp < 25:
12 classification = " Cool "
13 elif temp < 35:
14 classification = " Warm "
15 else :
16 classification = " Hot "
rk
17
A
18 print ( f " Temperature : { temp } C - { classification } " )
ic
19
print ( " -" * 40)
m
20
de
ca
A
34
AKTU Python Programming BCS302/BCC302 - Unit 2
8.2 Example 41: Student Grading System
[title=Example 41: Student Grade Calculator]
1 students = {
2 " Alice " : 85 ,
3 " Bob " : 78 ,
4 " Charlie " : 92 ,
5 " Diana " : 88 ,
6 " Eve " : 76
7 }
8
9 print ( " Student Grading Report : " )
10 print ( f " { ’ Name ’: <15}{ ’ Marks ’: <10}{ ’ Grade ’: <10} " )
11 print ( " -" * 35)
12
13 total_marks = 0
14 for name , marks in students . items () :
15 total_marks += marks
16
17 if marks >= 90:
18 grade = " A "
rk
19 elif marks >= 80:
grade = " B "
A
20
21 elif marks >= 70:
ic
22 grade = " C "
m
23 else :
de
24 grade = " D "
ca
25
26 print ( f " { name : <15}{ marks : <10}{ grade : <10} " )
A
27
28 average = total_marks / len ( students )
29 print ( " -" * 35)
30 print ( f " Class Average : { average :.2 f } " )
35
AKTU Python Programming BCS302/BCC302 - Unit 2
8.3 Example 42: Pyramid Pattern Generator
[title=Example 42: Number Pyramid Pattern]
1 n = 5
2
3 print ( " Number Pyramid : " )
4 for i in range (1 , n + 1) :
5 for j in range (1 , i + 1) :
6 print (j , end = " " )
7 print ()
8
9 print ( " \\ nNumber Pyramid ( Reverse ) : " )
10 for i in range (n , 0 , -1) :
11 for j in range (1 , i + 1) :
12 print (j , end = " " )
13 print ()
14
15 # Output shows two pyramids
rk
8.4 Example 43: Data Analysis Program
A
[title=Example 43: Calculate Statistics from Data]
ic
m
1 data = [45 , 67 , 23 , 89 , 56 , 78 , 34 , 90 , 12]
de
sum_data = 0
ca
4 max_value = data [0]
A
5 min_value = data [0]
6
7 for value in data :
8 sum_data += value
9 if value > max_value :
10 max_value = value
11 if value < min_value :
12 min_value = value
13
14 average = sum_data / len ( data )
15
16 print ( " Data Analysis Report : " )
17 print ( f " Total values : { len ( data ) } " )
18 print ( f " Sum : { sum_data } " )
19 print ( f " Average : { average :.2 f } " )
20 print ( f " Maximum : { max_value } " )
21 print ( f " Minimum : { min_value } " )
22 print ( f " Range : { max_value - min_value } " )
36
AKTU Python Programming BCS302/BCC302 - Unit 2
9 Common Mistakes and Best Practices
9.1 Common Mistakes
[title=Common Mistakes to Avoid]
1. Infinite Loops: Forgetting to update loop variables or conditions
2. Incorrect Indentation: Python uses indentation to define blocks
3. Off-by-One Errors: Using wrong range values or indices
4. Missing Colons: Forgetting colons after if, elif, else, for, while statements
5. Modifying Loop Variable: Changing loop variable inside the loop unpre-
dictably
9.1.1 Example: Infinite Loop
1 # DO NOT RUN THIS CODE
2 # count = 5
# while count > 0:
rk
3
4 # print ( count )
A
5 # # Missing : count -= 1
ic
6 # # This will run forever !
m
Listing 11: Infinite Loop Example (AVOID THIS)
de
ca
A
9.2 Best Practices
[title=Best Practices for Flow Control]
1. Use for loops when iterating over sequences with known length
2. Use while loops for conditions that change unpredictably
3. Always ensure loop conditions will eventually become False
4. Use meaningful variable names (not just i, j, k)
5. Keep loop bodies simple and understandable
6. Use break and continue sparingly for clarity
7. Test edge cases and boundary conditions
8. Add comments to explain complex logic
37
AKTU Python Programming BCS302/BCC302 - Unit 2
10 Summary and Key Takeaways
10.1 Key Concepts
• Conditional Statements (if, elif, else) control program flow based on conditions
• For Loops iterate over sequences with a known number of iterations
• While Loops repeat code as long as a condition remains True
• range() function generates numeric sequences for loops
• break exits a loop immediately
• continue skips the current iteration and continues to the next
• pass serves as a placeholder for empty code blocks
• else clause with loops executes when loop completes without break
• Nested loops allow complex iteration patterns
10.2 When to Use Each Structure
rk
• Use if-elif-else for multiple conditions and decision making
A
• Use for loops for iterating known sequences (lists, strings, ranges)
ic
m
• Use while loops for event-driven or condition-based repetition
de
• Use break when you find what you’re searching for
ca
A
• Use continue to skip unwanted iterations
• Use nested loops for multi-dimensional data processing
38
AKTU Python Programming BCS302/BCC302 - Unit 2
Quick Reference Guide
• if : if condition: statements
• if-else: if condition: statements1 else: statements2
• if-elif-else: if condition1: ... elif condition2: ... else: ...
• for loop: for variable in sequence: statements
• while loop: while condition: statements
• range(): range(stop) or range(start, stop) or range(start, stop, step)
• break: Exits the loop immediately
• continue: Skips current iteration
• pass: Do nothing (placeholder)
• Loop-else: else clause after loop executes if no break occurs
rk
A
ic
m
de
ca
A
AcademicArk
Comprehensive Learning Platform
[Link]
Study Material for AKTU University
BCS302/BCC302 - Python Programming
39