Python: 9 Conditions - If Else Statements
If else statements allow for a program to select the code to run based on the outcome of a true / false condition.
Look on W3 Schools for more information on if else statements in Python.
The example below has two numbers stored in the variables 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))
else:
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.