Read more
Alternative or Branching Statement
Introduction
Programs may contain set of statements. Th ese statements are the executable segments that yield the result. In general, statements are executed sequentially, that is the statements are executed one aft er another. Th ere may be situations in our real life programming where we need to skip a segment or set of statements and execute another segment based on the test of a condition. Th is is called alternative or branching. Also, we may need to execute a set of statements multiple times, called iteration or looping. In this chapter we are to focus on the various control structures in Python, their syntax and learn how to develop the programs using them.
Programming in Python
In Python, programs can be written in two ways namely Interactive mode and Script mode. The Interactive mode allows us to write codes in Python command prompt (>>>) whereas in script mode programs can be written and stored as separate file with the extension .py and executed. Script mode is used to create and edit python source file.
Python provides the following types of alternative or branching statements
i. Simple if statement
ii. if..else statement
iii. if..elif statement
In our day-to-day life we need to take various decisions and choose an alternate path to achieve our goal. May be we would have taken an alternate route to reach our destination when we find the usual road by which we travel is blocked. This type of decision making is what we are to learn through alternative or branching statement. Checking whether the given number is positive or negative, even or odd can all be done using alternative or branching statement.
i. Simple if statement
Simple if is the simplest of all decision making statements. Condition should be in the form of relational or logical expression.
Syntax:
Example:
Output 1:
Output 2:
ii. if..else statement
The if .. else statement provides control to check the true block as well as the false block. Following is the syntax of ‘if..else’ statement.
Syntax:
if <condition>:
statements-block 1
else:
statements-block 2
Example:
Output 1:
Output 2:
Syntax:
variable = variable1 if condition else variable 2
iii. if..elif statement
When we need to construct a chain of if statement(s) then ‘elif ’ clause can be used instead of ‘else’.
Syntax:
if<condition-1> :
statements-block 1
elif <condition-2>:
statements-block 2
else: statements-block n
In the syntax of if..elif..else mentioned above, condition-1 is tested if it is true then statements-block1 is executed, otherwise the control checks condition-2, if it is true statementsblock2 is executed and even if it fails statements-block n mentioned in else part is executed.
‘elif ’ clause combines if..else-if..else statements to one if..elif…else. ‘elif ’ can be considered to be abbreviation of ‘else if ’. In an ‘if ’ statement there is no limit of ‘elif ’ clause that can be used, but an ‘else’ clause if used should be placed at the end.
0 Reviews