If Else - Lakelands Computing

Title
Go to content
If Else
Using If statements allows you to put a form of decision making or selection into your programs. When an if statement is run it checks to see if the condition is True or False. It works using the following basic logic

  • If Condition A is True
  • Then do this Action (X)
  • Else (otherwise) do this Action (Y) instead.

A Condition can be several things:

    • comparing two things as
      • if a == b: (equals - includes being same data type)
      • if a > b: (greater than)
      • if a < b: (less than)
      • if a != b: (not equal)

    • checking if something is present
      • If a is in b (checks if a is found in b, can be used to look for characters in a string, or a value in a list, dictionary etc)

In python, the code to be run if the condition is true (or false) is indented (pushed in). The identation should be either 1 tab or 4 spaces. I use the tab as I find it easier to keep everything lined up that way.

Note the  : after the if a >b: etc and after else:. These colons are important (miss them out and the code will throw errors)
Did you notice I had to cast the age variable to integer on line 35. If I hadn't then the if statement wouldn't work  (delete it to see what happens)
All Text copyright Lakelands Academy & Mr T Purslow 2020.
All images copyright free / creative commons unless otherwise stated.
You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
Back to content