Lecture 9

Conditions, loops and files with Python

You can watch the video lectures for

if statement

We can use if statement to put conditions for parts of our code in Python. Logical conditions from math can be used as follows:

An example script printing if variables X or Y are grater or less than or equal to 10 is below.

Here the important thing is that we need to put some spaces after the if statement line.

Two different if condition can be used together with/without and, or and not.

We can use elif or else as follows:

if can be used with arguments.

The other argument type action='store_true' is quite useful.

for loop

for loop is used for iterating over a sequence. See the script below.

Python can loop in the arrays as follows.

Multiple for loops can be used together.

while loop

while works as both for and if. Loop with a condition.

Writing files in Python

We can write strings with f.write method:

Write arrays into a file using NumPy. Text and binary files.

Read binary files.