W13 Flashcards
What is the scope of Local variables?
Inside the function they are defined in.
What does a variable scope mean?
The parts of the program in which the variable is visible (accessed or modified).
Are parameter variables local or global?
Local
What type of errors will occur when using a variable out of its scope?
A compiler error
Can two different local variables have the same name and different values?
Yes
Variables defined outside of functions are considered as what type of variables?
Global variables
Global variables can be visible (accessed and modified) by what functions?
A global variable is visible to all functions that are defined after it.
How can you create or modify a global variable inside a function?
Using the keyword “global”. Otherwise, instead of accessing the global variable, a local variable will be created with the same global variable name
What are the Python collections?
Give an example
Collections are
containers that store data, such as Lists.
What operator do you use to access a list element?
The subscript operator [ ].
What operator do you use to create a list element?
The square brackets [ ].
What operator do you use to print, access or modify a part of a list?
The slice operator [ n1 : n2 ]
list[ : 6 ], what indexes will be printed?
from 0 to 5
list[ 6 : ], what indexes will be printed?
from 6 to last index
list[ 3 : 9 ], what indexes will be printed?
from 3 to 8
You can assign new values to a slice.
Ex:
List [ 2 : 5 ] = [11, 21, 88]
True or False?
True
list[-4]= equals what index???
list[-1]=equals what index???
list[-4] = list[last index - 3] or list[len(list)-4]
list[-1] = list[last index - 0] or list[len(list)-1]
What type of errors will occur when accessing a non-existing list element?
A run-time error:
IndexError: list index out of range
A list variable contains a “reference” to the list content?
True or False?
True list_name (list variable)= [ content] (reference)--> which is the list's location in the memory
What is Aliasing?
Aliasing is when two or more variables reference the same memory location.
The second variable is an alias for the first because both variables reference the same list
s = [ 3, 4 , 8]
s=r
r[0]=10
print(s)
10, 4 , 8
When passing a ‘list variable’ to a function’s parameter, modifying the parameter will not affect the original list?
True or False?
False.
This is called as ‘ Variables call by reference’.
Therefore, instead of modifying the parameter, pass the parameter to a new variable then do what you want.
Or, use ‘ Variables call by value’
A Python function can mutate the contents of a list in the calling function because it receives a reference to the list
—the parameter variable becomes an alias for the original list.
True or False?
True.
How to add elements to a list?
list.append()