1 Minute Read #18 - IF statements in Python
We can mark our progress through learning a programming language through the following concepts:
● Sequence
● Selection
● Repetition
The first of these is what we learn at the very beginning of programming a computer - learning how to correctly program a computer to do something in a certain set of steps, such as calculate a value and print the result. The code, when written correctly, performs these steps in a certain sequence.
Selection is a more advanced twist on this - it allows us to insert code which gives the user multiple pathways to take. In Python we use statements known as IF, ELIF and ELSE. These
Let’s try a couple of Naughty List programs…
In Python→ Idle 3.6 → New File, type the following:
Save the file as NaughtyList.py and run it.
It should look like this:
Now we can make a more sophisticated program. Start another New File, rather than use the existing NaughtyList file.
Call the new program NaughtyListVersion2.py
Type the following:
Test your code a few times to check it is working. It should run like this:
So far we have used IF and ELIF and ELSE in a fairly simple way. The next stage is to nest IF statements.
Clearly you can nest lots of different blocks of code within each other if you know what you are doing.
Whitespace is something like a tab (a block of blank spaces that move the cursor along when you hit the TAB key) or even a single tap of the spacebar. Python code that is at the same position - indented the same number of spaces from the left margin - groups the code into its own block. Whenever you start a new line of code with more spaces than the one that came before it, you are starting a new block. AND that block is part of the previous one.
The code below nicely illustrates blocks of code, including nested IFs. Type it into a New File, and call the file InstaMegaIF.py
As easy as a mince pie!