AuthorJing Wu2018-06-02

Introduction

We discussed the basic data types and data structures in Python in the last tutorial. This chapter covers logical operations and loops in Python, which are very common in programming.

Logical Operations

Like most programming languages, Python has comparison operators:

print(1 == 0)    # 1 equals 0
print(1 == 1)    # 1 equals 1
print(1 != 0)    # 1 is not equal to 0
print(5 >= 5)   # 5 is greater than or equal to 5
print(5 >= 6)    # 5 is greater than or equal to 6
[out]:
False
True
True
True
False

Each statement above has a boolean value, which must be either True or False, but not both.

We can combine simple statements P and Q to form complex statements using logical operators:

  • The statement "P and Q" is true if both P and Q are true, otherwise it is false.
  • The statement "P or Q" is false if both P and Q are false, otherwise it is true.
  • The statement "not P" is true if P is false, and vice versa.
print(2 > 1 and 3 > 2)
print(2 > 1 and 3 < 2)
print(2 > 1 or  3 < 2)
print(2 < 1 and 3 < 2)
[out]:
True
False
True
False

When dealing with a very complex logical statement that involves in several statements, we can use brackets to separate and combine them.

print((3 > 2 or 1 < 3) and (1 != 3 and 4 > 3) and not (3 < 2 or 1 < 3 and (1 != 3 and 4 > 3)))
print(3 > 2 or 1 < 3 and (1 != 3 and 4 > 3) and not ( 3 < 2 or 1 < 3 and (1 != 3 and 4 > 3)))
[out]:
False
True

Comparing the above two statements, we can see that it's wise to use brackets when we make a complex logical statement.

If Statement

An if statement executes a segment of code only if its condition is true. A standard if statement consists of 3 segments: if, elif and else.

if condition1:
    # if condition1 is true, execute the code here
    # and ignore the rest of this if statement
elif condition2:
    # if condition1 is false, and condition2 is true, execute the code here
    # and ignore the rest of this if statement
else:
    # if none of the above conditions is True, execute the code here

An if statement doesn't necessarily has elif and else part. If it's not specified, the indented block of code will be executed when the condition is true, otherwise the whole if statement will be skipped.

i = 0
if i == 0: print('i == 0 is True')
[out]: i==0 is True

As we mentioned above, we can write some complex statements here:

p = 1 > 0
q = 2 > 3
if p and q:
    print('p and q is true')
elif p and not q:
    print('q is false')
elif q and not p:
    print('p is false')
else:
    print('None of p and q is true')
[out]: q is false

Loop Structure

Loops are an essential part of programming. The "for" and "while" loops run a block of code repeatedly.

While Loop

A while loop will run repeatedly until a certain condition has been met.

i = 0
while i < 5:
    print(i)
    i += 1
[out]:
0
1
2
3
4

When making a while loop, we need to ensure that something changes from iteration to iteration so that the while loop will terminate, otherwise, it will run forever. Here we used i += 1 (short for i = i + 1) to make i larger after each iteration. This is the most commonly used method to control a while loop.

For Loop

A for loop will iterate over a sequence of value and terminate when the sequence has ended.

for x in [1,2,3,4,5]: print(x)
[out]:
1
2
3
4
5

We can also add if statements in a for loop. Here is a real example from our pairs trading algorithm:

stocks = ['AAPL','GOOG','IBM','FB','F','V', 'G', 'GE']
selected = ['AAPL','IBM']
new_list = []
for stock in stocks:
    if stock not in selected:
        new_list.append(stock)
print(new_list)
[out]: ['GOOG', 'FB', 'F', 'V', 'G', 'GE']

Here we iterated all the elements in the list 'stocks'. Later in this chapter, we will introduce a smarter way to do this, which is just a one-line code.

Break and continue

These are two commonly used commands in a for loop. If break is triggered while a loop is executing, the loop will terminate immediately:

stocks = ['AAPL','GOOG','IBM','FB','F','V', 'G', 'GE']
for stock in stocks:
    print(stock)
    if stock == 'FB': break
[out]:
AAPL
GOOG
IBM
FB

The continue command tells the loop to end this iteration and skip to the next iteration:

stocks = ['AAPL','GOOG','IBM','FB','F','V', 'G', 'GE']
for stock in stocks:
    if stock == 'FB': continue
    print(stock)
[out]:
AAPL
GOOG
IBM
F
V
G
GE

List Comprehension

List comprehension is a Pythonic way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence. For example, if we want to create a list of squares using for loop:

squares = []
for i in [1,2,3,4,5]:
    squares.append(i**2)
print(squares)
[out]: [1, 4, 9, 16, 25]

Using list comprehension:

foo = [1,2,3,4,5]
squares = [x**2 for x in foo]
print(squares)
[out]: [1, 4, 9, 16, 25]

Recall the example above where we used a for loop to select stocks. Here we use list comprehension:

stocks = ['AAPL','GOOG','IBM','FB','F','V', 'G', 'GE']
selected = ['AAPL','IBM']
new_list = [x for x in stocks if x not in selected]
print(new_list)
[out]: ['GOOG', 'FB', 'F', 'V', 'G', 'GE']

A list comprehension consists of square brackets containing an expression followed by a "for" clause, and possibly "for" or "if" clauses. For example:

print([(x, y) for x in [1,2,3] for y in [3,1,4] if x != y])
print([f'{x} vs {y}' for x in ['AAPL','GOOG','IBM','FB']
                     for y in ['F','V','G','GE'] if x != y])
[out]:
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
['AAPL vs F', 'AAPL vs V', 'AAPL vs G', 'AAPL vs GE', 'GOOG vs F', 'GOOG vs V', 'GOOG vs G', 'GOOG vs GE', 'IBM vs F', 'IBM vs V', 'IBM vs G', 'IBM vs GE', 'FB vs F', 'FB vs V', 'FB vs G', 'FB vs GE']

List comprehension is an elegant way to organize one or more for loops when creating a list.

Summary

This chapter has introduced logical operations, loops, and list comprehension. In the next chapter, we will introduce functions and object-oriented programming, which will enable us to make our codes clean and versatile.



QuantConnect Logo

Try the world leading quantitative analysis platform today

Sign Up

Previous: Python: Data Types and Data Structures Next: Python: Functions and Object-Oriented Programming