5.14. Logical syntax#

White space characters are critical components of Python syntax. The " ", \t and \n characters are employed.

As you will see, indentation of Python lines is used to delineate logical structure to a program. Lines that sequentially follow and are at the same indentation level are executed according to the same conditions.

Indentation can be done using \t or spaces. In general, it’s best to uses spaces and the convention is to use 4 spaces as a unit of indentation. In most text editors, this can be done by setting a preference for soft tabs equal to 4 spaces.

5.14.1. Indentation levels in a file#

When you are writing scripts, your file must have some lines that have no indentation.

Like this#
print("Hello World!")
Not like this!#
    print("# Correct")

5.14.2. Conditionals#

A “conditional” is a statement whose execution depends on the value of a variable. Python conditionals require using the : (colon) character to complete a statement.

I want to choose a greet based on the value of name. This objective is expressed as a Python conditional.

name = "Timbo"
if name == "Gavin":
    greet = "Hello Guru"
else:
    greet = "What Up"

5.14.3. More complicated conditionals#

If you have more than two conditions, you can use elif. The first case is always assessed using if, then elif, and last is else.

name = "Timbo"
if name == "Gavin":
    greet = "Hello guru"
elif name == "Timbo":
    greet = "What Up"
else:
    greet = "Sorry, but I do not know your name."

5.14.4. Conditional statement with multiple clauses#

There are binary operations that can be combined to increase the complexity of conditional clauses. Specifically, and, or not.

k = 24
j = 3
if k > 0 and j > 0:
    print("Both positive")
Both positive

check we don’t try taking the log of negative numbers

from math import log

if k < 0 or j < 0:
    print("Cannot take log of a negative")
else:
    print(log(k) - log(j))

We can use not to negate a statement.

if k and not j:
    print("k is different from zero, but j must be zero")

As an alternate, there may be causes where you wish to check for existence of a value in a series.

sequence = "ACGTTAGGTATGTAA"
if "ATG" in sequence:
    start_codon = True

Or

numbers = [0, 23, 47, 61]
if 2 not in numbers:
    absent = True

5.14.5. Repetition / Looping / Iteration#

These are mechanisms for doing exactly the same thing over and over. The primary approaches to doing this are the while and for statements. (In general, the for statement is preferred.)

5.14.5.1. while loops#

print("Before the while loop")
count = 0
while count < 3:
    print(count)
    count += 1
print("After the while loop")
Before the while loop
0
1
2
After the while loop
count = 0
while count < 1000:
    print(count)
    count += 1
    if count == 3:
        break  # a special key word for exiting loops
0
1
2

Note

The indentation specifies the logical grouping of statements. Only the indented lines after the while statement are executed when the condition (count < 3) is True.

5.14.5.2. for loops#

A for loop operates until it gets to the end of the series it’s given. The components of a for statement are:

for variable_name in my_series:
    # indented code to be executed at each step

# de-indented code executed after the for loop

So the key parts of a valid for statement line are:

  1. Begins with the for keyword

  2. a valid python variable name, variable_name in the above [1]

  3. the series of objects to be iterated over, my_series in the above

  4. terminated by a :

The for loop definition is completed by adding the code you wanted to execute on each iteration through the loop. Here’s an example.

word = "cheese"
for letter in word:
    print(letter)
c
h
e
e
s
e

In this case, our series of objects is word (a string). The variable letter is defined in the for loop statement and it will take on the value of each object (a string of length 1) in word. The code to be executed at each iteration through the loop is just a print statement. All lines of indented code following the for statement will be executed at each iteration.

Note

Strings have the special property of being iterable. Many other Python data types also have this property, including lists, tuples, dicts and files.

enumerate loops, a special for loop#

A for loop with the convenience of also returning the index of the element in the series.

word = "cheese"
for value in enumerate(word):
    print(value)
(0, 'c')
(1, 'h')
(2, 'e')
(3, 'e')
(4, 's')
(5, 'e')

functions return multiple objects. If you know a certain number of objects will be returned then knowing how to do a multiple assignment can be useful.

It can also be applied in other contexts. One particularly useful context is in looping. In the following example, I’m looping over pairs of integers and assigning the results to separate variables. Note the use of the "," in the for statement.

5.14.5.3. Multiple unpacking in loops#

One particularly useful context to use multiple unpacking is in looping. In the following example, I’m looping over pairs of integers and assigning the results to separate variables. Note the use of the "," in the for statement.

The tedious way#

# here is a tedious way
coordinates = [(0, 1), (0, 2), (0, 3)]
for coord in coordinates:
    x = coord[0]  # grabbing each integer by it's index
    y = coord[1]
    print(x, y)
0 1
0 2
0 3

The succinct way#

# This is more succinct
coordinates = [(0, 1), (0, 2), (0, 3)]
for x, y in coordinates:
    print(x, y)
0 1
0 2
0 3

5.14.6. Comments in code#

In Python, a comment is all text occurring after the # symbol line. All characters occurring after it are ignored by the interpreter. Comment lines are used to explain in normal language what a block of code is doing, or to record other information such as the license.

# this is a comment

a = 2 ** 16 # and this is another comment

5.15. Exercises#

  1. Show whether the number 11 is Truthy or Falsy?

  2. Show whether {} is Truthy or Falsy?

  3. Iterate over text and, if a character is a vowel (“aeiou”), print the character and its index in text.

text = "Some random text"

Fancy formatting not required.

Index :  Vowel
    1 : 'o'
    3 : 'e'
    6 : 'a'
    9 : 'o'
   13 : 'e'
  1. Write a for loop that prints whether the elements of values are Truthy, Falsey or actually the booleans True/False.

values = [0, 11, {}, False, True]
0 is Falsy
11 is Truthy
{} is Falsy
False is a bool
True is a bool