Functions
Functions
Hello Alice
Hello Bob
A parameter is a variable that an argument is stored in when a function is called.
In general, the value that a function call evaluates to is called the return value of the function.
Parameters and variables that are assigned in a called function are said to exist in that
function’s local scope.
Variables that are assigned outside all functions are said to exist in the global scope.
A local scope is created whenever a function is called. Any variables assigned in this function
exist within the local scope. When the function returns, the local scope is destroyed, and these
variables are forgotten
def spam():
eggs = 99
bacon()
print(eggs)
def bacon():
ham = 101
eggs = 0
spam()
def spam():
eggs = 'spam local'
print(eggs) # prints 'spam local'
def bacon():
eggs = 'bacon local'
print(eggs) # prints 'bacon local'
spam()
print(eggs) # prints 'bacon local'
eggs = 'global'
bacon()
print(eggs) # prints 'global'
bacon local
spam local
bacon local
global
If you need to modify a global variable from within a function, use the global statement.
def spam():
global eggs
eggs = 'spam'
eggs = 'global'
spam()
print(eggs)
spam
Because eggs is declared global at the top of spam() u, when eggs is set to 'spam' v, this
assignment is done to the globally scoped spam. No local spam variable is created.
There are four rules to tell whether a variable is in a local scope or global scope:
1. If a variable is being used in the global scope (that is, outside of all functions), then it is
always a global variable.
2. If there is a global statement for that variable in a function, it is a global variable.
3. Otherwise, if the variable is used in an assignment statement in the function, it is a local
variable.
4. But if the variable is not used in an assignment statement, it is a global variable.
def spam():
global eggs
eggs = 'spam' # this is the global
def bacon():
eggs = 'bacon' # this is a local
def ham():
print(eggs) # this is the global
eggs = 42 # this is the global
spam()
print(eggs)
Exception Handling
you want the program to detect errors, handle them, and then continue to run.
def spam(divideBy):
return 42 / divideBy
print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))
Errors can be handled with try and except statements. The code that could potentially have
an error is put in a try clause. The program execution moves to the start of a following
except clause if an error happens.
def spam(divideBy):
try:
return 42 / divideBy
except ZeroDivisionError:
print('Error: Invalid argument.')
print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))
21.0
3.5
Error: Invalid argument.
None
42.0
Lists
The List Data Type
A list is a value that contains multiple values in an ordered sequence.
A list value looks like this: ['cat', 'bat', 'rat', 'elephant'].
Values inside the list are also called items. Items are separated with commas
[1, 2, 3]
['cat', 'bat', 'rat', 'elephant']
['hello', 3.1415, True, None, 42]
spam = ['cat', 'bat', 'rat', 'elephant']
Lists can also contain other list values. The values in these lists of lists can be accessed using
multiple indexes, like so:
Negative Indexes
The integer value -1 refers to the last index in a list, the value -2 refers to the second-to-last
index in a list, and so on.
spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[-1]
'elephant'
>>> spam[-3]
'bat'
>>> 'The ' + spam[-1] + ' is afraid of the ' + spam[-3] + '.'
'The elephant is afraid of the bat.
a slice can get several values from a list, in the form of a new list. A slice is typed between
square brackets, like an index, but it has two integers separated by a colon.
In a slice, the first integer is the index where the slice starts. The second integer is the index
where the slice ends.
As a shortcut, you can leave out one or both of the indexes on either side of the colon in the
slice. Leaving out the first index is the same as using 0, or the beginning of the list. Leaving
out the second index is the same as using the length of the list, which will slice to the end of
the list.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[:2]
['cat', 'bat']
>>> spam[1:]
['bat', 'rat', 'elephant']
>>> spam[:]
['cat', 'bat', 'rat', 'elephant']
The + operator can combine two lists to create a new list value in the same way it combines
two strings into a new string value. The * operator can also be used with a list and an integer
value to replicate the list.
Methods
A method is the same thing as a function, except it is “called on” a value.
When there are duplicates of the value in the list, the index of its first appearance is returned.
To add new values to a list, use the append() and insert() methods
The previous append() method call adds the argument to the end of the list. The insert()
method can insert a value at any index in the list.
>>> spam = ['cat', 'dog', 'bat']
>>> spam.insert(1, 'chicken')
>>> spam
['cat', 'chicken', 'dog', 'bat']
The del statement is good to use when you know the index of the value you want to remove
from the list. The remove() method is good when you know the value you want to remove
from the list.
You can also pass True for the reverse keyword argument to have sort() sort the values in
reverse order
>>> spam.sort(reverse=True)
>>> spam
['elephants', 'dogs', 'cats', 'badgers', 'ants']
If you need to sort the values in regular alphabetical order, pass str.lower for the key keyword
argument in the sort() method call.
>>> spam = ['a', 'z', 'A', 'Z']
>>> spam.sort(key=str.lower)
>>> spam
['a', 'A', 'z', 'Z']
The tuple data type is almost identical to the list data type, except in two ways. First, tuples
are typed with parentheses, ( and ), instead of square brackets, [ and ].
>>> eggs = ('hello', 42, 0.5)
>>> eggs[0]
'hello'
>>> eggs[1:3]
(42, 0.5)
>>> len(eggs)
3
Tuples cannot have their values modified, appended, or removed.
>>> eggs = ('hello', 42, 0.5)
>>> eggs[1] = 99
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
eggs[1] = 99
TypeError: 'tuple' object does not support item assignment
If you have only one value in your tuple, you can indicate this by placing a trailing comma
after the value inside the parentheses. Otherwise, Python will think you’ve just typed a value
inside regular parentheses.
>>> type(('hello',))
<class 'tuple'>
>>> type(('hello'))
<class 'str'>
References
When you assign a list to a variable, you are actually assigning a list reference to the variable.
A reference is a value that points to some bit of data, and a list reference is a value that points
to a list.
>>> spam = [0, 1, 2, 3, 4, 5]
>>> cheese = spam
>>> cheese[1] = 'Hello!'
>>> spam
[0, 'Hello!', 2, 3, 4, 5]
>>> cheese
[0, 'Hello!', 2, 3, 4, 5]
Passing References
References are particularly important for understanding how arguments get passed to functions.
When a function is called, the values of the arguments are copied to the parameter variables.
For lists this means a copy of the reference is used for the parameter.
def eggs(someParameter):
someParameter.append('Hello')
spam = [1, 2, 3]
eggs(spam)
print(spam)