Mutation:

Python allows us to change the values of variables
The following Python program is valid:
x = “a”
x = 100
x = 2 * x - 1

Local vs Global variables

Variables defined inside a function are called local variables
– Local variables only can be mutated inside the function they are defined in

Variables defined outside a function are called global variables
– Global variables cannot be mutated inside any functions in CS116.

###Correct Usage of Global Variables: tax_rate = 0.13
def total_owed(amount):
return amount * (1+tax_rate)

This Causes an Error:

grade = 87
def increase_grade(inc):
      grade = grade + inc increase_grade(5)

Mutating Parameters

Consider the program:

def add1(n):
      n = n + 1
return n

starter = 0
y = add1(starter)

The value of n is changed locally, but the value of starter is not changed.The mutation of n is a local mutation only.
Even if starter was called n, the same behaviour would be observed.

Tip: Python expects each line of code to be an entire statement
Can be a problem e.g. due to indentation
If a statement is not done, use a \ (backslash) character to show it continues on next line

Built-in type Bool:

Very similar to Scheme

v1 and v2
True only if both v1, v2 are True
v1 or v2
False only if both v1, v2 are False
not v
True if v is False , otherwise False

Like Scheme, Python uses Short-Circuit evaluation
Stop evaluating as soon as answer is known
or: stop when one argument evaluates to True
and: stop when one argument evaluates to False

Example of an If Statement

if test: true_action_1 … true_action_K

def double_positive(x):
      result = x
      if x > 0:
            result = 2*x
      return result

Mutation | Home