Python Control Structures
Agenda
• Control Structures – Overview
• Conditional Statement
• If Statement
• If-Else Statement
• If-Elif-Else-Statement
• Loops
• For Loop
• While Loop
• Loop Controls
• Break
• Continue
• Else After Loops
Control Structures
• Definition
• Control structures are programming constructs that manage the flow of execution through a
script based on conditions or repetition. They are essential for creating dynamic and interactive
applications.
• Types of Control Structures:
• Conditional Statements: Direct the program to execute certain sections of code depending on
whether a specific condition or set of conditions are met.
• Loops: Enable the execution of a block of code repeatedly, either a predetermined number of
times or until a certain condition changes.
• Purpose:
• Used for handling decisions within programs, automating tasks, and managing complex data
flows.
Conditional Statements
• Purpose:
• Conditional statements allow Python programs to execute certain actions based on whether
specific conditions are true or false.
• Types:
• if: The most basic form of decision making, which executes a block of code only if a specified
condition is true.
• if-else: Extends the if statement by defining an alternative action if the condition is false.
• if-elif-else: Handles multiple conditions by executing different blocks of code for each
condition, with an optional else for any cases not covered by the elif conditions.
• Usage:
• Direct program flow based on user inputs, computational results, or external data.
• Implement feature toggles, error handling, and data validation.
If Statement
Syntax:
• Purpose:
• The if statement is the simplest form of
conditional control in Python, used to
execute a block of code only if a specified
condition is true.
Example:
• Functionality:
• Evaluates a condition (which can involve
logical, comparison, or identity operators).
• Executes the indented block of code
immediately following the statement if the
condition evaluates to True.
If-Else Statement
Syntax:
• Purpose:
• The if-else statement in Python provides a
way to execute one block of code if a
condition is true, and another block if it is
false.
• Functionality: Example:
• Decides between two courses of action based
on whether a condition evaluates to True or
False.
• Enhances control by covering both
possibilities of a condition, ensuring that a
code path is always executed.
Logical Operators with If..Else
We can combine multiple conditions using logical operators such as and, or,
and not.
age = 25
exp = 10
# Using '>' operator & 'and' with if-else
if age > 23 and exp > 8:
print("Eligible.")
else:
print("Not eligible.")
Output
Eligible.
# Example 1:
Basic usage with two conditions
age = 17
if age < 18 or age > 65:
print("You are either a minor or a senior citizen.")
else:
print("You are an adult of working age.")
# Example 2:
More complex conditions
day = "Sunday“
is_holiday = True
if day == "Saturday" or day == "Sunday" or is_holiday:
print("It's a weekend or a holiday!")
else:
print("It's a regular weekday.")
is_logged_in = False
if not is_logged_in:
print("Please log in to continue.")
else:
print("Welcome back!")
O/P
Please log in to continue
If-Elif-Else-Statement
Syntax:
• Purpose:
• The if-elif-else statement is used for
multiple conditional checks,
allowing for more than two possible
execution paths.
• Functionality: Example:
• Executes the first true condition it
encounters.
• If no conditions are true, the else
block is executed, providing a
default action.
Loops
• Purpose:
• Loops in Python enable the execution of a block of code repeatedly under specific conditions,
facilitating the automation of repetitive tasks and efficient data processing.
• Types:
• for Loop: Iterates over a sequence (like lists, tuples, strings) or other iterable objects.
• while Loop: Continues to execute a block of code as long as a specified condition remains true.
• Usage:
• Automate and simplify tasks that need to be repeated, such as data entry, file processing, or batch
processing.
• Implement loops in event-driven programming like games or user interfaces where certain conditions
trigger specific actions.
• Facilitate complex calculations that require iterative approaches, such as in numerical methods or
algorithmic processes.
For Loop
Syntax:
• Purpose:
• The for loop is designed to iterate over a
sequence (such as a list, tuple, string) or
any other iterable, allowing for precise
control over the execution of a block of
code. Example:
• Functionality:
• Iterates through each element in the iterable
one by one.
• Automatically handles the iteration process
without needing to manually update loop
counters or manage loop conditions.
While Loop
• Purpose: Syntax:
• The while loop allows code to be executed
repeatedly as long as a specified condition
remains true, providing a flexible tool for
handling operations where the number of Example:
iterations isn't predetermined.
• Functionality:
• Continues to run the code block contained
within it until the condition evaluates to
False.
• Frequently used in situations where the
loop must run until a particular state is
reached or an external condition is met.
Loop Controls
• Purpose:
• Loop controls modify the behavior of loops during their execution, providing more flexibility
in controlling the flow based on specific conditions.
• Functionality:
• break is used to exit a loop when a specific external condition is triggered.
• continue allows the loop to skip certain iterations that don't meet specific conditions.
• else adds additional logic that runs only when the loop concludes naturally, enhancing the logic
for scenarios involving searches or condition checks.
• Key Benefit:
• These controls provide nuanced management of loop execution, enabling more precise and
efficient program behavior in various looping contexts.
Types of Loop Controls
break: Exits the loop immediately, regardless of the loop condition.
Example:
continue: Skips the current iteration and proceeds to the next cycle of the loop.
Example:
else: Executes a block of code once after the loop completes, but only if the loop was not terminated
by a break.
Example:
Practice Questions
• Conditional Statements
• Temperature Advice: Write a Python script that takes a temperature value as input and prints "It's
a hot day" if the temperature is over 30 degrees, "It's a nice day" if it's between 20 and 30 degrees,
and "It's cold" if it's below 20 degrees.
• Loops
• Sum of Numbers: Create a Python program using a for loop that asks the user to input 5 numbers
and prints the sum of those numbers.
• Loop Controls
• Positive Number Collector: Write a program that uses a while loop to collect numbers from the
user until they enter '0'. Use a continue statement to skip and not count any negative numbers,
printing out the sum of only positive numbers entered once the loop ends.