Starting up with Python – Part7

If statement checks if a condition is true to execute a certain block of code and if its false, it not going to execute the block of code. You can also you use it to skip certain condition. So, let's see some previous articles on the project "starting up with python."

python_logo_by_bluex_pl

16.If statement

A simple start is to create a file as follows:

#! /usr/bin/env python2
hackers="mauritius"
if hackers=="mauritius":
    print 'this is mauritius'

What it means is to pass the value 'mauritius' to the variable hackers. It will check if its same value and will eventually print what it is told to that is 'this is mauritius'. The line #! /usr/bin/env python2 is to told the file to execute from the python environment otherwise be default it will run on bash which will gave an error. Indentation is also important at line 4.

However, if the variable hackers="worldwide" and you run the script, it will run and give u a blank output since hackers=="mauritius"

17. Else and elif statement

Now, we are going to see if the 'if statement' is false what do we want it to executes. In this code, since if hackers=="worldwide",  the output is based of the else statement. Let's see this code

#! /usr/bin/env python2
hackers="mauritius"
if hackers=="worldwide":
    print 'this is mauritius'
else:
    print 'this is worldwide'

We can also use several elif statement to keep on testing the variables until the answer is received. You can change values of the variables to play around with the code. If the value "mauritius" is not found under any of the if and elif variables, it will then return the value from the else statement.

#! /usr/bin/env python2
hackers="mauritius"
if hackers=="worldwide":
    print 'this is worldwide'
elif hackers=="Mars":
    print 'this is Mars'
elif hackers=="mauritius":
    print 'this is mauritius'
else: 
    print 'file corrupted'