Basics

We’ll cover basic Python syntax by example.

Many of these topics will be covered in more depth in other sections. The purpose here is to have a quick reference for jumping into writing Python code.

Hello World

print("Hello World")
Hello World

Variable Assignment

Variables do not need to be declared, and are not typed

x = 1
print(x)
x = 'a'
print(x)
1
a

Comments

Comments begin with the pound (#) symbol

x = 1 # assign the variable x
print(x) # print the variable x
1

Lists

A Python list is specified using square brackets []

x = [1, 2, 3]
print(x)
[1, 2, 3]

You can access elements using square brackets [] as well. Python is 0-indexed, so the first index is x[0]

print(x[0])
1

the length of the list can be obtained using len()

print(len(x))
3

Functions

Functions are defined using the def keyword, followed by the function name, arguments, and then a colon :. You can return values from a function using return

Scope is determined by indentation (4 spaces).

def square(x):
    # returns the square of x
    return x * x

square(2)
4

Functions can take multiple arguments, and keyword arguments. They can return mutiple values.

def f(x,y, a=2):
    # a is a keyword argument
    return x + y, a * x

w, z = f(1,3, a=1)
print(w)
print(z)
4
1

Strings

Strings in Python can be specified with either single quotes ', or double quotes ". You shouldn’t mix which one you are using

a = 'hello'
b = "hello"
a == b
True

Multi-line strings are specified with triple quotes - either ''' or """

a = """A mulit-
line string"""

print(a)
A mulit-
line string

printf-style formating

Strings can be formatted using a syntax similar to C’s printf.

s = "value = %d" % 1
s
'value = 1'
s = "name: %s, age: %d, weight: %.1f" % ("Bob", 20, 160.0)
s
'name: Bob, age: 20, weight: 160.0'

The format method

strings can be formatted using the format method, which will fill-in curly braces {}:

x = 1
print("x = {}".format(x))
x = 1

You can use the format arguments in multiple positions or in different orders by specifying the index in the braces:

x = 2
print("{0} * {0} = {1}".format(x, square(x)))
2 * 2 = 4

You can also use keyword arguments in format, which can be very helpful in complicated situations

print("{name1} said \"hello {name2}!\", and {name2} said \"hello {name1}!\"".format(name1="Alice", name2="Bob"))
Alice said "hello Bob!", and Bob said "hello Alice!"

f-strings

In Python 3.6 format strings, or f-strings were introduced. These give another option for formating strings, which is easy to read - similar to using keyword arguments with format, but names are pulled from the environment. F-strings are denoted with an f before the first quote, as in f'...'

name = "Alice"
s = f"Hello, {name}!"
print(s)
Hello, Alice!

A good reference for format string syntax is the documentation.

Documentation

You can read documentation for functions and classes using help():

help(print)
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

If you’re running ipython (either the REPL, or in a Jupyter notebook), you can use ?

print?

Documentation is written in docstrings. Right now, you see that the square function above does not have documentation aside from the call signature.

help(square)
Help on function square in module __main__:

square(x)

Docstrings are written in a string at the beginning of a function

def square(x):
    """
    returns the square of the input x
    """
    return x * x
help(square)
Help on function square in module __main__:

square(x)
    returns the square of the input x

Logic and Control Flow

For control flow, Python uses if, elif and else

The True and False keywords are used logically.

In Python, you should use and, or, and not for logical epressions.

def sign(x):
    """
    returns the sign of a number.
    """
    if x < 0:
        return -1
    elif x > 0:
        return 1
    else:
        return 0
    
print(sign(2), sign(-3), sign(0))
1 -1 0
if True:
    print(True)

if False:
    print(False)
True
if True or False:
    print(True or False)
True
if not False:
    print("hello")
hello

Iteration

Iteration can be done in for-loops or while loops. These use the keywords for and while.

Again, indentation determines scope.

break will break out of the loop.

continue will jump directly to the next iteration of the loop

for i in range(5):
    print(i)
0
1
2
3
4
n = 0
while True:
    if n == 5:
        break
    print(n)
    n = n + 1
0
1
2
3
4

You can also iterate over a variety of objects such as lists using in

x = [1,2,'a']
for i in x:
    print(i)
1
2
a

Classes and Objects

You can define custom classes using the class keyword. To obtain an instance of the class, you need to define the __init__ method.

class MyComplex():
    def __init__(self, re, im):
        self.re = re
        self.im = im
        
z = MyComplex(1, 2)
print(f"{z.re} + {z.im}i")
1 + 2i

A class is a recipe for creating objects. Everything in Python is an object, whose type is a class. You can find about an object’s type using type()

print(type(z))
print(type(square))
print(type(1))
<class '__main__.MyComplex'>
<class 'function'>
<class 'int'>

Packages

Packages provide functionality not available in standard Python. One such example is numpy, which provides a standard numerical array faster than Python lists.

First, you should make sure a package is installed. From a terminal:

$ conda install numpy

Now, from Python, you can import the package

import numpy

Functions and classes in a package are imported into a namespace, which by default has the same name as the package. For example, numpy has an array class, which you can access using numpy.array

a = numpy.array([1,2,3])
print(a)
type(a)
[1 2 3]
numpy.ndarray

You can change the namespace during import using the as keyword. For example, numpy is often imported as np

import numpy as np
a = np.array([1,2,3]) # now we use the np namespace
a
array([1, 2, 3])

Exercises

Exercise 1

Write a function that computes the sum of cubes of two numbers \(f: (x,y) \mapsto x^3 + y^3\)

# Your code here
def add_cubes(x, y):
    sum = x**3 + y**3
    return sum 

Exercise 2

Use Python to compute the sum \(1 + 2 + \dots + 100\)

# Your code here
def add():
    sum = 0
    for num in range(1,100):
        sum += num
    return sum

Exercise 3

Write a function that will take an integer n as input, and return the sum \(1 + 2 + \dots + n\)

# Your code here
def add_until_n(n):
    sum = 0
    for num in range(1, n):
        sum += num
    return sum

Exercise 4

Write a function that will take an integer n as input and print “even” if n is even, and “odd” if n is odd.

Hint: Look up the modulo operator.

# Your code here
def is_even(n):
    if n%2 == 0:
        print("even")
    else:
        print("odd")