What is a Control Structure in Python
What is a Control Structure in Python
What is a Control Structure in Python
Control structures in Python are fundamental building blocks that allow the program
to make decisions, repeat actions, or control the flow of execution based on
conditions.
repetition structures, like for or while loops, allow code to run multiple times until
a condition is met.
1. if Statement
The if statement is the simplest selection structure in Python. It evaluates a condition and
executes the associated block of code only if the condition is True. If the condition is False,
the program skips the if block and continues with the next statement.
Syntax:
if condition:
Example:
number = int(input("Enter a number: "))
if number > 0:
print("The number is positive.")
if-else Statement
The if-else statement allows the program to handle two possible outcomes
of a condition. If the condition is True, the code inside the if block executes;
otherwise, the code inside the else block runs.
Syntax:
if condition:
# Code to execute if the condition is True
else:
# Code to execute if the condition is False
Example
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
if-elif-else Statement
The if-elif-else statement is used when there are multiple conditions to check.
The elif (short for "else if") is checked only if the previous conditions are False. The else
block, if present, executes only when all conditions are False.
Syntax:
if condition1:
# Code to execute if condition1 is True
elif condition2:
# Code to execute if condition2 is True
elif condition3:
# Code to execute if condition3 is True
else:
# Code to execute if all conditions are False
Example :
marks = int(input("Enter your marks: "))
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 50:
print("Grade: C")
else:
print("Grade: F")