Control structures allow you to dictate the flow of your program. They enable your code to make decisions, repeat tasks, and manage complex logic. Mastering these constructs is essential for building dynamic and efficient Python applications.
Conditional statements let your program choose different paths based on boolean expressions (True/False).
if StatementConcept:
Evaluates a condition; if the condition is True, the indented block below it executes.
Syntax:
if condition:
# code block executed when condition is True
Example:
temperature = 30
if temperature > 25:
print("It's a hot day!")
if-else StatementConcept:
Provides an alternative block of code if the condition is False.
Syntax:
if condition:
# code block if condition is True
else:
# code block if condition is False
Example:
temperature = 20
if temperature > 25:
print("It's a hot day!")
else:
print("It's not that hot.")
if-elif-else LadderConcept:
Checks multiple conditions in order. Only the first true condition's block is executed.
Syntax:
if condition1:
# code block for condition1
elif condition2:
# code block for condition2
else:
# code block if none of the above conditions are True
Example:
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: D or below")
Loops are used to repeat code execution. Python provides several types of loops that you can use depending on your needs.
while Loop