XClose

An introduction to research programming with Python

Home
Menu

Control and Flow

Turing completeness

Now that we understand how we can use objects to store and model our data, we only need to be able to control the flow of our program in order to have a program that can, in principle, do anything!

Specifically we need to be able to:

  • Control whether a program statement should be executed or not, based on a variable. "Conditionality"
  • Jump back to an earlier point in the program, and run some statements again. "Branching"

Once we have these, we can write computer programs to process information in arbitrary ways: we are Turing Complete!

Conditionality

Conditionality is achieved through Python's if statement:

In [1]:
x = -3
if x < 0:
    print(x, "is negative")
    print("This is controlled")
print("Always run this")
-3 is negative
This is controlled
Always run this

The controlled statements are indented. Once we remove the indent, the statements will once again happen regardless of whether the if statement is true of false.

Else and Elif

Python's if statement has optional elif (else-if) and else clauses:

In [2]:
x = -3
if x < 0:
    print("x is negative")
else:
    print("x is positive")
x is negative
In [3]:
x = 5
if x < 0:
    print("x is negative")
elif x == 0:
    print("x is zero")
else:
    print("x is positive")
x is positive

Try editing the value of x here, and note which section of the code is run and which are not.

In [4]:
choice = "dlgkhdglkhgkjhdkjgh"

if choice == "high":
    print(1)
elif choice == "medium":
    print(2)
else:
    print(3)
3

Comparison

True and False are used to represent boolean (true or false) values.

In [5]:
1 > 2
Out[5]:
False

Comparison on strings is alphabetical - letters earlier in the alphabet are 'lower' than later letters.

In [6]:
"A" < "Z"
Out[6]:
True
In [7]:
"UCL" > "King's"
Out[7]:
True

There's no automatic conversion of the string True to the boolean variable True:

In [8]:
True == "True"
Out[8]:
False

Be careful not to compare values of different types. At best, the language won't allow it and an issue an error, at worst it will allow it and do some behind-the-scenes conversion that may be surprising.

In [9]:
"1" < 2
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In [9], line 1
----> 1 "1" < 2

TypeError: '<' not supported between instances of 'str' and 'int'

Any statement that evaluates to True or False can be used to control an if Statement. Experiment with numbers (integers and floats) - what is equivalent to True?

In [10]:
0 == False
Out[10]:
True

Automatic Falsehood

Various other things automatically count as true or false, which can make life easier when coding:

In [11]:
mytext = "Hello"
if mytext:
    print("Mytext is not empty")

mytext2 = ""
if mytext2:
    print("Mytext2 is not empty")
Mytext is not empty

We can use logical not and logical and to combine true and false:

In [12]:
x = 3.2
if not (x > 0 and type(x) == int):
    print(x, "is not a positive integer")
3.2 is not a positive integer

not also understands magic conversion from false-like things to True or False.

In [13]:
not not "Who's there!"  #  Thanks to Mysterious Student
Out[13]:
True
In [14]:
bool("")
Out[14]:
False
In [15]:
bool("James")
Out[15]:
True
In [16]:
bool([])
Out[16]:
False
In [17]:
bool(["a"])
Out[17]:
True
In [18]:
bool({})
Out[18]:
False
In [19]:
bool({"name": "James"})
Out[19]:
True
In [20]:
bool(0)
Out[20]:
False
In [21]:
bool(1)
Out[21]:
True
In [22]:
not 2 == 3
Out[22]:
True

But subtly, although these quantities evaluate True or False in an if statement, they're not themselves actually True or False under ==:

In [23]:
[] == False
Out[23]:
False
In [24]:
bool([]) == bool(False)
Out[24]:
True

Indentation

In Python, indentation is semantically significant. You can choose how much indentation to use, so long as you are consistent, but four spaces is conventional. Please do not use tabs.

In the notebook, and most good editors, when you press <tab>, you get four spaces.

In [25]:
if x > 0:
    print(x)
3.2

 Pass

A statement expecting identation must have some indented code or it will create an error. This can be annoying when commenting things out (with #) inside a loop or conditional statement.

In [26]:
if x > 0:
    # print x
print("Hello")
  Cell In [26], line 3
    print("Hello")
    ^
IndentationError: expected an indented block

So the pass statement is used to do nothing.

In [27]:
if x > 0:
    pass
print("Hello")
Hello