VMware ESXi and vSphere Cluster Management
Python if...else Statement
Learn how Python if...else statements make two-way decisions using Boolean conditions, comparisons, user input, thresholds, and modulo.
What the Python if...else Statement Does
An if...else statement lets a program choose between two actions. It creates two possible paths, called branches, based on a condition.
An if statement runs an indented block when its condition is True. The else clause runs its alternative block when that condition is False. For one if...else decision, exactly one branch runs.
| Condition result | Code block executed | Code block skipped |
|---|---|---|
True | if block | else block |
False | else block | if block |
Basic Syntax
The condition is written after if. A colon ends the line, and the statements controlled by the condition are indented. The else keyword is aligned with if, also ends with a colon, and has its own indented block. Unlike if, else has no condition.
if condition:
statements_when_true
else:
statements_when_falseFor example:
temperature = 30
if temperature >= 25:
print("It is warm.")
else:
print("It is cool.")Because temperature >= 25 is True, Python prints It is warm. and skips the else block. If the temperature were 20, Python would skip the if block and print It is cool..
Conditions and Boolean Results
A condition is an expression used to control program flow. It produces a Boolean value: either True or False.
Comparison operators are commonly used to create conditions. For example, score >= 60 asks whether score is at least 60. The equality operator == asks whether two values are equal. It is different from the single equals sign, =, which assigns a value to a variable.
score = 75
if score >= 60:
print("Pass")
else:
print("Try again")The greater-than-or-equal-to operator, >=, includes the boundary value. Therefore, 60 >= 60 is True.
Indentation Defines Each Branch
Python uses leading whitespace called indentation to define code blocks. Every statement belonging to the if branch must be indented consistently. The statements belonging to the else branch must also be indented consistently.
logged_in = True
if logged_in:
print("Welcome.")
print("Your dashboard is ready.")
else:
print("Please sign in.")
print("This runs after the conditional structure.")The first two print() calls are inside the if block. The third is inside the else block. The final print() is aligned with if and else, so it occurs after the conditional structure regardless of which branch ran.
Use consistent indentation, commonly four spaces. Incorrect indentation can cause a syntax error or place a statement in the wrong branch. A statement accidentally moved outside both blocks can also cause both messages to print.
Control-Flow Behavior
Python evaluates the if condition first. If it is True, Python runs the if block and skips the else block. If it is False, Python skips the if block and runs the else block.
The else clause is not evaluated as an independent second condition. It simply means “when the preceding if condition was false.”
Using User Input in a Decision
The input() function reads text entered by a user and returns that text as a string. If the input represents a whole number, use int() to convert it into an integer before making a numeric comparison.
name = input("Enter your name: ")
age = int(input("Enter your age: "))Without int(), the value stored in age would be text rather than an integer. Comparing that text with a number can produce a type-related error or unexpected behavior.
Example: Age Eligibility Check
This program checks whether an entered age meets a minimum age of 21. It uses >= so that age 21 qualifies.
name = input("Enter your name: ")
age = int(input("Enter your age: "))
if age >= 21:
print(name, "meets the age requirement.")
else:
print(name, "does not meet the age requirement.")For the input Mark and 19, the condition 19 >= 21 is False, so the else message runs:
Mark does not meet the age requirement.For the input Alex and 21, the condition 21 >= 21 is True, so the if message runs:
Alex meets the age requirement.Why the Boundary Operator Matters
If age 21 should qualify, use >= 21. Using > 21 would exclude 21 because it tests for values strictly greater than 21.
Example: Even-or-Odd Number Checker
The modulo operator, written as %, returns the remainder after division. When an integer is divided by 2, a remainder of zero means the number is even.
number = int(input("Enter an integer: "))
if number % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")The condition number % 2 == 0 has two operations. First, number % 2 calculates the remainder after division by 2. Then, == 0 checks whether that remainder equals zero.
For input 100, 100 % 2 is 0, so the if branch runs:
The number is even.For input 5, the remainder is 1, so the condition is False and the else branch runs:
The number is odd.Conditions Used in These Examples
| Expression | Meaning | Example result |
|---|---|---|
age >= 21 | Checks whether age meets or exceeds the threshold | True when age is 21 |
number % 2 == 0 | Checks whether a number divides evenly by 2 | True when number is 100 |
Common Patterns
Two-Way Conditional Execution
if condition:
statements_when_true
else:
statements_when_falseConverting Numeric Input
value = int(input("Enter a number: "))Testing Whether an Integer Is Even
number % 2 == 0Troubleshooting
- Numeric comparison causes a type-related error:
input()returns a string. Convert the value withint()before comparing it with an integer. - Indentation error or wrong branch behavior: Indent every statement in a branch consistently, and align
elsewithif. - The else message appears at the threshold: The comparison may use
>instead of>=. Use>=when the threshold itself qualifies. - The even test never succeeds: Write the complete condition as
number % 2 == 0. The modulo result must be compared with zero using==. - Both branch messages print: Check that the true message is indented inside the
ifblock and the false message is indented inside theelseblock.
Key Terms
- if statement: A control-flow statement that runs an indented block when a condition is true.
- else clause: The alternative branch that runs when the preceding
ifcondition is false. - condition: An expression evaluated as
TrueorFalseto control program flow. - Boolean: A truth value represented by
TrueorFalse. - branch: One possible path of execution in a conditional statement.
- indentation: Leading whitespace that defines Python code blocks.
- comparison operator: An operator such as
>=or==used to compare values. - greater than or equal to (
>=): Tests whether the left value is at least as large as the right value. - equality operator (
==): Tests whether two values are equal. - modulo operator (
%): Returns the remainder after division. input(): A function that reads user input as a string.int(): A conversion function that changes suitable text into an integer.
Exam-Ready Summary
- Write the condition after
ifand finish the line with a colon. - Indent the statements that belong to the
ifbranch. - Align
elsewithif;elsehas no condition. - Indent the statements that belong to the
elsebranch. - Exactly one branch of a single
if...elsestatement runs. - Use
int(input(...))when numeric input must be compared as an integer. - Use
>=when a threshold includes its boundary. - Use
number % 2 == 0to identify even integers.