Basics

Variables

The symbol = assigns values to variables. In Python, variables are not constant, that is, they can be reassigned.

msg = "Hello World!"  # Assign to the variable `msg`
print(msg)  # Prints `Hello World!`
msg = "Hello Again!"  # Reassign
print(msg)  # Prints `Hello Again!`

Arithmetic

Arithmetic is done with the symbols +, -, *, /, **, // and %. The symbol ** is for exponentiation. The symbol // is for integer division. The symbol % is for remainder after division.

print(1 + 2)  # Addition, prints `3`
print(5 - 3)  # Subtraction, prints `2`
print(4 * 2)  # Multiplication, prints `8`
print(8 / 4)  # Division, prints `2.0`
print(7 // 3)  # Floor division, prints `2`
print(7 % 3)  # Modulus, prints `1`

Containers

A list is a mutable linearly ordered collection of objects. Lists are defined with square brackets []. Entries are accessed and reassigned by indexing with square brackets []. The method append adds an object to the end. The function len returns the number of elements.

nums = [1, 2, 3]
print(nums[1])  # Prints `2`
nums[1] = 9  # nums = [1, 9, 3]
nums.append(4)  # nums = [1, 9, 3, 4]
nums = nums + [5, 6]  # nums = [1, 9, 3, 4, 5, 6]
len(nums)  # 6

A tuple is an immutable linearly ordered collection of objects. It does not have methods like append. Tuples are defined with parentheses ().

point = (1, 2)
print(point[0])  # Prints `1`
print(len(point))  # Prints `2`
point[0] = 3  # Type error

A dictionary is a mutable collection of key-value pairs. Dictionaries are defined with curly braces {} and colons to separate pairs.

ages = {'Alice': 30, 'Bob': 25}
print(ages['Alice'])  # Prints `30`
ages['Alice'] = 31  # Updates Alice's age to 31
ages['Charlie'] = 20  # Adds a new key-value pair for Charlie
del ages['Bob']  # Removes Bob from the dictionary
print(len(ages))  # Prints `2`

Lists, tuples and dictionaries are the most common containers. Another built-in container is the set, which is an unordered collection of unique elements. The library collections has additional containers. The library numpy is used for arrays such as matrices.

Functions

A function is a block of code that may take arguments, may return a value and can be called multiple times. Functions are denoted by the keyword def and an indented body.

def square(x):
    return x * x

print(square(3))  # Prints `9`

If a function does have an explicit return statement, then it returns None by default. A function that does not return None is proper. A function that returns None is improper. What a function does separately from its return is a side effect.

def print_square(x):
    print(x * x)
    # No explicit return

print(print_square(3))  # Prints 9 and then `None`

Functions are useful for compartmentalization. Even if a function is only called once, it is easier to debug, read and maintain code that is broken into functions.