GURU NANAK INSTITUTE OF TECHNOLOGY
NAAC ACCREDITED | DEPARTMENT OF ARTIFICIAL INTELLIGENCE & MACHINE LEARNING
Session 2026-27 (ODD) | Semester III | Subject: Python Programming (Code: BOE3T01)
ASSIGNMENT 2 SOLUTION (UNIT II)
Date of Declaration: 29.07.2026 Date of Submission: 07.08.2026
QUESTION 1: Explain the if, if-else, and nested if-else statements in Python with suitable syntax and
examples.
In Python, conditional statements are control flow structures that allow a program to execute specific blocks of
code based on whether a given condition evaluates to True or False. Python relies on indentation (whitespace)
to define the scope of code blocks following conditional statements.
1. The if Statement
The if statement is the simplest decision-making statement. It evaluates a boolean expression. If the
expression is True, the code block inside the if statement is executed. If False, the block is skipped entirely.
Code Example: if Statement Syntax
Syntax:
if condition:
# Code to execute if condition is True
statement_1
statement_2
Code Example: Simple if Statement
age = 20
if age >= 18:
print('Eligible to vote in India.')
print('Please register your voter ID.')
Output:
Eligible to vote in India.
Please register your voter ID.
2. The if-else Statement
The if-else statement provides an alternate path of execution. If the condition evaluates to True, the if block
runs. If the condition evaluates to False, the else block runs.
Code Example: if-else Statement Syntax
Syntax:
if condition:
# Code executed if condition is True
statement_if
else:
# Code executed if condition is False
statement_else
Code Example: if-else Statement
marks = 42
if marks >= 40:
print('Status: PASSED the examination.')
else:
print('Status: FAILED. Needs re-examination.')
Output:
Status: PASSED the examination.
3. The Nested if-else Statement
A nested if-else statement occurs when an if or else block contains another if-else statement inside it. This
allows checking multiple layered conditions sequentially.
Code Example: Nested if-else Syntax
Syntax:
if outer_condition:
if inner_condition:
# Executed if both outer and inner conditions are True
statement_1
else:
# Executed if outer is True but inner is False
statement_2
else:
# Executed if outer_condition is False
statement_3
Code Example: Nested if-else Execution
account_active = True
balance = 1500
withdrawal_amount = 500
if account_active:
if balance >= withdrawal_amount:
balance -= withdrawal_amount
print(f'Transaction successful! Remaining balance: INR {balance}')
else:
print('Transaction failed: Insufficient account balance.')
else:
print('Transaction failed: Account is suspended.')
Output:
Transaction successful! Remaining balance: INR 1000
Figure 1.1: Logical execution flowcharts for simple if-else and nested if-else structures.
QUESTION 2: Differentiate between for and while loops in Python with suitable examples.
Loops are control structures used to repeatedly execute a block of code as long as a specified condition is met
or until a sequence of items is exhausted. Python provides two primary loop constructs: for loop and while
loop.
Comparison Table: for Loop vs. while Loop
Feature / Aspect for Loop while Loop
Primary Purpose Iterating over a sequence/iterable (list, Executing a block of code as long as a
tuple, string, range). condition evaluates to True.
Nature of Loop Definite iteration — number of Indefinite iteration — number of
repetitions is known beforehand. repetitions depends on runtime
condition.
Initialization & Increment Handled automatically by Python's Must be explicitly defined and managed
iterator mechanism. by the programmer inside loop body.
Infinite Loop Risk Extremely low risk (terminates when High risk if condition is never updated to
sequence ends). evaluate to False.
Syntax Structure for var in sequence: while condition:
1. Python for Loop Example
A for loop iterates over elements of any sequence (such as a list or a range object) in order.
Code Example: for Loop Iteration
# Calculating the sum of first 5 natural numbers using for loop
total_sum = 0
for i in range(1, 6):
total_sum += i
print(f'Step {i}: Current sum = {total_sum}')
print(f'Final Sum: {total_sum}')
Output:
Step 1: Current sum = 1
Step 2: Current sum = 3
Step 3: Current sum = 6
Step 4: Current sum = 10
Step 5: Current sum = 15
Final Sum: 15
2. Python while Loop Example
A while loop continues executing as long as the test expression remains True.
Code Example: while Loop Iteration
# Countdown timer demonstrating while loop
countdown = 5
while countdown > 0:
print(f'Timer: {countdown} seconds remaining...')
countdown -= 1 # Crucial step to prevent infinite loop
print('Blastoff! Timer reached zero.')
Output:
Timer: 5 seconds remaining...
Timer: 4 seconds remaining...
Timer: 3 seconds remaining...
Timer: 2 seconds remaining...
Timer: 1 seconds remaining...
Blastoff! Timer reached zero.
Figure 2.1: Flowcharts illustrating execution mechanics of for loop vs. while loop.
QUESTION 3: Write a Python program to demonstrate the use of the if statement for checking
whether a given number is positive, negative, or zero.
To categorize any real number as positive, negative, or zero, we use conditional evaluation using the if-elif-else
ladder. In mathematics:
• A number x > 0 is Positive.
• A number x < 0 is Negative.
• A number x == 0 is Zero.
Complete Python Program
Code Example: Positive / Negative / Zero Classifier
# Program: Check whether a number is Positive, Negative, or Zero
# Author: Dept of AI & ML (GNIT)
def check_number_status(num):
print(f'Checking Number: {num}')
# Step 1: Check if number is strictly greater than 0
if num > 0:
print(f'Result: The number {num} is POSITIVE (+).')
# Step 2: Check if number is strictly less than 0
elif num < 0:
print(f'Result: The number {num} is NEGATIVE (-).')
# Step 3: If neither positive nor negative, it must be zero
else:
print(f'Result: The number is ZERO (0).')
print('-' * 45)
# Demonstration with test cases
check_number_status(15.8) # Positive case
check_number_status(-24) # Negative case
check_number_status(0) # Zero case
Output:
Checking Number: 15.8
Result: The number 15.8 is POSITIVE (+).
---------------------------------------------
Checking Number: -24
Result: The number -24 is NEGATIVE (-).
---------------------------------------------
Checking Number: 0
Result: The number is ZERO (0).
---------------------------------------------
Step-by-Step Logic Analysis
1. First Condition (if num > 0): Evaluates if the value is strictly positive. If True, prints 'POSITIVE' and skips the
remaining conditions.
2. Second Condition (elif num < 0): If the first condition is False, Python evaluates whether the number is
strictly negative. If True, prints 'NEGATIVE'.
3. Fallback Block (else): If the number is neither greater than zero nor less than zero, it is mathematically
guaranteed to be zero.
Figure 3.1: Decision flowchart for classifying numbers as positive, negative, or zero.
QUESTION 4: Describe the use of logical operators (NOT, AND) and the IN operator in conditional
statements with suitable examples.
In Python, logical operators and membership operators allow programmers to construct compound boolean
conditions within control statements.
1. Logical AND Operator (and)
The and operator returns True only if both operand conditions evaluate to True. If any operand is False, the
entire expression evaluates to False (short-circuit evaluation).
Code Example: Logical AND Operator
username_correct = True
password_correct = True
# Both conditions must be True
if username_correct and password_correct:
print('Access Granted: Welcome to the Student Portal!')
else:
print('Access Denied: Invalid credentials.')
Output:
Access Granted: Welcome to the Student Portal!
2. Logical NOT Operator (not)
The not operator is a unary operator that inverts the boolean value of a expression. If a condition is True, not
makes it False, and vice versa.
Code Example: Logical NOT Operator
is_maintenance_mode = False
# Condition becomes True when is_maintenance_mode is False
if not is_maintenance_mode:
print('System Status: Online and accepting user queries.')
else:
print('System Status: Under scheduled maintenance.')
Output:
System Status: Online and accepting user queries.
3. Membership Operator (in)
The in operator checks whether a specified element or substring exists inside a target sequence (such as a list,
tuple, string, or set). Returns True if found, False otherwise.
Code Example: Membership IN Operator
allowed_courses = ['AIML', 'CSE', 'ECE', 'Data Science']
student_branch = 'AIML'
if student_branch in allowed_courses:
print(f'Registration Successful for {student_branch} branch.')
else:
print(f'Branch {student_branch} is not eligible for this event.')
Output:
Registration Successful for AIML branch.
4. Combined Application (AND + NOT + IN)
Code Example: Combined Conditional Expression
# Security evaluation combining AND, NOT, and IN
blocked_ip_list = ['[Link]', '[Link]']
user_ip = '[Link]'
has_valid_token = True
is_flagged = False
# Access allowed if IP is NOT in blocked list AND token is valid AND NOT flagged
if (user_ip not in blocked_ip_list) and has_valid_token and (not is_flagged):
print('Security Check: Passed all multi-factor authentication requirements.')
else:
print('Security Check: Suspicious access attempt blocked.')
Output:
Security Check: Passed all multi-factor authentication requirements.
QUESTION 5: Explain control statements (break, continue, and pass) and analyze their effect on
loop execution.
Loop control statements alter the standard sequential execution flow of loops. They allow programmers to
interrupt iteration, skip specific steps, or reserve structural blocks.
1. The break Statement
The break statement immediately terminates the loop in which it is placed. Program execution jumps directly
to the first statement outside/after the loop body.
Code Example: break Statement
# Search algorithm using break
target = 30
numbers = [10, 20, 30, 40, 50]
for num in numbers:
print(f'Checking number: {num}')
if num == target:
print(f'Target {target} found! Exiting loop.')
break
print('Execution continued outside loop.')
Output:
Checking number: 10
Checking number: 20
Checking number: 30
Target 30 found! Exiting loop.
Execution continued outside loop.
2. The continue Statement
The continue statement skips the remaining code inside the loop for the current iteration and immediately
jumps to the next iteration test/increment step.
Code Example: continue Statement
# Print only odd numbers using continue
for n in range(1, 7):
if n % 2 == 0: # Skip even numbers
continue
print(f'Odd number processing: {n}')
Output:
Odd number processing: 1
Odd number processing: 3
Odd number processing: 5
3. The pass Statement
The pass statement is a null operation (placeholder). When executed, nothing happens. It is used to construct
syntactically required empty blocks (functions, classes, loops) without raising indentation errors.
Code Example: pass Statement
# Placeholder loop using pass
for item in [1, 2, 3]:
if item == 2:
pass # TODO: Implement complex processing logic later
print(f'Processed item: {item}')
Output:
Processed item: 1
Processed item: 2
Processed item: 3
Comparative Analysis of Loop Control Statements
Statement Action / Behavior Effect on Loop Execution Common Use Case
break Terminates loop prematurely. Exits loop completely; jumps to Early exit on finding target item
code outside loop. or error condition.
continue Skips remainder of current Jumps directly to next iteration Bypassing specific unwanted
iteration. test/increment step. elements (e.g., filtering evens).
pass Null operation (does nothing). No effect on loop execution Reserving empty blocks for
flow; continues normally. future code development.
Figure 5.1: Comparative visual flow showing the impact of break, continue, and pass on loop execution.