Python Else If: Using Conditional Statements
Computers do not understand English or Spanish or any other native human language. To tell a computer to perform specific actions to completing a task reliably, and sometimes even repeatedly, it needs to have instructions; which are somewhat similar in nature to the recipes used in a kitchen for making delicious food, and a scrumptious meal.
These instructions are what we call a programming language. So if you are curious to learn about how to make your computer say your name out loud when you login everyday morning, or have your computer balance your monthly accounts, or pull a file from the Internet comic strip every day, you have come to the right place.
You may be curious to learn a programming Language. As far as programming languages go, Python is one of the best general purpose languages you can start with and learn to instruct a computer. In this blog post you will learn to write simple Python programs using conditional logic and if-else statements.
Introduction to Python
Python is a object oriented, multi-paradigm programming language. While it is vast and complex, enabling platforms like Instagram, and Google operate parts of their websites behind the scenes, Python can be simple and it’s easy to get started.
You can download Python package for your platform from the source website and run the tests and programs or the interactive interpreter.
Fork in The Road – Conditional Statements
Conditional statements show the intent of the programmer, you in this case, to instruct the computer to take one of the available branches of execution.
Imagine a lost hiker on a trail that has come to a fork in the road. How does she decide which path to take to join the rest of the party? We can guess the hiker would try to do any of the following,
call her friends
find out fresh footprints in the snow/sand
ask others that maybe hanging out in the vicinity if they have seen her party
call out to the group
light a flare
call emergency number
Assuming she tries one or all of these options, it will lead her to choose the path at the fork. This situation of a lost hiker at fork in the road, is modeled by the computer program using the conditional statements.
In pseudo-code we can write the situation as,
if ( calling_her_friends == success ): follow the path friends tell you else if ( found_fresh_footprints == success ): follow the path where footprints are else if ( ask_others_for_info == success ): vicinity if they have seen her party else if ( call_out_to_the_group == success ): follow the path group informs you else if ( light_a_flare == success ): follow the aid that arrives else: call_emergency_number
What we have done with this program is to instruct the computer to try all these options 1-5 in succession, and when any of them turn a success condition, we take that branch of code and let the computer follow that path. If all else fails, we take the emergency number option in branch 6.
Syntax of Conditional Statements
There is pretty much only one conditional statement in Python – the if-else statement. Python does not have a switch-case statement.
if <condition>: <body_1> elif <condition>: <body_2> ... elif <condition>: <body_n> ... else: <body_else>
Note that the syntax of Python language requires the body of if-statement to be indented by a tab (or same number of spaces) for each level of nesting.
Once you have installed Python language you can start the interpreter with $ python or using the IDLE interface on Windows. Starting python will show you a prompt like,
[email protected]:~/$ python Python 2.7.3 (default, Feb 27 2014, 20:00:17) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information.
Once you have interpreter started, try entering the code,
>>> if True: print "This branch executes" This branch executes
and you should see the self-descriptive output. Clearly the computer looks at the “condition” on the if-statement, which is True, and continues to execute its “body” – in this print the text.
Let us try changing the condition to False, and see what the Python interpreter has to show us;
>>> if False: print "This branch does not!"
The code does not print anything on the terminal, indicating the computer does not follow the body, since the condition is false. Pretty easy, isn’t it ?
Lets string up a few more of these if-elif-else branches, and see the effect of the precedence
>>> if False: print "Ignored branch" elif True: print "Take this branch first" elif True: print "because precedence of this statement is lower" else: print "final option is not taken!" Take this branch first >>>
which shows a series of conditional statements and the interpreter invokes the first branch that is true.
Lets finish this section with something called the nested-if statements,
if False: print "Ignored branch" elif True: print "Take this branch first" if False: print "2/Ignored branch" elif False and True: print "2/Take this branch first ??" elif True and False: print "2/because precedence of this statement is lower ??" else: print "2/final option is taken!" elif True: print "because precedence of this statement is lower" else: print "final option is not taken!" Take this branch first 2/final option is taken!
Putting it all together in a file, with following code listing,
if True: print "This branch executes" if False: print "This branch does not!" if False: print "Ignored branch" elif True: print "Take this branch first" elif True: print "because precedence of this statement is lower" else: print "final option is not taken!" if False: print "Ignored branch" elif True: print "Take this branch first" if False: print "2/Ignored branch" elif False and True: print "2/Take this branch first ??" elif True and False: print "2/because precedence of this statement is lower ??" else: print "2/final option is taken!" elif True: print "because precedence of this statement is lower" else: print "final option is not taken!"
and saving it as ‘conditionals.py’ you should see,
This branch executes Take this branch first Take this branch first 2/final option is taken!
$ python conditionals.py, is the command to interpret the code and then run the program.
Example – Finding Prime Numbers
Prime numbers are defined as numbers which are divisible by 1 or itself. For example number 17 can be written only as product of 1 and 17. It cannot be divided completely by any other number, 2, 3, 4 … to 16 without leaving a remainder.
Let us try and write a program to find if the number is prime, we start by following this algorithm,
- Is the number divisble by 2, 3, 4 to N-1 ?
- Use the modulo function to find the divisibility
- Repeat for numbers from 2 to N-1; For optimized performance we can use sqrt(N) as upper limit
- If all of these numbers are not divisiblePutting it all together we get the program, prime.py,
from math import sqrt,ceil N = input('Enter a # ') isprime = True for x in range( 2,int( ceil(sqrt(N))) ): if N%x == 0: isprime = False if isprime: print("Number %g is prime"%N) else: print("Number %g is not prime"%N)
which you can run interactively with inputs 5, 7, 29, 41 which are all prime and inputs 10,15,69 which are composite.
$ python primes.py Enter a # 29 Number 29 is prime
$ python primes.py Enter a # 69 Number 69 is not prime
Computer programming languages have strict syntax to write instructions (programs). A simple, but fundamental, instruction in computer programming is the conditional statement, If-Else. You can always learn more about software design and building programs using Python.
Top courses in Python
Python students also learn
Empower your team. Lead the industry.
Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.