Download Python - e-Learning

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Python
#4 - Functions
Functions


A function is a block of organized, reusable code that is used
to perform a single, related action.
Functions provide better modularity for your application and a
high degree of code reusing.
Defining Functions with def
Function name and its arguments.
Function definition begins with def
def get_final_answer(filename):
"""Documentation String"""
line1
Read documentation using
>>> help(<function name>)
Colon.
line2
return total_counter
...
First line with less
indentation is considered to be outside
of the function definition.
‘return’ indicates the
value to be sent back to the caller.
Calling a Function
>>> def myfun(x, y):
return x * y
>>> myfun(3, 4)
12
4
Example
>>> def greet():
return 'Good Evening'
>>> greet()
'Good Evening'
>>> temp = greet()
>>> print(temp)
Good Evening
>>> temp
'Good Evening'
Functions without returns
 All functions in Python have a return value
 even if no return line inside the code.
>>> def myfun(x,y):
print(x*y)
 Functions without a return return the
special value
None.
 None is a special constant in the
language.
 None is equivalent to False.
 The interpreter doesn’t print None
>>> myfun(2,1)
2
>>> z = myfun(2,1)
2
>>> z
>>> print(z)
None
6
Every function returns something
def sign(num):
if num > 0:
return 1
elif num == 0:
return 0
# else:
# return -1
print sign(3)
1
print sign(-9)
None
If the function doesn't return
a value, Python returns None
Yet another reason why
commenting out blocks of code
is a bad idea...
Functions are objects in Python
 Functions can be used just like any other data
 They can be
 Arguments to function
 Return values of functions
 Assigned to variables
 Parts of tuples, lists, etc
>>>
… def myfun(x):
return x*3
>>> def apply(q, x):
return q(x)
>>> apply(myfun, 7)
21
8
Variable scope




When writing functions it is
important to understand scope.
Scope refers to the area in a
program where a variable is
defined.
Normally, a variable is defined
after it has been assigned a value.
You cannot reference a variable
until it has been assigned a value.
>>> p = p+1
Traceback (most recent call last):
File "<pyshell#72>", line 1, in <module>
p = p+1
NameError: name 'p' is not defined
Variable scope: use the LEGB rule

Local -> Enclosed -> Global -> Built-in
•Local: can be inside a function (or class method, for example).
•Enclosed can be enclosing function, e.g., if a function is
wrapped inside another function.
•Global refers to the uppermost level of the executing script
itself, and
•Built-in are special names that Python reserves for itself
Global Scope
>>> def myfun():
print(x)
return x+1
>>> x = 10
>>> myfun()
10
11
... and local variables
>>> def myfun2():
y=2
print(y)
return y+2
>>> print(y)
Traceback (most recent call last):
File "<pyshell#42>", line 1, in <module>
print(y)
NameError: name 'y' is not defined
>>> myfun2()
2
4
Scope: EXAMPLE
The global keyword



A global variable can
be declared in a
function using the
keyword global
fun2() contains a
global declaration of x
Caution: Must call the
function!
>>> def fun2():
global zz
zz = 100
>>> fun2()
>>> zz
100
>>> def fun2():
global tt
tt = 100
>>> tt
Traceback (most recent call last):
File "<pyshell#68>", line 1, in <module>
tt
NameError: name 'tt' is not defined
Scope again!
Example
>>> x = 99
>>> y = 17
>>> def fun(x):
y=100
print(x,y)
>>> fun(77)
77 100
>>> print(x,y)
99 17
By value ? By reference?
Most languages (C, Java, ...) distinguish “passing by value” and “passing by reference”.
In Python, such a distinction is somewhat artificial, and it is a bit subtle whether your
variables are going to be modified or not. Fortunately, there exist a rule.
1.
2.
3.
Parameters to functions are references to objects, which are passed by value.
When you pass a variable to a function, python passes the reference to the object to
which the variable refers (the value). Not the variable itself.
If the value passed in a function is immutable, the function does not modify the
caller’s variable. If the value is mutable, the function may modify the caller’s variable
in-place.
By value ? By reference? The run time stack

The run-time stack is a data structure that is used by Python to execute programs.
Python needs this run-time stack to maintain information about the state of your
program as it executes.

A stack is a data structure that lets you push and pop elements.

–
–
You push elements onto the top of the stack and you pop elements from the top of the stack.
Think of a stack of trays. You take trays off the top of the stack in a cafeteria.

Stacks can be created to hold a variety of different types of elements. The run-time
stack is a stack of activation records.

An activation record is an area of memory that holds a copy of each variable that is
defined in the local scope of a function while it is executing.
Function parameters
>>> def greet(name):
answer = 'Hello' + name
return answer
>>> greet('master')
'Hellomaster'
Give them parameters
def greet(name):
answer = 'Hello, ' + name
return answer
'doctor'
temp
temp = 'doctor'
stack
value
Give them parameters
name
def greet(name):
answer = 'Hello, ' + name
return answer
'doctor'
temp
temp = 'doctor'
result = greet(temp)
stack
Each function call creates a new stack frame
value
Give them parameters
name
def greet(name):
answer = 'Hello, ' + name
return answer
answer
'doctor'
temp
'Hello, doctor'
stack
value
temp = 'doctor'
result = greet(temp)
Each function call creates a new stack frame
Give them parameters
def greet(name):
answer = 'Hello, ' + name
return answer
temp = 'doctor'
result = greet(temp)
'doctor'
temp
'Hello, doctor'
result
stack
value
Each function call creates a new stack frame
def add(a):
b=a+1
return b
def double(c):
d = 2 * add(c)
return d
stack
value
Each function call creates a new stack frame
10
def add(a):
b=a+1
return b
def double(c):
d = 2 * add(c)
return d
val = 10
val
stack
value
Each function call creates a new stack frame
def double(c):
d = 2 * add(c)
return d
val = 10
result = double(val)
10
double
def add(a):
b=a+1
return b
c
val
stack
value
def double(c):
d = 2 * add(c)
return d
val = 10
result = double(val)
add
def add(a):
b=a+1
return b
a
double
Each function call creates a new stack frame
c
10
val
stack
value
def double(c):
d = 2 * add(c)
return d
val = 10
result = double(val)
print result
add
def add(a):
b=a+1
return b
a
b
10
double
Each function call creates a new stack frame
c
11
val
result
stack
value
Each function call creates a new stack frame
def double(c):
d = 2 * add(c)
return d
val = 10
result = double(val)
print result
10
double
def add(a):
b=a+1
return b
c
d
val
result
22
stack
value
Each function call creates a new stack frame
def add(a):
b=a+1
return b
def double(c):
d = 2 * add(c)
return d
val = 10
result = double(val)
print result
10
val
result
22
stack
value
Each function call creates a new stack frame
def add(a):
b=a+1
return b
def double(c):
d = 2 * add(c)
return d
val = 10
result = double(val)
print result
22
10
val
result
22
stack
value
Only see variables in the current and global
frames
temp = 'doctor'
result = greet(temp)
greet
name
global
def greet(name):
temp = 'Hello, ' + name
return temp
temp
temp
stack
'Hello, doctor'
'doctor'
value
Only see variables in the current and global
frames
def greet(name):
temp = 'Hello, ' + name
return temp
global
temp = 'doctor'
result = greet(temp)
print result
Hello, doctor
'Hello, doctor'
temp
'doctor'
result
stack
value
Example
Can define default parameter values
def adjust(value, amount=2.0):
return value * amount
Default Values for Arguments
 You can provide default values for a function’s arguments
 These arguments are optional when the function is called
>>> def myfun(b, c=3, d=“hello”):
return b + c
>>> myfun(5,3,”hello”)
>>> myfun(5,3)
>>> myfun(5)
All of the above function calls return 8.
3
6
Can define default parameter values
def adjust(value, amount=2.0):
return value * amount
print(adjust(5))
10
Can define default parameter values
def adjust(value, amount=2.0):
return value * amount
print(adjust(5))
10
print(adjust(5, 1.001))
5.005
Keyword Arguments
 Functions can be called
>>> def myfun (a, b, c):
return a-b
>>> myfun(2, 1, 43)
1
>>> myfun(c=43, b=1, a=2)
1
>>> myfun(2, c=43, b=1)
1
with arguments out of order
 These arguments are
specified in the call
 Keyword arguments can be
used for a final subset of
the arguments.
3
9
Keyword and positional arguments
>>> myfun(1,b=2,c=43)
-1
>>> myfun(b=2,1,c=3)
SyntaxError: positional argument follows keyword
argument
Example. Root of <equation> . i^4 -93i -19620
Example. Root of <equation>
Example. Fibonacci
Example.
Summing up all elements in a tuple
>>> t=(1.5 ,2.0 ,3.1 ,6.4 , -4.7 ,7.1 , -0.01)
>>> s=0
>>> for x in t:
... s += x
...
>>> print s
Example
>>> t=(1.5 ,2.0 ,3.1 ,6.4 , -4.7 ,7.1 , -0.01)
>>> sum(t)
Lambda Notation


Functions can be defined without giving them names.
This is most useful when passing a short function as an
argument to another function.
>>> apply(lambda z: z * 4)



Argument to apply() is an unnamed function that takes
one input and returns the input multiplied by four.
Note: only single-expression functions can be defined
using this lambda notation.
Lambda notation has a rich history in CS research and the
design of many current programming languages.
4
6
Example. f (x, y) = x+2y
Example
Default argument value
!!!!
>>> f=lambda x, y=0, z=0, w : x+2*y+3*z+4*w
SyntaxError: non-default argument follows default argument
>>> f=lambda x, y=0, z=0, w=1 : x+2*y+3*z+4*w
>>> f=lambda x, y=0, z : x+2*y+3*z+4*w
SyntaxError: non-default argument follows default argument
Functions call ... lambda