Conditions

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

Simple Conditions

Simple conditions only have one condition

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#
# 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:
  
# 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

01
02
03
04
05
06
07
08
09
10
#
# 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).

1
2
3
#
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:

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

All absent pupils in either S1 or S2:

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

List Conditions

Instead of using lots of ors or ands:

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:

1
2
3
4
5
6
7
8
9
#
# 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']: #
#