Midterm 1 Solutions

Question 1

The scope of a variable is roughly defined as where a variable can be read/written based on where it was defined.

In python, variables in outer scopes (for example, a global variable) are readable by inner scopes, and variables in inner scopes are not accessible from outside. We use arguments and return values in functions to pass variables between scopes. Python also has some other weird scope rules, like loop variables are useable after a loop has completed, but these need not be mentioned.

If you create a variable outside a function:

x = 5

Then you can read that variable inside functions

def myfoo():
    return x + 5

But if you redefine a variable inside a function:

def myfoo():
    x = x + 1

The x on the left hand side is a new variable visible only inside the function (whereas the x in x+1 is the global variable). Thus, it masks/shadows the global variable.

A suitable answer would be something like “a variable defined inside a function will shadow the same variable outside the function, and you’ll only be able to use the variable defined inside”.

Question 2 (Take home) / Question 3 (In class)

This is a short version, longer answers are fine!

def is_increasing(lst):
    return sorted(lst) == lst

Question 3 (Take home) / Question 2 (In class)

This is a short version based on a comprehension, longer answers are fine!

def unique_elements(input_list):
    return [x for x in input_list if input_list.count(x) == 1]