Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Basics

Open in Colab

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

Variable Assignment

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

Comments

Comments begin with the pound (#) symbol

Lists

A Python list is specified using square brackets []

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

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

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).

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

Strings

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

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

printf-style formating

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

The format method

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

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

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

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'...'

A good reference for format string syntax is the documentation.

Documentation

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

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

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

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

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.

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

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

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.

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()

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

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

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

Exercises

Exercise 1

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

Notebook Cell

Exercise 2

Use Python to compute the sum 1+2+⋯+1001 + 2 + \dots + 100.

Notebook Cell

Exercise 3

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

Notebook Cell

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.

Notebook Cell