Python Syntax Cheatsheet

Inspired by Jake VanderPlas' A Whirlwind Tour of Python.

Basics

In [1]:
# Print statement
print("Hello World!")  # Python 3 - No parentheses in Python 2

# Optional separator
print(1, 2, 3)  # 1 2 3
print(1, 2, 3, sep='--')  # 1--2--3

# Variables (dynamically typed)
mood = "happy"  # or 'happy'

print("I'm", mood)
Hello World!
1 2 3
1--2--3
I'm happy

String formatting

In [49]:
# https://realpython.com/python-f-strings/
# https://cito.github.io/blog/f-strings/

name = "Garance"
age = 11

message = "My name is %s and I'm %s years old." % (name, age)  # Original language syntax
print(message)
message = "My name is {} and I'm {} years old.".format(name, age)  # Python 2.6+
print(message)
message = f"My name is {name} and I'm {age} years old."  # Python 3.6+
print(message)
My name is Garance and I'm 11 years old.
My name is Garance and I'm 11 years old.
My name is Garance and I'm 11 years old.

Numbers and arithmetic

In [98]:
# Type: int
a = 4

# Type: float
b = 3.14

a, b = b, a
print(a, b)  # 3.14 4

print(13 / 2)  # 6.5
print(13 // 2)  # 6

# Exponential operator
print(3 ** 2)  # 9
print(2 ** 3)  # 8
3.14 4
6.5
6
9
8

Lists

In [80]:
countries = ["France", "Belgium", "India"]
print(len(countries))  # 3
print(countries[0])  # "France"
print(countries[-1])  # "India"

# Add element at end of list
countries.append("Ecuador")

print(countries)
3
France
India
['France', 'Belgium', 'India', 'Ecuador']

Conditions and loops

In [55]:
for i in range(10):
    if i % 2 == 0:
        print(f"{i} is even")
    else:
        print(f"{i} is odd")
0 is even
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd

Functions

In [70]:
def square(x):
    """ Returns the square of x """
    
    return x ** 2

# Print function docstring
help(square)

print(square(0))  # 0
print(square(3))  # 9
Help on function square in module __main__:

square(x)
    Returns the square of x

0
9

Default function parameters

In [82]:
def fibonacci(n, a=0, b=1):
    """ Returns a list of the n first Fibonacci numbers"""

    l = []
    while len(l) < n:
        a, b = b, a + b
        l.append(a)
    return l

print(fibonacci(7))  # [1, 1, 2, 3, 5, 8, 13]
[1, 1, 2, 3, 5, 8, 13]

Lambda (anonymous) functions

In [74]:
add = lambda x, y: x + y

print(add(1, 2))  # 3
3

Modules and packages

In [94]:
# Importing all module content into a namespace
import math
print(math.cos(math.pi))  # -1.0

# Aliasing an import
import numpy as np
print(np.cos(np.pi))  # -1.0

# Importing specific module content into local namespace
from math import cos, pi
print(cos(pi))  # -1.0

# Importing all module content into local namespace (use with caution)
from math import *
print(sin(pi) ** 2 + cos(pi) ** 2)  # 1.0
-1.0
-1.0
-1.0
1.0