Part 5 Flashcards
What does the scope of a variable denote?
The area of the program from which it is accessible
If given a value outside of a function, what scope does a variable have?
Global - accessible from elsewhere in program
What is global scope?
Means variable can be accessed from anywhere in the program
However - cannot create a new variable with the same name even in a seperate function
What is local scope?
Variable only accessible from within the function it was defined in.
What Exception type is raised when a variable that does not exist is accessed?
NameError: name ‘variablename’ is not defined
Happens also when variablename has local scope but is attempted to be accessed outside of the function
What happens when you try to set the value of a global variable inside a function?
What would happen if you executed this:
def myfun():
print(x) x = 5
x = 10
myfun()
It masks the global variable - so any changes within the function will not affect the global variable
The program shown would raise an UnboundLocalError - trying to access the variable before it is assigned
What is the lifetime of a variable?
The time it will remain in existence in a program
Global variables exist for the entire duration of the program after being assigned
Local variables only for the duration of their function
What happens when a mutable object is passed as an argument to a function, then modified within the function?
The original object is actually modified. Probably because they are pointers to the objects rather than copies of
May tuples contain multiple types?
Yes.
How can we create a tuple with just one element?
mytup = (1,)
Will contain just the element 1