Step 1: The if Statement
The if statement is the basic form of control flow in Python. It allows for conditional execution of a statement or group of statements based on the value of an expression.
Step 2: The Condition
After the if keyword, you provide a condition. This condition is an expression that can be evaluated as True or False. Python will execute the body of the if only when the condition is True.
Step 3: The Body
If the condition is True, Python executes the block of code that's indented under the if statement. If the condition is False, the code block under the if is skipped.
Step 4: The else and elif Statements (Optional)
else: You can follow an if statement with an optional else block which is executed when the if condition is False.
elif (else if): It's used for multiple conditions to provide additional checks.
Example: Choosing a Path Based on Age
Imagine you're writing a program that suggests activities based on a person's age.
age = 18 # Let's assume the person is 18 years old
if age < 13:
print("You can play in the kids' area.")
elif age < 18:
print("You can join the teenagers' group.")
else:
print("Welcome to the adults' zone.")
Explanation:
First condition (if age < 13): Python checks if age is less than 13. If True, it would print "You can play in the kids' area." Since our age is 18, this condition is False, so Python skips this block.
Second condition (elif age < 18): Next, Python checks if age is less than 18. Again, since our age is 18, this condition is also False, so Python skips this block too.
Else: Since none of the previous conditions were True, Python executes the code in the else block, printing "Welcome to the adults' zone.