Statement

From CS 61A Wiki
(Redirected from Nonlocal)
Jump to: navigation, search

A statement is an instruction that the Python interpreter executes. Statements do not return a value; they are simply executed. They change the state of or control the program.

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
3

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
3

assert

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

pass

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.

Examples:

# 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
else:
    # ...

return

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.

Example:

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

yield

Main article: Generator#yield statement

raise

Main article: Exception#Raising an exception

break

Main article: Iteration#break statement

continue

Main article: Iteration#continue statement

import

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

Examples:

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

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
0
>>> fn()
>>> a
1

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

When a nonlocal variable is attempted to be rebound without using nonlocal, Python will raise the following exception: UnboundLocalError: local variable referenced before assignment. Example:

>>> def fn(x):
...     def inner():
...         x += 1
...     return inner
... 
>>> fn(1)()
Traceback (most recent call last):
  ...
UnboundLocalError: local variable 'x' referenced before assignment

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.

Anatomy of a compound statement

Conditional statements

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

if condition1:
    ...
elif condition2:
    ...
else:
    ...

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.

Example:

import datetime
hour = datetime.datetime.now().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")
else:
    print("Good night")

A conditional statement can be a one-liner through Python's version of the ternary operator. The syntax is: expression1 if condition else expression2. If condition evaluates to True, expression1 is returned, otherwise expression2 is returned. Examples:

>>> x = -3
>>> "x is negative" if x < 0 else "x is nonnegative"
'x is negative'
>>> x = 0
>>> "x is negative" if x < 0 else ("x is zero" if x == 0 else "x is positive") # chained
'x is zero'

while

Main article: Iteration#While loop

for

Main article: Iteration#For loop

try

Main article: Exception#Handling an 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)
2
>>> fn(1) # omitted b
3

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

Sources