Conditional Statements
Conditional Statements
Conditional Statements:
Conditional control statements are also called branching or selection statements that
execute one group of instructions depending on the outcome of a decision.
1. if statements
2. if...else statements
3. if...elif...else statements
4. Nested if statements
1
If statements:
The if statement is called a conditional statement. The if keyword performs the basic
conditional test that evaluates a given expression for a Boolean value of True or False.
The condition/expression must be followed by a : colon, then statements to be executed.
if condition/expression :
statement 1
.....
statement N
if condition is True, then indented statements will be executed
2
if statements using comparison operators:
if a==b :
print ("a is equal to b")
if a<b :
print ("a is less than b")
if a >=b :
print ("a is greater than or equal to b")
if (a != b) :
print ("a and b are not equal")
3
If…else statement:
if…else statement also tests the specified condition/expression. If the condition is True, the commands
in the if part of the block are executed. If the condition is False, the commands under else part will be
executed .
The syntax of the if…else:
if condition/expression :
statement 1
.....
statement N
else:
statement 2
.....
statement N
4
If…elif…else statement:
The if …elif statement allows you to check multiple expressions and executes a block of code
as soon as one of the conditions evaluates to TRUE.
5
Nested if statements:
One condition can also be nested within another. The nested if…else statement allows you to check for
multiple test expressions and execute different codes for more than two conditions.
The syntax of the nested if construct is:
outer if
if Condition/expression :
statement 1
.....
Inner if
if Condition/expression :
statement 1
.....
else:
statement 1
.....
.....
statement N
else:
statement 1
6
.....