Python/Program Flow and Logicals
Preliminaries
One essential thing to understand when programming in Python is that correct indenting of code is essential. The Python programming language was designed with readability in mind, and as a result forces you to indent code blocks such as the following:
- while and for loops
- if, elif, else constructs
- functions
The indent for each code block must be the same, and the Python programming language also requires you to mark the start of a code block with a colon. So where MATLAB used end
to mark the end of a block of code, Python uses a change in indent. Other than this, simple Python programmes aren't dissimilar to those in MATLAB.
So for example, the simplest case of an if
conditional statement in Python would look something like this
if condition:
statement1
statement2
...
and the code in lines statement1
, statement2
, ...
is executed only if condition
is true. Sharp sighted readers might also spot another difference to MATLAB, in Python there is no need to add a semicolon at the end of a line to suppress output.
The if
functionality can be expanded using else
as follows
if condition:
statement1
statement2
...
else:
statement1a
statement2a
...
where statement1
, statement2
, ...
is executed if condition
is true, and statement1a
, statement2a
, ...
is executed if condition
is false. Note that the code block after the else
starts with a colon, and the code block is also indented.
Finally, the most general form of this programming construct introduces the elif
keyword (in contrast to elseif
in MATLAB to give
if condition1:
statement1
statement2
...
elif condition2:
statement1a
statement2a
...
...
...
elseif conditionN:
statement1b
statement2b
...
else:
statement1c
statement2c
...