Lets dive into the Python keywords if, elif and else. Visualise all these keywords as the traffic controllers telling the control flow where it should go. This will give you a firm grasp on how to use all these keywords allowing you to crush any programming scenario where a choice needs to be made.

Transcript

Hey gang! Tim here from Core Electronics and today we're nailing our understanding of the “if”, “elif” and “else” keywords within the programming language of Python. (Usable on the Picos, Raspberry Pi, and many other boards)

By having a firm grasp on how to use these keywords effectively you'll be able to efficiently crush any programming scenario where a choice needs to be made. Imagine all these keywords as the traffic controllers telling the control flow where to go. As a refresher, the control flow is a 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 a programming language and these will be used to demonstrate the effects of these keywords.

Keywords are the nuts and bolts of any programming language; they are the reserved words and they have special meaning. This special meaning can be commands or parameters which will be executed as soon as the computing device (such as the Raspberry Pi) encounters the keyword when the code is run. So, let's dive into a brief overview of them all. In Python the “if” keyword is a control flow statement which allows us to execute a part of the software script only when a certain condition is satisfied, the “elif” keyword is shorthand for “else if” 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. 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's program, now let's demonstrate these keywords inside some Python scripts and accompany them with a control structure flowchart.

Jumping into the computer we can see a script inside the Python programming window which uses an “if” keyword to make a decision. The results of this script can be seen in the Python idle shell, which is below after I’ve run it. This script will attempt to emulate a bouncer standing outside a nightclub, the 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 will create a variable to represent the client's age, this variable has identifier “A”, “A” for age then it will welcome the potential client into the club if they're 18 years or older. If the age is not met then it will not do this, so regardless of the previous outcome the final step in the script will be to create another variable. So, in this case it will be a string variable which embodies the future activity of the bouncer, “B” for bouncer, so syntax worth noting when you finish the line which initializes an “if” statement, you'll see you need to write a colon, furthermore all parts of the script which are part of the “if” branch must have an indentation. This is achieved either by entering four spacebars with the spacebar key or a single press of the tab key.

Also, on the computer is a control structure flowchart representing this script. The flowchart demonstrates exactly the path of execution that the computing device can do when the script is run. So, in this example because “A” is “18”, the flow would go through here and because it's true, we’d come this way and say “come into the club buddy” which does happen and then produces the final variable “B”, so you can clearly see that there's two different ways to get to the final variable creation. So if “A” was less than “18” then it would go through this because if “A” is greater than “18” that's false because it's less than “18” and then it will go straight to here. So, if I were to run this again with a less than “18” run the module, you'll see that it doesn't print anything.

Next, the “elif” keyword which as I said 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. So, jumping back into the computer screen we can see a script inside the Python programming window which uses an “elif” keyword and an “if” keyword to make a decision. The results of this script can be seen in the Python idle shell after the module has been run. Now worth noting, it is possible to utilize multiple “elif” keywords each testing for a different unique condition with a single “if” statement, so the script does what the previous one did but it also does more. So to start it creates a variable to represent the client's age, this variable has identifier “A”, “A” for age then it will welcome the potential client into the club if they're 18 years or older however if the age is not met as I will demonstrate now, then it will tell a person “too bad” and not only just “too bad” it will also tell them however many years it will take until they hit the legal drinking age, so regardless of the previous outcome the final step in the script will be to create another variable.

The syntax worth noting is that you must use a colon at the end of the line and everything else is also indented which is part of the “elif” branch of your software. So, I brought to the table a control structure flowchart that represents this script, the flowchart demonstrates exactly the path of execution that the computing device can do, while the script is run. So, you can see clearly that there's three different ways for this script to end up at the final variable being created, now you might ask how can this be? Because if “A” is greater than or equal to 18 and “A” is less than 18 leave  nowhere or no space to go but if I have to change the code just a little bit, for instance if I was to say less than 13 which doesn't make any sense in Australia, but if I did that and then run the code you'll see that nothing is printed and this is the code going through this third option. This is the advantage of seeing control flow, flow charts like this, you can see exactly all the options that your script can possibly have.

Finally, the “else” keyword this catches anything which is not caught by the preceding conditions, this keyword is used in conjunction with “if” statements. The “else” statement can also be used with all logical comparison operators, these are logical conditions or conditional expressions. So flying into the computer, there is a script inside the Python programming window which uses an “if” keyword and also an “else” keyword to make a decision the results of this Python script can be seen in the Python idle shell, once I run this module, so this script does exactly what the previous “elif” script did, however it does not need two comparison operators to run correctly this is because the “else” keyword is acting as a catch-all and does not require a comparison operator to run. This catch-all means also that there is only two parts that the control flow can take to get to the creation of variable “B” so brought to the table with me is a control structure flowchart representing the script and you can see just that there's only two ways to get to variable “B”.

Now, finally I’ll introduce the concept of “nested if” statements there may be a situation where you want to check for another condition, after a condition resolves to true. Python programming language allows you to do this by utilizing “if” statements inside other “if” statements this is referred to as “nested if” statements. Bounding into the screen one more time you can see a more complicated script than before written in the Python programming window this has an “if” statement nested inside another “if” statement, you can also see the keywords “elif” for used and “else” the results of this script can be seen in the Python idle shell after I’ve run this script. This script is emulating a scenario where a client has come to the nightclub but has no ID, in this scenario the individual attempts to leverage their social clout but the bouncer is having none of it and then the client is swiftly prevented from entering.

Now the variable “A” embodies the answer that that 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 which you can see here, if integer number equals the type of “A” when variable “A” is an integer number, the embedded “if” statement is not executed and instead it goes straight out here to the “else” and print “no I don't remember you, you need ID here” however when this is an integer number, the embedded “if” statements will run so for instance this became “18” and I ran this now you'll see that it says “come to the club buddy”, so 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.

The syntax worth noting each time there is a deeper level of “if” statements the indentation must increase by a further step, which you can see happening here. Here's one indentation and here is a double indentation, now without a control structure flowchart it will not be clear that there are four potential paths for execution flow to get to the creation of variable “B” but I brought one on the table with me today and you can see that there's one, two, three and four different ways to get to the final variable creation.

Now all these keywords have a huge amount of depth and are regularly used making choices and decisions is a part of life, the world is constantly in flux and is impermanent nothing is constant except for change, as such 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 in this context simplified means to lower the total number of lines within the Python script. if you're interested in learning more about shorthand methods come check out written up Core Electronics guide online and that's it! Until next time, stay cosy.

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.