420 likes | 520 Views
LING 408/508: Computational Techniques for Linguists. Lecture 3 8/24/2012. Office hours. My schedule will not be finalized until September Until then, office hours are by appointment only But many times are available: M, W 11-12, 1-3 T, Th 12-1, 2-3
E N D
LING 408/508: Computational Techniques for Linguists Lecture 3 8/24/2012
Office hours • My schedule will not be finalized until September • Until then, office hours are by appointment only • But many times are available: • M, W 11-12, 1-3 • T, Th 12-1, 2-3 • And I will likely be in my office anyway at: • M, W 11-12 • T, Th 2-3
Outline • Functions • Namespaces and scopes • Built-in functions and modules • Short assignment #2
Compute the area of some circles pi = 3.14159 radius1 = 5 area = pi * radius1**2 radius2 = 3 area = pi * radius2**2 radius3 = 4 area = pi * radius3**2 • This is getting cumbersome Area = πr2
Code reuse • Code that is executed many times can be packaged together within a function def area_of_circle(radius): area = 3.14159 * radius**2 return area
Function syntax keyword def to declare a function def area_of_circle(radius): area = 3.14159 * radius**2 return area function parameters function name } body of function return statement
Examples of function syntax One parameter, returns the value of a variable def area_of_circle(radius): area = 3.14159 * radius**2 return area def calculate_tax(price, tax_rate): return price * tax_rate def say_hello(): print('hello') • Remarks: • Name of function follows keyword def • Optional comma-separated list of function parameters • Function body: indented portion • return statement is optional Two parameters, returns the result of an expression No parameters, no return statement
Indentation for function body • Amount of indentation must be consistent def f(): a = 3 b = 4 def g(): a = 3 b = 4 def h(): # cannot do this: different indentation a = 3 b = 4
Calling a function • A function definition by itself does not compute anything • Need to call the function • Supply values to the parameters of the function • Perform the computations in the body of the function • Return computed values (if any) to the caller
Calling a function: example 5 3 def area_of_circle(radius): area = 3.14159 * radius**2 return area radius1 = 5 radius2 = 3 # call function, # assign return value to variable area1 = area_of_circle(radius1) # 78.53975 area2 = area_of_circle(radius2) # 28.27431 5 3 28.27431 78.53975 78.53975 28.27431 • Function call: • Supply values to function parameters • Compute body of function • Return computed values (if any) to caller 5 78.53975 28.27431 3
Order of execution again • Code is executed from top to bottom • Function must be defined before it can be called • Can’t do this: print(area_of_circle(6)) def area_of_circle(radius): return 3.14159 * radius**2
Parameters vs. arguments • Technically speaking: • A parameter is the name of a variable in a function definition def area_of_circle(radius): • An argument is a value passed to a function in a function call radius1 = 5 area1 = area_of_circle(radius1) • But the two terms are often used interchangeably
Nested function calls def add(a, b): return a + b def multiply(c, d): return c * d print(multiply(add(5, 6), 2) # computes (5 + 6) * 2 • Evaluation sequence: print(multiply(add(5, 6), 2)) #print(multiply(5+6, 2)) print(multiply(11, 2)) #print(11*2) print(22)
Function parameters: default values (advanced) >>> def f(x, y=7): return x + y >>> f(3) # y not specified, use default value 10 >>> f(3, 4) # overrides value for y 7
Keyword arguments in function call: call by specifying variable names(advanced) >>> def f(x, y): return x - y >>> f(x=1, y=4) -3 >>> f(y=4, x=1) -3 >>> f(4, 1) 3
Multiple return values • Functions can return more than one value >>> def f(): return 1, 2, 3 >>> (a, b, c) = f() # same as (a,b,c) = (1,2,3) >>> a 1 >>> b 2 >>> c 3 >>> a, b, c = f() # same
Return value of None >>> def f(): print('hello') >>> f() 'hello' >>> a = f() 'hello' >>> a None • None is the return value of a function when no explicit return value is specified • We’ll see this again when we get to lists
Outline • Functions • Namespaces and scopes • Built-in functions and modules • Short assignment #2
Namespaces and scopes • Namespace: portion of code in which variable names are available for use • Global namespace • Function namespace • Scope of a variable: the namespace or portion of code in which a variable and its value can be accessed • Determines how to look up the value of a variable
Example a = 1 b = 2 x = 3 # scope of x: here and below print(a + b) print(x) # look up value of x in its scope
A function creates a new namespace, limited to the body of the function def myfunc(): x = 3 # scope of x is local to # the function body print(x) # looks up x in its scope myfunc() # calls myfunc, prints 3 print(x) # error, x is undefined
Global namespace x = 7 # declare in global namespace def myfunc(): print(x) # found in global scope myfunc() # prints 3
Global namespace x = 7 # declare in global namespace def myfunc(): x = 3 # local scope print(x) # found in local scope myfunc() # prints 3 print(x) # prints 7
Looking up value of a variable y = 7 def myfunc(): x = 2 print(x) # found in local (function) scope print(y) # found in global scope myfunc() • To look up the value of a variable: • First, if it is contained within the body of a function, look for its value within the local scope (function namespace) • Otherwise, look up value of variable within global namespace
Function parameters are also in local scope b = 7 def myfunc(b): print(b) myfunc(3) # prints 3 print(b) # prints 7
Try to modify variable outside its scope(doesn’t work) x = 3 def myfunc(): x = 2 myfunc() print(x) # prints 3
To modify a global variable from within a function, declare the variable as global x = 3 def myfunc(): global x x = 2 print(x) # prints 2
Example application:How many times was a function called? num_times_called = 0 def myfunc(): global num_times_called num_times_called += 1 myfunc() myfunc() myfunc() print(num_times_called)# prints 3
Can avoid confusion by using different variable names in arguments and function parameters a = 3 b = 4 def myfunc(aa,bb): # instead of myfunc(a, b) return aa + bb # instead of return a + b myfunc(a, b)
Outline • Functions • Namespaces and scopes • Built-in functions and modules • Short assignment #2
Built-in functions • Python provides many functions that are immediately available for use • http://docs.python.org/library/functions.html
Built-in functions >>> abs(-3.5) # absolute value 3.5 >>> float(2) # convert to floating-point 2.0 >>> int(2.0) # convert to an integer 2 >>> max([4,3,2,3,6,1]) 6 >>> min([4,3,2,3,6,1]) 1 >>> sum([4,3,2,3,6,1]) 19
input • Accept input from the user >>> a = input() 579 >>> a 579 >>> b = input() 'how are you' >>> b 'how are you'
dir • Returns a list of the names in the current scope >>> a = 3 >>> b = 7 >>> dir() ['__builtins__', '__doc__', '__name__', '__package__', 'a', 'b']
Demonstrate function namespace with dir() >>> a = 3 >>> b = 7 >>> dir() ['__builtins__', '__doc__', '__name__', '__package__', 'a', 'b'] >>> def myfunc(x): y = 7 print(dir()) >>> myfunc() ['x','y']
Get available names with dir(object) >>> a = [1,2,3] >>> dir(a) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] >>> a.reverse() >>> a [3, 2, 1]
help(object) help() # interactive help help(dir) # help on a function b = 3 help(b) # help on an integer help([1,2,3]) # help on a list
Modules • A module is a .py file with code that you can use • May contain variables • May contain functions • May contain classes • Many modules come with Python, and contain useful code
Example: math module >>> import math >>> dir(math) ['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'hypot', 'isinf', 'isnan', 'ldexp', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
Example: math module >>> math.pi # dot operator 3.1415926535897931 >>> help(math.sqrt) Help on built-in function sqrt in module math: sqrt(...) sqrt(x) Return the square root of x. >>> math.sqrt(4) # same as 4**.5 2.0
Outline • Functions • Built-in functions and modules • Namespaces and scopes • Short assignment #2
Due 8/27 • Suppose bookstores get a 40% discount off the list price of books. Shipping costs $3 for the first copy and 75 cents for each additional copy. What is the total cost for 60 copies of a book whose list price is $24.95? Separately, what is the total cost for 35 copies of a book whose list price is $49.99? • Compute the answers through a function and two calls to the function. The function should take appropriate parameters. • Turn in on paper; may be handwritten