From CS 61A Wiki
Revision as of 19:22, 4 June 2014 by Axis (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Jump to: navigation, search

A statement is an instruction that the Python interpreter can execute. Statements do not return a value; they are simply executed.

Simple statements

A simple statement fits on one line. Simple statements may occur on a single line separated by semicolons.

Assignment statement

An assignment statement is used to bind variable names to values and to modify attributes of mutable objects.

The = operator is used:

var = val

Python also supports multiple assignment:

var1, var2 = val1, val2 # equivalent to:
                        # var1 = val1
                        # var2 = val2

An assignment is executed in the following way:

  • evaluate the right of the equals sign
  • bind the name(s) on the left to the resulting value

If a name is already bound to a value, the old value is overwritten by the new value. Example:

>>> a = 2; a = 3
>>> a # a takes on the last value it was bound to

Assignment statements in the form x = x op y can be shortened to x op= y, where op is an arithmetic operator. Example:

>>> a = 2
>>> a += 1 # equivalent to a = a + 1
>>> a


The assert statement is used as a debugging assertion. The syntax is assert expr, where expr is a boolean expression. If expr evaluates to False (i.e., the check fails), an AssertionError is thrown. Otherwise, nothing happens.

Adding another argument allows you to specify a debugging message when the check fails: assert expr, msg. Examples:

>>> x = -5
>>> assert x == -5
>>> assert x % 2 == 0, "x is not even"
Traceback (most recent call last):
AssertionError: x is not even
>>> assert x > 0
Traceback (most recent call last):


pass is a null operation—when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed.


# a class with no methods or attributes
class A:
    pass # omitting this would result in an IndentationError
# complex conditional
if condA and (condB or condC):
    pass # do nothing
    # ...


return expr leaves the current function call with expr as a return value. If expr is omitted or there is no return statement in the function, the return value is None.

return can occur only in a function definition.


>>> def fn():
...     return 3
>>> fn()


Main article: Generator


Main article: Exception


Main article: Iteration


Main article: Iteration


An import statement loads a module into the program. A module is a file containing Python definitions and statements.


>>> from operator import add
>>> add(2, 3)
>>> from functools import reduce
>>> reduce(add, [1, 2, 3])

global and nonlocal

global var tells Python to modify the binding of var in the global frame if it exists instead of creating a new binding in the current frame. Example:

>>> a = 0
>>> def fn():
...     global a
...     a += 1
>>> a
>>> fn()
>>> a

nonlocal var behaves the same, except for var in a parent (but non-global) frame. Example:

>>> def fn(x):
...     def inner():
...         nonlocal x
...         x += 1
...     inner()
...     return x
>>> fn(1)

Compound statements

Compound statements contain groups of other statements. Compound statements generally provide control flow (controlling the execution of the enclosed statements) and span multiple lines.

A compound statement consists of one or more clauses, which consists of a header and a suite. The header ends with a colon (:) and controls the suite that follows; the suite is a sequence of statements.

Conditional statements

Conditional statements are used to perform different actions depending on some boolean condition. The syntax is:

if condition1:
elif condition2:

where condition1 and condition2 are boolean expressions. If condition1 evaluates to True, its suite is executed and the rest of the compound statement is skipped. Otherwise, Python checks condition2. If that evaluates to True, the second suite is executed and the rest of the compound statement is skipped. Otherwise, the else suite is executed.

The elif and else clauses are optional, and there may be more than one elif clause.


import datetime
hour = # returns the current hour (24-hour clock)
if hour < 10:
    print("Good morning")
elif hour < 12:
    print("Soon time for lunch")
elif hour < 18:
    print("Good day")
elif x < 22:
    print("Good evening")
    print("Good night")


Main article: Iteration


Main article: Iteration


Main article: Exception

Function definition

The syntax of a function definition is:

def fn(param1, param2):

where param1 and param2 are formal parameters. They are the names that the passed in arguments will be bound to.

If parameters are of the form param = expression, the function is said to have default parameter values. When the corresponding argument is omitted in a function call, the parameter's default value is used. Example:

>>> def fn(a, b=2):
...     return a + b
>>> fn(1, 1)
>>> fn(1) # omitted b

A function definition is executed in the following way:

  • create a function object with signature name(formal parameters)
  • set the body of that function to be everything indented after the first line
  • bind the function name to the function object in the current frame

Class definition

Main article: Object-oriented programming