9 Conditions – If Else Statements

If else statements allow for a program to select the code to run based on the outcome[3] of a true / false condition[1].

Look on W3 Schools for more information on if else statements in Python[4].

The example below has two numbers stored in the variables[2] num1 and num2. the if statement has a condition num1 < num2 which will check if num1 is less than num2 if this is True the indented code below after the : will run

If it is false the indented code after the else: statement will run.

num1 = 75
num2 = 30
if num1 < num2:
  print("{} is smaller than {}.".format(num1, num2))
  print("{} is larger than or equal to {}.".format(num1, num2))

Indentation of code is really important in Python.

Wherever you see a : the next section of code is expected to be indented.

All of the code that is indented will be run if that condition is true.

print("Program starting")
name = input("Please enter your name: ")
if name == "Bob":
  print("Hi Bob")
  print("I hope that you are having a good day")
print("Program finished")

Entering a value that caused a true condition

Entering a value that caused a false condition

The else block of an if statement is optional.

a = 6
b = 7
if a > b:
  print("a is greater than b")

The example above would not print any output as the condition would evaluate to be false so the code block would be skipped.

Terms definitions
1. condition. A statement that a program checks to see if it is true or false. If true, an action is taken. Otherwise, the action is ignored.
2. variables. “Containers” used to label and store data in memory. The data can then be used throughout a program: * Integer variables use only numbers and so can be used for calculations * String variables are sequences of code that may contain numbers, letters, and other characters, and so cannot be used for calculations.
3. outcome. Products and systems developed through Technological Practice for a specific purpose. A technological outcome is evaluated in terms of its fitness for purpose, and can be described by their physical and functional nature.
4. Python. A type of programming language. It is one of many high-level, general-purpose programming languages. It was first released in 1991