Learn to control the flow of a Python program using if
, if...else
and if...elseif
statements. These statements are called conditional statements and help in writing boolean conditions that generally compare two variables or expressions.
a = 0
if a > 0:
print("a is greater than 0")
elif a < 0:
print("a is less than 0")
else:
print("a is 0")
1. Using if
An “if statement” is written by using the if
keyword.
a = 10
b = 20
if b > a:
print("b is greater than a") #Prints this message
1.1. Indentation
Python uses indentation to define the scope in the code. (Similar to curly brackets in Java). So be mindful of indentation while writing if else statements in Python.
1.2. Combining Multiple Expressions with Logical Operators
We can combine multiple expressions in the if statement using logical operators. Python provides two logical operators:
and
: Logical ANDor
: Logical OR
The following condition tests that b and c, both, are greater than a.
a = 10
b = 20
c = 30
if b > a and c > a:
print("b and c are greater than a") #Prints this message
1.3. Shorthand if
Whenever there is only a single statement to be executed inside the if block then shorthand if statement can be used. The statement can be put on the same line as the if statement.
if b > a: print("b is greater than a")
2. Using if … else
The if statement is executed only if a certain condition is True. If the condition is False, then else
statement is executed if provided in the program.
a = 100
b = 20
if b > a:
print("b is greater than a")
else:
print("b is smaller than a") #Prints this message
We can write the shorthand if-else statement similar to the shorthand if statement we saw in the first section. Its syntax is:
statement_when_True if condition else statement_when_False
Let us rewrite the previous example in shorthand if-else statement.
a = 100
b = 20
print("b is greater than a") if (b > a) else print("b is smaller than a") #Prints 'b is smaller than a'
3. Using elif
The elif
statement is short form of else if
statements in other programming languages such as Java. A Elif
statement containing a conditional expression will be executed if its previous conditional expression is evaluated as False.
In this example, x is greater than y so the if
statement will be False. So, the program will execute the elif
statement which is True.
x = 100
y = 200
z = 300
if y < x:
print('y is less than x')
elif y < z:
print('y is less than z') #Prints this message
4. Nested if .. else
We can have if
statements inside another if
statements, this is called nested if
statements. We can compile these statements up to any level.
a = 20
if a > 10:
print("a is greater than 10") #Prints this message
if a < 20:
print("a is less than 20")
else:
print("a is equal to 20") #Prints this message
5. Empty if
A Python program cannot have an empty if
statement. If for any reason, you must provide an empty if
statement then use the pass
keyword.
x = 100
y = 200
if x < y:
pass
Happy Learning !!
Leave a Reply