If, Elif and Else Keywords in Python

Updated 13 April 2022

Continuing our Python journey deeper into this dynamo of a programming language we will immerse into the keywords | if |, | elif | and | else |. Imagine all these keywords as the traffic controllers telling the control flow where to go. The control flow is the sequence in which individual statements, instructions or functions of a software program are executed and evaluated. Control structures are a flowchart method to represent the control flow of programming languages and these will be used to demonstrate the effects of these Keywords. Keywords are the nuts and bolts vocabulary of any programming language, are reserved words and have special meaning. This special meaning can be commands or parameters which will be executed as soon as the computing device encounters the keyword when the code is run. For a great reference on keywords check out the guide All the Keywords in Python.

By having a firm grasp on how to use these keywords effectively and efficiently you will be able to crush any programming scenario where a choice needs to be made. Making choices and decisions is a part of life. The world is continuous flux and is impermanent. Nothing is constant except for change. Hopefully, the contents of this guide should enable you to make better decisions and the contents can be seen below.These keywords are all about asking a Python a Question

There are several related tutorials on our website to help you become a coding magus. A great place to start would be Python Rundown and Main Windows and Python and MicroPython - Compare and Access. These will also tell you where to download Python and access online Python emulators. Python is an excellent language to utilise with Raspberry Pi Boards such as Raspberry Pi 4 Model B 8GB. These are computing devices that can easily fit on the palm of your hand.

As always if you have any questions, queries or things to add please let us know your thoughts!


Overview of If, Elif and Else

In Python the | if | keyword is a control flow statement which enables us to execute a part of the software script only when a certain condition is satisfied. The | elif | keyword is shorthand for else if. This keyword is effectively an evaluation method that asks the question - if the previous conditions were not true, then try this new condition. Then if that new condition is met the code executes this particular true branch of the software program. The | else | keyword is a catch-all method, meaning anything which is not caught by the preceding conditions the control flow will still undergo a unique branch of the software program.

There may be a situation when you want to check for another condition after a condition resolves to true. In such a situation, you can use a nested if statements. A nested if statements is an if statement with another embedded if statement inside the keyword structure. Ergo it is an inner if statement which is within the body of an if statement.

Worth noting, an interesting feature of Python which differs it from other programming languages is it does not compile before executing software programs. When a compile occurs in other programming software it converts the human-written source code to a machine-executable code. This usually always takes place before a software program is executed. This means every possible code path (ergo, branches of the script) is tested. Since Python does not do this, if one of the branches of the script contains an error but the execution flow does not go down this branch, the code will run with no error issues. There are advantages and disadvantages to this. It is worthwhile for prosperity and consistency to execute Python scripts through every potential code path to ensure there are no hidden errors in your code.


Control Structures

Control structures are a flowchart method to represent the control flow of programming languages. In computer science, the control flow is the order in which individual statements, function utilisation or instructions of a software program are executed. This is also referred to as the flow of control. Simply program flow is a general term which describes the order in which your lines of code are evaluated by the computing device.

Control structure flowcharts convey each step in the software program as boxes of various kinds. The order is demonstrated by connecting the boxes with arrows. The shape of the box represents the code line type and allow for easier identification. The shape of the box can represent either a command statement, a variable creation, a condition or a decision. A great reference point for these can be found at Control Structures in Python.

Three Simple Code Flowcharts Using Control Structures


If Keyword

The | if | keyword is a control flow statement which enables us to execute a part of the software script only when a certain condition is satisfied. If statements can be used with all the logical comparison operators learned about before. These can be seen as logical conditions or conditional expressions. Below is a simple script inside the Python Programming Window which uses an | if | keyword to make a decision. The result of this script can be seen in the Python IDLE Shell adjacent. Further below is a control structure flowchart representing this script. The flowchart demonstrates exactly the paths of execution that the computing device can do when this script is run.

This script will attempt to emulate a bouncer standing outside a night club. This script will ask a potential client if they are of the Australian legal age to drink alcohol, which is 18 years old. To start it creates a variable to represent the client's age. This variable has identifier A (A for age). Then it will welcome a potential client into the club if they are 18 years or older. If the age is not met then it will not do this. Regardless of the previous outcome, the final step in the script will be to create another variable. In this case, it will be a string variable which embodies the future activity of the bouncer (B for bouncer). 

Syntax worth noting, when you finish the line which initialises if statement you must end the statement with | : |. Furthermore, all parts of the script which are part of the if branch must have an indentation. This is achieved either by entering four spaces with the spacebar key or a single press of the tab key, both buttons found on your keyboard. 

Bouncers performing their job. Two Variables defined and a Comparison Operator

Control Structure Flowchart Annotated with code that uses an if Statement


Elif Keyword

The | elif | keyword is shorthand for else if. This keyword is used in conjunction with if statements. The keyword is effectively an evaluation method that asks the question - if the previous conditions were not true, then try this new condition. Then if that new condition is met the code executes this particular true branch of the software program. Elif statements can be used with all logical comparison operators. These can be seen as logical conditions or conditional expressions. Below is a simple script inside the Python Programming Window which uses an | elif | keyword and an | if | keyword to make decisions. Worth noting, it is possible to utilise multiple | elif | keywords each testing for different unique conditions within a single if statement. Let us know if you want to see this. The result of this script can be seen in the Python IDLE Shell adjacent. Further below is a control structure flowchart representing this script. The flowchart demonstrates exactly the paths of execution that the computing device can do when this script is run.

This script does what the previous one does but more! To start it creates a variable to represent the client's age. This variable has identifier A (A for age). Then it will welcome a potential client into the club if they are 18 years or older. If the age is not met then it will tell the person too bad and to come back in however many years it will take till they hit the legal drinking age. Regardless of the previous outcome, the final step in the script will be to create another variable. In this case, it will be a string variable which embodies the future activity of the bouncer (B for bouncer). Using the | elif | keyword generates three potential paths for control flow to get to the creation of variable B.

Syntax worth noting, when you finish the line which initialises the elif statement you must end the statement with | : |. Furthermore, all parts of the script which are part of the elif branch must have an indentation. This is achieved either by entering four spaces with the spacebar key or a single press of the tab key, both buttons found on your keyboard.

Bouncers performing more of their job. In this case Three Variables defined and two Comparison Operator

If and Elif statements in a control structure flowchart


Else Keyword

The else keyword catches anything which is not caught by the preceding conditions. This keyword is used in conjunction with if statements. The else statements can also be used with all logical comparison operators. These are logical conditions or conditional expressions.  Below is a simple script inside the Python Programming Window which uses an | if | keyword and an | else | keyword to make decisions. The result of this script can be seen in the Python IDLE Shell adjacent. Further below is a control structure flowchart representing this script. The flowchart demonstrates exactly the paths of execution that the computing device can do when this script is run.

This script does exactly what the previous elif script did, however, it does not need two comparison operators to run. This is because the | else | keyword acts as a catch-all and does not require a comparison operator to run. This catch-all means using this method there are only two paths that the control flow can take to get to the creation of variable B. Whereas, using the | elif | keyword generates three potential paths for control flow to get to the creation of variable B.

Syntax worth noting, when you finish the line which initialises the else statement you must end the statement with | : |. Furthermore, all parts of the script which are part of the else branch must have an indentation. This is achieved either by entering four spaces with the spacebar key or a single press of the tab key, both buttons found on your keyboard. 

Bouncers performing more of their job. In this case Three Variables defined and only one Comparison Operator

If and Else statements in a control structure flowchart


Nested If Statements

There may be a situation when you want to check for another condition after a condition resolves to true. Python programming language allows you to do this by using if statements inside other if statements. This is referred to as a nested if statement. Below is a script that has been written in the Python Programming Window where an if statement has been nested inside another if statement. The results of this script can be seen in a Python IDLE Shell adjacent. Further below is the control structure flowchart for this script. This demonstrates how the nested if structure operates and also aid understanding of what exactly the possible paths of code execution are.

This script is emulating a scenario where a client has come to the night club but has no ID. In this scenario, the individual attempts to leverage their social clout but the bouncer is having none of it and the client is swiftly prevented from entering. The variable A now embodies the answer that the potential client is saying to the bouncer. The initial if statement decides the path of control flow based on whether the variable A is an integer number. When variable A is an integer number the embedded if statement is executed. This runs the same script as seen under the Elif Keyword heading. If the variable is not an integer number the | else | keyword is executed. This prints a string variable that represents the response of the bouncer to the client, which is efficiently preventing entrance to the establishment. Regardless of all previous outcomes, the final step in the script will be to create a variable B to embody the future behaviour of the bouncer. There are four potential paths for control flow to get to the creation of variable B.

Syntax worth noting, each time there is a deeper level of if statements the indentation must increase by a further step. Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. A single indentation is achieved either by entering four spaces with the spacebar key or a single press of the tab key, both buttons found on your keyboard. 

Bouncers will quiver when they realise how easily they could be replaced! An if statement nested inside another if statement

Nested If Statement Control Structure Flowchart


Shorthand and Simplified Methods

There is a lot of depth to these keywords. Furthermore, because of their regular use, the syntax when using these Python keywords is very forgiving. Thus, there are a number of different shorthand methods to more efficiently use these keywords whilst retaining their function. Simplified, in this context, means to lower the total number of lines within a programming script.

Below is a shorthand version of the previous script (the script under the Nested If Statement heading). The below script will perform exactly the same. Shorthand methods do not increase the ease of readability for a human though and below demonstrates this. This code does introduce some swell syntax methods that can be used in your future coding escapades. For instance, you can use a single line to represent an entire statement which incorporates the | if |, | else | and | print | keywords.

Shorthand or convoluted? You decide.


The Next Step

The natural next step in our coding adventures would be the guide Loops in Python. This will provide deep knowledge on the | for | and | while | keywords, both unique tools to control the execution flow of your Python scripts.


Download the Codes

Below you can find all the code for the above examples. You will be able to run the codes here on your own computing device and modify the code at your leisure. Open it up with Python IDLE Shell and run it using the Python Programming Window.  

Attachment - Python-If-Elif-Else-Scripts.zip

Have a question? Ask the Author of this guide today!

Please enter minimum 20 characters

Your comment will be posted (automatically) on our Support Forum which is publicly accessible. Don't enter private information, such as your phone number.

Expect a quick reply during business hours, many of us check-in over the weekend as well.

Comments


Loading...
Feedback

Please continue if you would like to leave feedback for any of these topics:

  • Website features/issues
  • Content errors/improvements
  • Missing products/categories
  • Product assignments to categories
  • Search results relevance

For all other inquiries (orders status, stock levels, etc), please contact our support team for quick assistance.

Note: click continue and a draft email will be opened to edit. If you don't have an email client on your device, then send a message via the chat icon on the bottom left of our website.

Makers love reviews as much as you do, please follow this link to review the products you have purchased.