This section covers doing different actions based on input given to the programme (changing the control flow).
True/False
To decide whether to do something in a programme, you use what is known as a boolean statement. This statement (a boolean) is either True or False.
The literals (text you enter directly in your code) True
and False
represent true and false (whether something is true), for example:
a_true_variable = True a_false_variable = False
You can negate (reverse) a True
/False
value by preceding it will the not
keyword:
About: Keywords: These are words that do something specific in the Python language and cannot be used for anything else other than their set purpose.
>>> not True False >>> to_negate = False >>> not to_negate True
Given two (or more if you chain statements together) boolean values you can create a new value based on what they are using the and
and or
keywords. The two values are placed either side of the keywords. and
will result in True
(False
otherwise) only if both boolean values are True
, or
will result in True
if at least one value is True
, if neither values are True
, False
will be the result:
>>> True and not False True >>> False or not True False >>> not False and not False and True True >>> not False or False or True True
Given two values (including boolean values) you can create a boolean value based on them by comparing them to each other:
>>> 1==5 False >>> "Matthew"=="Matthew" True >>> 5=8 True >>> 5!=(8-3) False >>> "Alphabet" < "Begin" True >>> not True == False True
The operators (==, <, etc.) available for use are:
Operator | Checks |
---|---|
x==y | if x is the same as y |
x != y | if x is different to y |
x < y | if x is smaller than/lexicographically before y |
x > y | if x is larger than/lexicographically after y |
x <= y | if x less than or the same as y |
x >= y | if x larger than or the same as y |
not x | if x == False |
x and y | if x and y are both True |
x or y | if either x or y is True |
Lexicographically means ‘in dictionary order’.
If the condition checked is true, the result is True (False otherwise), as shown above.
You can also use variables for the comparisons:
>>> website = "Invincitech.com" >>> website=="Invincitech.com" True >>> website=="Wikipedia.org" False >>> stars=10 >>> stars==2 False >>> stars==10 True
Conditionally executing code…
…or doing something if something is true.
In the last part input was taken from the user in a very simple programme:
print("Please enter your name, followed by [ENTER]:") name = input() print("Hello "+name+".")
By the end of this section you should be able to cause different messages to be printed when different names are entered (an exercise to complete later).
if statements
An if statement takes a boolean value (e.g. True
or the result of x==y
), and executes its code if the value is True
.
For example:
x = 5 if x==5: print("x equals 5")
As x has been set to 5, the code will print “x equals 5”, all if statements are like this, the code they run is placed in a block, indented a fixed number of spaces (four used here), and the line the condition is on ends with a colon (to indicate the start of a new block).
if [condition/boolean]: [code to run, line 1] [code to run, line 2] [code to run, line...
The code not in the if statement is left unindented, and executed regardless of what the if statement does.
else statements
Looking back at the example given, how would something different be printed if x!=5. An if statement with a x!=5 (or !(x=5)) as the condition would work:
x=6 if x=5: print("x equals 5") if x!=5: print("x is not equal to 5")
The else statement behaves the way, but clearly indicates behaviour (do this, if
, otherwise do this, else
):
x=6 if x=5: print("x equals 5") else: print("x does not equal 5")
In both the second statement (if x!=5
and the else
) will be run, printing “x does not equal 5
“.
Checking for multiple related conditions
Should something different need to happen when x=0 or 6 or 34, for each one, and a general piece of code to be run for all other values of x, the if statements can be nested (i.e. have if and else statements in the if statement blocks):
if x=0: print("x is zero") else: if x=6: print("x is six, an even number") else: if x=34: print("x is 34, 34=2*17") else: print("x is just "+str(x)) #str(x) converts x to a string so it can be appended, # which is covered in a later section
This will rapidly get out of hand for a larger programme, so a better method exists, the elif
(else if) statement:
if x=0: print("x is zero") elif x=6: print("x is six, an even number") elif x=34: print("x is 34, 34=2*17") else: print("x is just "+str(x))
Now try the exercise suggested earlier (which uses name
instead of x
and compares strings instead of numbers).
Repeatedly running code (while)
The below will print all the numbers from 1-10 (change it to 5-25 as an exercise):
x = 1 while x!=11: #alternatively x<11 print(x) #print x - str(x) not needed as x is printed by itself x = x+1 #increase x by 1
This makes use of the while statement, which repeatedly runs its body (block that is attached to it), until its condition is false. It supports the same conditions as the if statement and is formulated in the same way (except while is substituted for if).
The above prints
1 2 3 4 5 6 7 8 9 10
It could have been formulated differently as:
x = 0 while x<10: x = x+1 #increase x by 1 print(x) #print x
This gives the same result; try to determine why (or explain what happens in terms of x).
Using while (known as a loop) is done in all major programmes and this is known as looping. The programme will run through the loop’s code (while’s body) loop back to the beginning of the loop (start of the while’s body) and run the code again, and loop back and so forth, until the condition is false.
Summary
Using everything learnt so far you can now cause specific pieces of code to run, given that a condition is true and from that, cause a specific path to be followed through the code – causing something different to happen with different inputs to the programme (script).