Understanding Python Conditional Statements: If, Else, and Elif
Conditional statements in Python allow programs to make decisions based on certain conditions. Python provides several logical operators commonly used in mathematics to compare values:
- Equals:
a == b
- Not Equals:
a != b
- Less than:
a < b
- Less than or equal to:
a <= b
- Greater than:
a > b
- Greater than or equal to:
a >= b
Basic If Statement
The if
keyword initiates a conditional block. Here’s an example:
a = 33
b = 200
if b > a:
print("b is greater than a")
In this case, since 200 is greater than 33, the condition is true and the message is printed.
Indentation in Python
Python uses indentation to define blocks of code. Unlike other programming languages that use braces, Python relies on whitespace to determine scope. Incorrect indentation leads to syntax errors:
if b > a:
print("b is greater than a") # This will raise an error
Using Elif
elif
(short for “else if”) allows additional conditions to be checked if the initial if
is false.
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
Using Else
The else
block executes if none of the preceding conditions are true:
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Else Without Elif
else
can also be used independently when no elif
is necessary:
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Short-Hand If
Python supports a short-hand version of the if
statement for single-line execution:
if a > b: print("a is greater than b")
Short-Hand If…Else (Ternary Operator)
You can use a one-line if...else
expression, known as a ternary operator:
a = 2
b = 330
print("A") if a > b else print("B")
Multiple conditions can also be nested in a single line:
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")
Logical Operators
And Operator
The and
keyword checks if both conditions are true:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Or Operator
The or
keyword checks if at least one condition is true:
if a > b or a > c:
print("At least one of the conditions is True")
Not Operator
The not
keyword reverses the result of a condition:
a = 33
b = 200
if not a > b:
print("a is NOT greater than b")
Nested If Statements
Python supports nesting of if
statements within each other:
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
The Pass Statement
When you want to define an if
block with no action (as a placeholder), use the pass
keyword:
a = 33
b = 200
if b > a:
pass
Learn More with Devyra
For a deeper understanding of Python’s control structures and logical operations, continue exploring on Devyra, your trusted learning platform for programming and development tutorials.