Control Flows From Python

     As Other Languages Python also has control flow Statements. They are as follows:-

if Statement

     It used to check condition according to it control program flow.
Syntax:
    if condition:
        statement1
        statement2
        ...

if..else Statement

     It is used control flow according to condition, If condition evaluates to True, It will execute if block, else block otherwise.
Syntax:
    if condition:
        statement1
        statement2
        ...
    else:
        statement1
        statement2
        ...
Example:
>>> a = 3
>>> b = 9
>>> if b > a:
...     print "B is Max"
... else:
...     print "A is Max"
... 
B is Max

if..elif..else Statement

     Python Doesn't supports switch...case like C or Java, it is replaced with if - elif - else. It first checks if condition if it evaluates true it executes statements enclosed within otherwise it goes to elif, checks condition if it is true it executes statements in it's block otherwise it executes else block statements.
Syntax:
    if condition:
        statement1
        statement2
        ...
    elif condition:
        statement1
        statement2
    else:
        statement1
        statement2
        ...
Example:
     We slightly modify above program. As follows,
>>> a = 3
>>> b = 9
>>> b = 7
>>> if a > b and a > c:
...     print "A is Max"
... elif b > c:
...     print "B is Max"
... else:
...     print "C is Max"
... 
B is Max
     That's it. We Will See Next Loops, Keep Following.

Comments

Popular posts from this blog

Getting Started With Python

Python List

The dir Function