Python                                                          Home : www.sharetechnote.com

 

 

 

 

Python - Condition Statement 

 

Following is standards format of Python if statement. Be careful that you should not miss ':' at the end of the condition and also be careful that you are using proper indentation. Check the examples in this page.

 

NOTE 1 : All the examples in this page are written in Python 3.x. It may not work if you use Pyton 2.x

NOTE 2 : All the examples in this page are assumed to be written/run on Windows 7 unless specifically mentioned. You MAY (or may not) need to modify the syntax a little bit if you are running on other operating system.

    < Type 1 >  --------- see Example 1, Example 2

     

    if condition :

          indentedStatementBlock

     

     

    < Type 2 >

     

    if condition :

          indentedStatementBlock

    else :

          indentedStatementBlock

     

     

    < Type 3 > --------- see Example 3

     

    if condition1 :

          indentedStatementBlock

    elif condition2 :

          indentedStatementBlock

    elif condition3 :

          indentedStatementBlock

    elif condition4 :

          indentedStatementBlock

    elif condition5 :

          indentedStatementBlock

    else :

          indentedStatementBlock

For the if statement in any language, what you need to know first is how they represent 'Comparison' and 'Logical Operation/Binary Operaton'.

 

Followings are the list of comparison operators in if statement

    == Equal  
    != Not Equal  
    <> Not Equal  
    > Greater than  
    < Less than  
    >= Greater than or equal  
    <= Less than or equal  

 

Followings are the list of logical operators used in if statement

    and Logical AND Example 3
    or Logical OR  
    not Logical NOT  

 

Followings are some examples for if statement.

    < Example 1 >

     

    check = 0.4

     

    if check > 0.5 :

        print("Run A...")

    print("Run B...")

    print("Run C...")

     

    Result : -----------------------------------

    Run B...

    Run C...

     

     

    < Example 2 >

     

    check = 0.4

     

    if check > 0.5 :

        print("Run A...")

        print("Run B...")

    print("Run C...")

     

    Result : -----------------------------------

    Run C...

     

     

    < Example 3 >

     

    score = 75

     

    if score >= 90 :

       print("Grade A")

    elif (score < 90) and (score >= 80) :

       print("Grade B")

    elif (score < 80) and (score >= 70) :

       print("Grade C")

    elif (score < 70) and (score >= 60) :

       print("Grade D")

    else :

       print("Grade F")

     

    Result : -----------------------------------

    Grade C