UNIT – II CONTROL STRUCTURES – II BSC MATHS
UNIT – II CONTROL STRUCTURES
Boolean Expressions - Selection Control - If Statement- Indentation in Python- Multi-Way
Selection -- Iterative Control- While Statement- Infinite loops- Definite vs. Indefinite Loops- Boolean
Flag. String, List and Dictionary, Manipulations Building blocks of python programs, Understanding and
using ranges.
Boolean Expressions
Definition: Boolean expressions evaluate to either True or False.
Common Operators:
o == (equal to), != (not equal to), <, >, <=, >= (comparisons).
o Logical operators: and, or, not.
o Used in control structures (like if and while statements) to make decisions based
on conditions.
M.EASWARI, MCA, NET., – ASSISTANT PROFESSOR IN CS
UNIT – II CONTROL STRUCTURES – II BSC MATHS
Selection Control
Definition: Control structures that allow for conditional execution of statements based on
a Boolean expression.
Examples:
o if, else, and elif (in Python).
Purpose: To execute certain code blocks based on whether the condition evaluates to
True or False.
M.EASWARI, MCA, NET., – ASSISTANT PROFESSOR IN CS
UNIT – II CONTROL STRUCTURES – II BSC MATHS
If Statement
Definition: A decision-making structure in Python that executes a block of code if a
given condition is True.
if condition:
# Execute this block of code if condition is True
Indentation in Python:
o Python uses indentation (spaces or tabs) to define the scope of control structures,
unlike languages that use braces {}.
o Indentation must be consistent, otherwise, it will result in an IndentationError.
M.EASWARI, MCA, NET., – ASSISTANT PROFESSOR IN CS
UNIT – II CONTROL STRUCTURES – II BSC MATHS
Multi-Way Selection
Definition: A control structure where multiple conditions are checked in sequence, and
different blocks of code are executed depending on which condition is True.
o if-elif-else structure:
if condition1:
# Code block 1
elif condition2:
# Code block 2
else:
# Code block 3
M.EASWARI, MCA, NET., – ASSISTANT PROFESSOR IN CS
UNIT – II CONTROL STRUCTURES – II BSC MATHS
M.EASWARI, MCA, NET., – ASSISTANT PROFESSOR IN CS
UNIT – II CONTROL STRUCTURES – II BSC MATHS
Iterative Control (Loops)
Definition: Used for repeating code execution based on a condition.
Iterative control allows you to repeat a block of code multiple times until a certain condition is
met. In Python, the primary ways to implement loops are the while loop and the for loop.
1. While Loop
The while loop repeats as long as a given condition evaluates to True.
Example: Using a while loop
# Example of while loop
count = 1
while count <= 5: # Loop will run as long as count is less than or equal to 5
print("Iteration:", count)
count += 1 # Increment the count by 1 after each loop
Explanation:
The loop starts with count = 1.
M.EASWARI, MCA, NET., – ASSISTANT PROFESSOR IN CS
UNIT – II CONTROL STRUCTURES – II BSC MATHS
It checks if count <= 5. If true, it prints "Iteration: 1", then increases the value of
count by 1.
The loop continues running until count exceeds 5.
Output:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
2. Infinite Loops
An infinite loop occurs when the loop condition never becomes False. This can happen if you
forget to update the loop variable or set a condition that can never be False.
Example: Infinite Loop
# Example of an infinite loop
while True:
print("This will run forever unless stopped.")
break # Breaking the infinite loop manually
Explanation:
The condition True is always true, so the loop runs indefinitely unless we manually break
out of it using break.
Output:
This will run forever unless stopped.
(Note: we will see the message printed once because the break statement stops the loop.)
3. Definite Loops with for Loop
The for loop is generally used when you know in advance how many times you want to loop.
Example: Using a for loop with a range
# Example of a for loop
for i in range(1, 6): # Loops from 1 to 5
print("Iteration:", i)
M.EASWARI, MCA, NET., – ASSISTANT PROFESSOR IN CS
UNIT – II CONTROL STRUCTURES – II BSC MATHS
Explanation:
The range(1, 6) generates numbers from 1 to 5, and the loop iterates over these
numbers.
For each iteration, the value of i is printed.
Output:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
4. Definite vs Indefinite Loops
Definite Loop: The number of iterations is known before the loop starts (e.g., using a for
loop with a known range).
Indefinite Loop: The number of iterations is not known in advance and depends on a
condition (e.g., using a while loop).
Example of Definite Loop (using for loop):
for i in range(3): # Definite loop, runs 3 times
print("Definite loop iteration", i)
Example of Indefinite Loop (using while loop):
counter = 0
while counter < 3: # Indefinite loop, continues until the condition is false
print("Indefinite loop iteration", counter)
counter += 1
Output for both examples:
Definite loop iteration 0
Definite loop iteration 1
Definite loop iteration 2
Indefinite loop iteration 0
Indefinite loop iteration 1
Indefinite loop iteration 2
5. Using a Boolean Flag
A Boolean flag is a variable that can be used to control the flow of loops, especially when you
need to break the loop based on some condition.
M.EASWARI, MCA, NET., – ASSISTANT PROFESSOR IN CS
UNIT – II CONTROL STRUCTURES – II BSC MATHS
Example of Boolean Flag in a Loop
flag = True
while flag:
response = input("Do you want to continue (y/n)? ")
if response == "n":
flag = False # Set flag to False to stop the loop
else:
print("Continuing the loop...")
Explanation:
The loop continues as long as flag is True.
If the user enters "n", flag is set to False, stopping the loop.
Summary of Iterative Control (Loops):
while loop: Repeats as long as a condition is True.
for loop: Repeats for a specific number of times (often used with range()).
Infinite loop: A loop that runs forever unless manually stopped.
Definite vs. Indefinite loops: Definite loops have a known iteration count, while
indefinite loops depend on conditions.
Boolean flag: A variable used to control the flow of the loop.
While Statement
Definition: A loop that continues executing as long as the condition remains True.
while condition:
# Repeatedly execute this block as long as condition is True
Infinite Loops:
o A while loop can create an infinite loop if the condition never becomes False.
o Example:
while True:
# Infinite loop (should have a break condition inside)
Definite vs. Indefinite Loops
Definite Loop:
M.EASWARI, MCA, NET., – ASSISTANT PROFESSOR IN CS
UNIT – II CONTROL STRUCTURES – II BSC MATHS
o The number of iterations is known beforehand (e.g., for loop using a fixed
range).
o Example:
for i in range(5):
# Executes 5 times
Indefinite Loop:
o The number of iterations is not known in advance, and depends on a condition
(e.g., while loop).
o Example:
while condition:
# Execute until the condition becomes False
Boolean Flag
Definition: A variable used to represent a Boolean condition, often used to control loops
or conditional execution.
Example:
flag = True
while flag:
# Keep looping until flag is False
if some_condition:
flag = False
A Boolean flag is a variable that is used to control the flow of a program, particularly in loops
and conditionals. The flag holds a True or False value and can be used to determine whether a
certain action or set of actions should be executed.
A Boolean flag is often used in situations where you need to break out of a loop or keep a loop
running based on a certain condition.
Example: Using a Boolean Flag in a Loop
In this example, we will use a Boolean flag to control whether the program keeps asking the user
if they want to continue or not.
# Initialize the Boolean flag
flag = True
# Start a loop that continues until the flag is False
while flag:
# Ask the user for input
user_input = input("Do you want to continue? (yes/no): ")
M.EASWARI, MCA, NET., – ASSISTANT PROFESSOR IN CS
UNIT – II CONTROL STRUCTURES – II BSC MATHS
# Check if the input is 'no'
if user_input.lower() == 'no':
flag = False # Change the flag to False, ending the loop
print("Exiting the loop.")
else:
print("Continuing the loop...")
Explanation:
The flag is initially set to True, so the loop starts.
The program asks the user whether they want to continue. If the user enters "no", the flag
is set to False, and the loop ends.
If the user enters anything other than "no", the program prints "Continuing the
loop..." and repeats the process.
Output Example:
Do you want to continue? (yes/no): yes
Continuing the loop...
Do you want to continue? (yes/no): no
Exiting the loop.
Use Case: Breaking Out of a Loop Early
A Boolean flag can also be used to break out of a loop based on certain conditions. Here’s an
example where a flag is used to stop a loop once a particular number is found.
# Example of using a Boolean flag to break a loop
numbers = [10, 15, 25, 30, 50]
flag = False # Flag to control the loop
# Check if the number 30 exists in the list
for num in numbers:
if num == 30:
flag = True # Set flag to True when 30 is found
print(f"Number {num} found!")
break # Break out of the loop once the number is found
# If the flag is still False, it means the number was not found
if not flag:
print("Number not found.")
Explanation:
The loop goes through each number in the list and checks if it's equal to 30.
If it finds 30, it sets the flag to True and breaks the loop.
If the loop completes without finding 30, it prints "Number not found."
M.EASWARI, MCA, NET., – ASSISTANT PROFESSOR IN CS
UNIT – II CONTROL STRUCTURES – II BSC MATHS
Output:
Number 30 found!
Summary of Boolean Flag:
Purpose: Boolean flags are used to control loops, conditionals, and the flow of a program
based on specific conditions.
Common Applications:
o Controlling whether a loop should continue or stop.
o Exiting loops early when a certain condition is met.
o Ensuring certain actions are performed only once or under specific conditions.
String, List, and Dictionary Manipulations
Strings:
o Used to store sequences of characters. You can manipulate strings using methods
like upper(), lower(), replace(), and slicing.
o Example:
name = "John"
print(name[0]) # J
print(name[::-1]) # nhoJ (reverse string)
Lists:
o A mutable collection to store multiple items. Manipulation includes adding,
removing, and accessing elements.
o Example:
numbers = [1, 2, 3]
numbers.append(4) # Add to the end of the list
print(numbers[0]) # Access first element (1)
Dictionaries:
o A collection of key-value pairs. Keys are unique and allow quick access to values.
o Example:
student = {"name": "Alice", "age": 20}
print(student["name"]) # Access value by key
1. String Manipulations
M.EASWARI, MCA, NET., – ASSISTANT PROFESSOR IN CS
UNIT – II CONTROL STRUCTURES – II BSC MATHS
Strings in Python are sequences of characters. You can perform various operations such as
slicing, concatenation, and using built-in methods like upper(), lower(), and replace().
Example: String Manipulations
# Example of string manipulations
sentence = "Hello, Python Programming!"
# Convert to uppercase
uppercase_sentence = sentence.upper()
print("Uppercase:", uppercase_sentence)
# Convert to lowercase
lowercase_sentence = sentence.lower()
print("Lowercase:", lowercase_sentence)
# Find a substring (substring exists or not)
substring_check = "Python" in sentence
print("Contains 'Python'?", substring_check)
# Replace a word
new_sentence = sentence.replace("Python", "Java")
print("After replacement:", new_sentence)
# String slicing
sliced_sentence = sentence[7:13] # Extract "Python"
print("Sliced string:", sliced_sentence)
Explanation:
upper() converts all characters in the string to uppercase.
lower() converts all characters in the string to lowercase.
The in operator checks if a substring exists within a string.
replace(old, new) replaces occurrences of the substring old with new.
String slicing allows extracting a portion of the string.
Output:
Uppercase: HELLO, PYTHON PROGRAMMING!
Lowercase: hello, python programming!
Contains 'Python'? True
After replacement: Hello, Java Programming!
Sliced string: Python
2. List Manipulations
Lists in Python are ordered collections that can hold items of any type. You can manipulate lists
by adding, removing, and modifying elements.
M.EASWARI, MCA, NET., – ASSISTANT PROFESSOR IN CS
UNIT – II CONTROL STRUCTURES – II BSC MATHS
Example: List Manipulations
# Example of list manipulations
fruits = ["apple", "banana", "cherry", "date"]
# Add a new item to the list
fruits.append("elderberry")
print("After appending:", fruits)
# Insert an item at a specific position
fruits.insert(1, "blueberry") # Insert "blueberry" at index 1
print("After inserting at index 1:", fruits)
# Remove an item by value
fruits.remove("banana")
print("After removing 'banana':", fruits)
# Access elements
first_fruit = fruits[0] # First element
print("First fruit:", first_fruit)
# Slice the list
sliced_fruits = fruits[1:4] # Get a sublist from index 1 to 3
print("Sliced fruits:", sliced_fruits)
# List comprehension (creating a new list with squared numbers)
numbers = [1, 2, 3, 4, 5]
squared_numbers = [x ** 2 for x in numbers]
print("Squared numbers:", squared_numbers)
Explanation:
append() adds an item to the end of the list.
insert(index, item) inserts an item at a specific index.
remove(value) removes the first occurrence of the specified value.
List slicing allows you to extract a portion of the list.
List comprehension is used to create a new list by applying an operation on each item.
Output:
After appending: ['apple', 'banana', 'cherry', 'date', 'elderberry']
After inserting at index 1: ['apple', 'blueberry', 'banana', 'cherry', 'date',
'elderberry']
After removing 'banana': ['apple', 'blueberry', 'cherry', 'date',
'elderberry']
First fruit: apple
Sliced fruits: ['blueberry', 'cherry', 'date']
Squared numbers: [1, 4, 9, 16, 25]
3. Dictionary Manipulations
Dictionaries in Python are unordered collections of key-value pairs. You can perform various
operations like adding, updating, and deleting items.
M.EASWARI, MCA, NET., – ASSISTANT PROFESSOR IN CS
UNIT – II CONTROL STRUCTURES – II BSC MATHS
Example: Dictionary Manipulations
# Example of dictionary manipulations
student = {
"name": "Alice",
"age": 22,
"major": "Computer Science"
}
# Accessing a value by key
student_name = student["name"]
print("Student's Name:", student_name)
# Add a new key-value pair
student["gpa"] = 3.9
print("After adding GPA:", student)
# Update an existing value
student["age"] = 23
print("After updating age:", student)
# Remove a key-value pair
del student["major"]
print("After removing 'major':", student)
# Check if a key exists
has_age = "age" in student
print("Does student have an 'age' key?", has_age)
# Looping through dictionary keys and values
for key, value in student.items():
print(f"{key}: {value}")
Explanation:
You can access a dictionary value using its key (e.g., student["name"]).
You can add a new key-value pair or update an existing one.
The del statement is used to remove a key-value pair.
The in operator checks if a key exists in the dictionary.
You can loop through a dictionary using the .items() method to access both keys and
values.
Output:
Student's Name: Alice
After adding GPA: {'name': 'Alice', 'age': 22, 'major': 'Computer Science',
'gpa': 3.9}
After updating age: {'name': 'Alice', 'age': 23, 'major': 'Computer Science',
'gpa': 3.9}
After removing 'major': {'name': 'Alice', 'age': 23, 'gpa': 3.9}
Does student have an 'age' key? True
name: Alice
age: 23
gpa: 3.9
M.EASWARI, MCA, NET., – ASSISTANT PROFESSOR IN CS
UNIT – II CONTROL STRUCTURES – II BSC MATHS
Summary:
String Manipulations: You can modify strings using methods like upper(), lower(),
replace(), and slicing to extract substrings.
List Manipulations: Lists are mutable and can be modified using methods like
append(), insert(), and remove(). You can also use list comprehensions for creating
new lists.
Dictionary Manipulations: Dictionaries are collections of key-value pairs that can be
accessed, updated, added, or removed using keys.
Building Blocks of Python Programs
Basic structure: A Python program is typically made up of statements, functions, and
classes.
Comments: Use # for single-line comments to improve code readability.
Indentation: Python uses indentation to define blocks of code in loops, conditionals, and
functions.
Understanding and Using Ranges
Definition: range() is a built-in function that generates a sequence of numbers, often
used in loops.
o Syntax: range(start, stop, step)
o Example:
for i in range(1, 10, 2):
print(i) # Outputs 1, 3, 5, 7, 9
M.EASWARI, MCA, NET., – ASSISTANT PROFESSOR IN CS