We’ve looked at decision statements in flowcharts and pseudo-code before. Now we want to look at how to build them in Python.
Decisions are very important because they allow you to skip a section of code that isn’t relevant to you as you are running a program.
Think about a situation where you are checking to see if a person can drive or not. Well, if they are not at least a certain age, they cannot even get a licence, so the code doesn’t need to ask the program’s user if they have a license because we know the answer already.
In its most basic format, an if statement in Python follows the following format:
if <condition> :
<true block>
A condition has to be in a true/false response. Many times, we will look at numeric values, since those are easy. Python gives us six (6) relational operators to check between two values. These are very familiar to those found in Algebra.
Conditional | Value/Name |
== | Equality – double equals |
< | Less Than |
> | Greater Than |
<= | Less Than or Equal To |
>= | Greater than or Equal To |
!= | Not equal To |
An example of using this would look like
if num1 > 50000 :
Notice that parenthesis are not required around the condition, like in some other languages.
The condition has to give a true/false response. It is designed for this. If it is true, the true block of code will execute.
Python uses indention instead of braces, like some other languages. So on the line after your if statement, indent and that code will run if the if statement is true. Keep your indention for any additional lines of code that need to run. For example:
if sales > 50000 :
print("Bonus is due")
bonus = 1500
But what if you want to do something different if the value of the condition statement was not true. That’s where the else block comes into play. After the true block is run, go back to the same level of indention as your if statement and write else : After that, you can have an else block of code, like you see below.
if sales > 50000 :
print("Bonus is due")
bonus = 1500
else :
print("No bonus this month")
You can see the else statement here, where the condition was not met. However, we can utilize more complex decision if necessary.
Using the If Statement was originally found on Access 2 Learn