Python : Crash Course Part 9 – Statements

Python uses IF, ELIF and ELSE statements for processing results based on the condition passed within them. The condition is then followed by colon to pass/perform the desired action.

In [1]:if 1<2:
            print('perform this action')
       perform this action

Note that we are performing a print action in python and there is no python Out prompt here on the jupyter notebook.

Lets try some more examples, I have coded the operation statement in the same line, but as a best practice and easier understanding you can code the operation in the second line in your juypter notebook. You will notice the indentation happening automatically in jupyter notebook after pressing the enter key after the colon symbol.

In [2]:if 1<2 : x=2+2
In [3]:x
Out[4]:4

Lets now use multiple IF conditions and see how it works.

In [5]: if 1==1 : 
                 print ('First') 
           else : 
                 print ('Last')
Out[6]: First

If the condition is True ( 1==1) then the code will print First else it will print Last.

In [7]:if 1 < 2  : 
                print ('First') 
       elif 2==2 : 
                print ('Second')
       elif 3==3 :
                print ('Third')
       else :
                print ('Last')
Out[8]: Second

Notice what happened above, even though 3==3, it did not print Third as python stops the iteration when the first condition is true or is satisfied. In our example 2==2, which is true and hence Second was printed.

Try out some more examples using these statements and let me know if you found it easy to absorb.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s