Python if-elif-else

Here are some course notes for getting started with Python. In this article, we’ll look at and run some code which has an example of if, elif, and else in it.


Python if, elif and else

if

The if statement can be used to ask a question, and if the answer is True it will run the code block after it

elif

elif can be used after if. If the if question was False it will execute the code after elif if the elif question is True. It really means “else if”, but that was too long for some lazy programmers to type, so they use elif instead!

else

else can be used after an if statement, and sometimes after an elif statement. It executes the code after it, only if none of the previous questions turned out to be True

Code Comments

It’s helpful sometimes to add comments to your code, especially if it gets complicated!

Preceding some text in a python script with “#” stops the python program from treating it as python code - it just ignores it. This means we can use “#” to write comments in our Python scripts to help others understand our code.

The example code

if,elif,else is best illustrated by example, so we have some code to try!

Click with the right mouse button on this link: if_elif_else.py and choose “save link as” or “save target as”.

Can you save the code in a suitable directory, open a terminal window, navigate to the right directory, and run the code?

What does the code do?