Explained
Introduction
In programming, a program rarely runs line by line without making decisions or
repeating actions. Real programs must respond to conditions and perform tasks
multiple times. This is where control structures and loops become essential.
Control structures allow a program to decide which instructions to execute
based on certain conditions. Loops allow a program to repeat a block of code
until a specific condition is met.
Understanding these concepts is crucial because they are used in almost every
program, from simple scripts to complex software systems.
This document explains Python control structures and loops with clear
explanations and practical examples.
Control Structures in Python
Control structures determine the flow of execution in a program. Instead of
executing every line sequentially, the program can make decisions.
Python mainly uses the following decision structures:
• if statement
• if–else statement
• if–elif–else statement
• nested if statements
The if Statement
The if statement executes a block of code only if a specific condition is true.
, Syntax
if condition:
statement
If the condition evaluates to true, the program executes the statement.
Example
temperature = 30
if temperature > 25:
print("It is a hot day")
Output
It is a hot day
Explanation:
The program checks whether the temperature is greater than 25. Since the
condition is true, the message is printed.
The if–else Statement
The if–else statement allows a program to choose between two actions
depending on the condition.
Syntax
if condition:
statement1
else:
statement2
Example
age = 17
if age >= 18:
print("You are eligible to vote")
else:
print("You are not eligible to vote")