0% found this document useful (0 votes)
11 views

Functions

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Functions

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Functions

def Statements with Parameters


def hello(name):
print('Hello ' + name)
hello('Alice')
hello('Bob')

Hello Alice
Hello Bob
A parameter is a variable that an argument is stored in when a function is called.

Return Values and return Statements

In general, the value that a function call evaluates to is called the return value of the function.

A return statement consists of the following:


• The return keyword
• The value or expression that the function should return

Local and Global Scope

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

Local Scopes Cannot Use Variables in Other Local Scopes

def spam():
eggs = 99
bacon()
print(eggs)
def bacon():
ham = 101
eggs = 0

spam()

Global Variables Can Be Read from a Local Scope


def spam():
print(eggs)
eggs = 42
spam()
print(eggs)

Local and Global Variables with the Same Name

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

The global Statement

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']

spam = ["cat", "bat", "rat", "elephant"]

spam[0] spam[1] spam[2] spam[3]

Lists can also contain other list values. The values in these lists of lists can be accessed using
multiple indexes, like so:

spam = [['cat', 'bat'], [10, 20, 30, 40, 50]]


>>> spam[0]
['cat', 'bat']
>>> spam[0][1]
'bat'
>>> spam[1][4]
50

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.

Getting Sublists with Slices

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.

>>> spam = ['cat', 'bat', 'rat', 'elephant']


>>> spam[0:4]
['cat', 'bat', 'rat', 'elephant']
>>> spam[1:3]
['bat', 'rat']
>>> spam[0:-1]
['cat', 'bat', 'rat']

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']

Getting a List’s Length with len()


The len() function will return the number of values that are in a list value

>>> spam = ['cat', 'dog', 'moose']


>>> len(spam)
3

Changing Values in a List with Indexes

>>> spam = ['cat', 'bat', 'rat', 'elephant']


>>> spam[1] = 'aardvark'
>>> spam
['cat', 'aardvark', 'rat', 'elephant']
>>> spam[2] = spam[1]
>>> spam
['cat', 'aardvark', 'aardvark', 'elephant']
>>> spam[-1] = 12345
>>> spam
['cat', 'aardvark', 'aardvark', 12345]

List Concatenation and List Replication

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.

>>> [1, 2, 3] + ['A', 'B', 'C']


[1, 2, 3, 'A', 'B', 'C']
>>> ['X', 'Y', 'Z'] * 3
['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z']
>>> spam = [1, 2, 3]
>>> spam = spam + ['A', 'B', 'C']
>>> spam
[1, 2, 3, 'A', 'B', 'C']
Removing Values from Lists with del Statements

The del statement will delete values at an index in a list.

>>> spam = ['cat', 'bat', 'rat', 'elephant']


>>> del spam[2]
>>> spam
['cat', 'bat', 'elephant']
>>> del spam[2]
>>> spam
['cat', 'bat']

The in and not in Operators


You can determine whether a value is or isn’t in a list with the in and not in operators.

>>> 'howdy' in ['hello', 'hi', 'howdy', 'heyas']


True
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> 'cat' in spam
False
>>> 'howdy' not in spam
False
>>> 'cat' not in spam
True

myPets = ['Zophie', 'Pooka', 'Fat-tail']


print('Enter a pet name:')
name = input()
if name not in myPets:
print('I do not have a pet named ' + name)
else:
print(name + ' is my pet.')

The Multiple Assignment Trick


The multiple assignment trick is a shortcut that lets you assign multiple variables with the
values in a list in one line of code.

>>> cat = ['fat', 'black', 'loud']


>>> size = cat[0]
>>> color = cat[1]
>>> disposition = cat[2]

you could type this line of code:


>>> cat = ['fat', 'black', 'loud']
>>> size, color, disposition = cat
Augmented Assignment Operators

Methods
A method is the same thing as a function, except it is “called on” a value.

Finding a Value in a List with the index() Method


List values have an index() method that can be passed a value, and if that value exists in the
list, the index of the value is returned. If the value isn’t in the list, then Python produces a
ValueError error.

>>> spam = ['hello', 'hi', 'howdy', 'heyas']


>>> spam.index('hello')
0
>>> spam.index('heyas')
3
>>> spam.index('howdy howdy howdy')
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
spam.index('howdy howdy howdy')
ValueError: 'howdy howdy howdy' is not in list

When there are duplicates of the value in the list, the index of its first appearance is returned.

>>> spam = ['Zophie', 'Pooka', 'Fat-tail', 'Pooka']


>>> spam.index('Pooka')
1

Adding Values to Lists with the append() and insert() Methods

To add new values to a list, use the append() and insert() methods

>>> spam = ['cat', 'dog', 'bat']


>>> spam.append('moose')
>>> spam
['cat', 'dog', 'bat', 'moose']

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']

Removing Values from Lists with remove()


The remove() method is passed the value to be removed from the list it is called on

>>> spam = ['cat', 'bat', 'rat', 'elephant']


>>> spam.remove('bat')
>>> spam
['cat', 'rat', 'elephant']

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.

Sorting the Values in a List with the sort() Method

>>> spam = [2, 5, 3.14, 1, -7]


>>> spam.sort()
>>> spam
[-7, 1, 2, 3.14, 5]
>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']
>>> spam.sort()
>>> spam
['ants', 'badgers', 'cats', 'dogs', 'elephants']

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

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'>

Converting Types with the list() and tuple() Functions


>>> tuple(['cat', 'dog', 5])
('cat', 'dog', 5)
>>> list(('cat', 'dog', 5))
['cat', 'dog', 5]
>>> list('hello')
['h', 'e', 'l', 'l', 'o']

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)

The copy Module’s copy() and deepcopy() Functions


Python provides a module named copy that provides both the copy() and deepcopy()
functions. The first of these, copy.copy(), can be used to make a duplicate copy of a mutable
value like a list or dictionary, not just a copy of a reference.

>>> import copy


>>> spam = ['A', 'B', 'C', 'D']
>>> cheese = copy.copy(spam)
>>> cheese[1] = 42
>>> spam
['A', 'B', 'C', 'D']
>>> cheese
['A', 42, 'C', 'D']

You might also like