Conditions

These are used in decisions (if commands) and conditional loops

Simple Conditions

Simple conditions only have one condition

#
# equals, is the same as
if name == "fred":

# is not equal to, is not the same as
if name != "fred":

# is less than
if age < 18:

# is less than or equal to
if age <= 18:

# is greater than
if age > 18:

# is greater than or equal to
if age >= 18:

# is between two numbers (inclusive)
if age>=13 and age<=18:
if 13 <= age <= 18:
 
# is not between two numbers (inclusive) 
if age<13 or age>18:
 
#

Complex Conditions

Complex conditions have more than one condition, using AND, OR or NOT

#
# and - all conditions must be met
if age>= 13 and age<=14:
 
# or - any of the conditions must be met
if age==13 or age==14:
 
# not - the condition must not be met
if not (age==13 or age==14):
#

Each condition must be in full:

if age==13 or age==14:

You cannot write:

if age==13 or 14:

Ambiguity

Conditions with both an “and” and an “or” are ambiguous (more than one meaning).

#
absent=True and year="S1" or year="S2"
#

Brackets should be used to removed the ambiguity.

Pupils in S1 who are absent, and all pupils in S2:

#
(absent=True and year="S1") or year="S2" 
#

All absent pupils in either S1 or S2:

#
absent=True and (year="S1" or year="S2")
#

List Conditions

Instead of using lots of ‘or’s or ‘and’s:

if age==13 or age==18 or age==21 or age==50:
if name!='fred' and name!='sue' and name!='mark':

lists can be used:

#
# in the list
if age in [13, 18,21, 50]:
if name in ['fred', 'sue', 'mark']:
 
# not in the list
if age not in [13, 18,21, 50]:
if name not in ['fred', 'sue', 'mark']: #
#