Decision control is fundamental to programming, allowing your code to dynamically respond to different situations. Python provides powerful tools for implementing decision control, primarily through the use of if
, elif
(else if), and else
statements. This tutorial will guide you through these essential control structures.
Table of Contents
- The
if
Statement - The
if...else
Statement - The
if...elif...else
Statement - Nested
if
Statements - Conditional Expressions (Ternary Operator)
1. The if
Statement
The simplest form of decision control is the if
statement. It executes a block of code only when a specified condition evaluates to True
.
x = 10
if x > 5:
print("x is greater than 5")
In this example, the condition x > 5
is checked. Since it’s True
, the print()
function is executed. If x
were less than or equal to 5, the print()
statement would be skipped.
2. The if...else
Statement
The if...else
statement allows you to execute one block of code if a condition is True
and a different block if it’s False
.
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
If x
is greater than 5, the first print()
statement runs. Otherwise, the else
block is executed.
3. The if...elif...else
Statement
For situations with multiple conditions, the if...elif...else
statement is invaluable. It checks conditions sequentially until a True
condition is encountered. The corresponding code block is executed, and the rest are skipped. The optional else
block is executed only if none of the preceding conditions are True
.
x = 7
if x > 10:
print("x is greater than 10")
elif x > 5:
print("x is greater than 5")
elif x > 0:
print("x is greater than 0")
else:
print("x is not greater than 0")
Here, the conditions are evaluated in order. Because x > 5
is True
, “x is greater than 5” is printed, and the remaining checks are bypassed.
4. Nested if
Statements
You can embed if
, elif
, and else
statements within other if
statements to create nested structures for complex decision-making.
x = 10
y = 5
if x > 5:
if y < 10:
print("x is greater than 5 and y is less than 10")
else:
print("x is greater than 5 but y is not less than 10")
else:
print("x is not greater than 5")
The inner if
statement only executes if the outer if
condition is True
. Maintain clear indentation for readability and correct execution.
5. Conditional Expressions (Ternary Operator)
Python offers a concise way to express simple if...else
logic using conditional expressions. This is particularly useful for assigning values based on a condition.
x = 10
message = "x is greater than 5" if x > 5 else "x is not greater than 5"
print(message)
This single line achieves the same result as a longer if...else
block. Note that conditional expressions are best suited for relatively straightforward scenarios.
This tutorial provides a solid foundation in Python’s decision control mechanisms. Practice and experimentation are key to mastering these concepts and building robust, dynamic programs.