Python Introduction | Statements | Conditional Branching with if

if Statements

Control statements can be divided into conditional branches and loops. A conditional branch selects processing according to a condition. The basic form is the if statement.

Basic if Form (1)

if condition:
    processing when the condition is true

Basic if Form (2)

if condition:
    processing when the condition is true
else:
    processing when the condition is false

Write a condition after if, followed by a colon (:). The indented block runs when the condition is true.

To run different processing when the condition is false, return to the indentation level of if, write else:, and add another indented block.

Python also provides elif: for checking additional conditions, but begin by understanding if and else.

The following example determines whether a number is even or odd.

x = 1234
check = x % 2
if check == 0:
    print(str(x) + " is even.")
else:
    print(str(x) + " is odd.")
print("....end.")

Output:

% python3 if.py
1234 is even.
....end.

Writing Conditions

Conditions are essential to using if statements.

Numeric Comparisons

Comparison expressions check relationships between two values.

Operator Meaning
value1 == value2 The values are equal.
value1 != value2 The values are not equal.
value1 < value2 value1 is less than value2.
value1 <= value2 value1 is less than or equal to value2.
value1 > value2 value1 is greater than value2.
value1 >= value2 value1 is greater than or equal to value2.

Boolean Values and Variables

A Boolean value is either True or False. An if statement runs its indented block when its condition is True. When the condition is False, it skips the block or runs the else block.

Summary

Comparison expressions and Boolean values are closely related. A comparison returns a Boolean value. Ultimately, every if condition is evaluated as either True or False.