Conditional Statement – If… Else
Conditional Statements (Decision Making)
The basic decision statements in the computer are selection structure. The decision is described to computer as a conditional statement that can be answered True or False Python language provides the following conditional (decision making) statements.
- If statement
- If….. else statement
- If……elif…..else statement
- Nested if …. else statement
if condition / test expression : statement(s)
: at the end of if indicates continuation of statement
Statement(s) belonging to if are indented to indicate block of code to be executed, if condition is satisfied
Indentation is used to form a block of statement in Python. All statement at same indent level are considered in same block.
Usually four spaces are used to start a new block, but it can be any number of spaces or even tab(s) may be used.
First unindented statement marks end of block.
if condition / test expression :
statement(s)
else :
statement(s)
if condition / test expression :
statement(s)
elif condition / test expression :
statement(s)
:
:
else :
statement(s)
There will only be one else in an if statement.
Nested condition – An if statement can be placed inside if, just like any other
statement.
There can be chain of elif statement in one if.
Iterative construct
Python provide two types of looping construct
while
for
While loop
while test expression / condition :
statement(s)
[else:
statement(s)] optional
• When test expression written in while returns false then the else statement if present, gets executed.
For loop
for var(iteratorVar) in sequence :
statement(s)
[ else :
statement(s) ] optional
• Sequence is any sequence data type viz list, tuple, dictionary.
• Else statement, if given, will execute immediately after for block, always.
• Apart from sequence type, for loop can iterate over range() function, file, etc.
• range function
➢ range(start, stop, step)
➢ Generates a sequence of numbers beginning from start till stop-1
➢ Step signifies the interval between the terms
➢ We can have negative value for step when start> stop
➢ First and third arguments are optional
➢ Default value of start is 0 and step is -1
Unconditional transfer of control
break statement
Transfers control out of the loop
continue statement
Skips current iteration in the loop
pass statement
Valid executable statement. Used to replace the section of code to be defined later