Docsity

Python Function Basics: Understanding Scope, Return Values, and Parameter Passing - Prof. , Lab Reports of Computer Systems Networking and Telecommunications

Partial preview of the text

Download Python Function Basics: Understanding Scope, Return Values, and Parameter Passing - Prof. and more Lab Reports Computer Systems Networking and Telecommunications in PDF only on Docsity!

CSCI 553: Networking III

Unix Network Programming

Spring 2007

Python Functions & Libraries

Today's Agenda

 Lab 04 Discussion

Answers will be available through svn via user harry

account this afternoon.

Make sure name labor/x.py & executable & interpretable

 8 Labs, 40% so 4 Labs 20% == 2 letter grades

More Python Scripting

 Python Libraries

Sets & Dictionaries

OOP intro

Lab 05 Unit Testing

Defining Functions

Define a new function using def

 Parameter names follow in parentheses

def double(x):

return x * 2

print double(5)

print double(['basalt', 'granite'])

['basalt', 'granite', 'basalt',

'granite']

Cannot declare types for parameters

Returning Values

 (^) Finish the function at any time using return def sign(x): if x < 0: return - if x == 0: return 0 return 1  (^) Functions with return statements scattered through them are hard to understand  (^) Have to read the function line by line to figure out what it might do  (^) In general:  (^) Use early returns at the start of the function to handle special cases  (^) And then one return at the end to handle the general case

Scope

 (^) Python manages variables using a call stack

Global variable.

rock_type = 'unknown'

Function that creates local variable.

def classify(rock_name): if rock_name in ['basalt', 'granite']: rock_type = 'igneous' elif rock_name in ['sandstone', 'shale']: rock_type = 'sedimentary' else: rock_type = 'metamorphic' print 'in function, rock_type is', rock_type

Call the function to prove that it uses its local 'x'.

print "before function, rock_type is", rock_type classify('sandstone') print "after function, rock_type is", rock_type before function, rock_type is unknown in function, rock_type is sedimentary after function, rock_type is unknown

Scope

 When a function is called, Python creates a new stack frame

 (^) A table of name/value pairs  (^) Parameters are just local variables that are automatically initialized  (^) When a variable is referenced, Python looks for it in:  (^) The top stack frame, then  (^) The global variables Figure l8.1: Call Stack

Parameter Passing

Figure 8.2: Parameter Passing

Making Copies

To pass a copy of a list into

a function, slice it

 values[:] is the same as

values[0:len(values)]…

 (^) …which is a slice of values that includes the entire list…  (^) …and slicing creates a new list def add_salt(first, second): first += "salt" second += ["salt"] str = "rock" seq = ["gneiss", "shale"] print "before" print "str is:", str print "seq is:", seq add_salt(str, seq[:]) print "after" print "str is:", str print "seq is:", seq before str is: rock seq is: ['gneiss', 'shale'] after str is: rock seq is: ['gneiss', 'shale']

Default Parameter Values

 (^) You can specify default values for parameters when defining a function  (^) Just “assign” some value to the parameter in the definition def total(values, start=0, end=None):

If no values given, total is zero.

if not values: return 0

If no end specified, use the entire sequence.

if end is None: end = len(values)

Calculate.

result = 0 for i in range(start, end): result += values[i] return result

Default Parameter Values

 The parameters actually passed when the function is called

are matched up left to right

numbers = [10, 20, 30] print "numbers being added:", numbers print "total(numbers, 0, 3):", total(numbers, 0, 3) print "total(numbers, 2):", total(numbers, 2) print "total(numbers):", total(numbers) numbers being added: [10, 20, 30] total(numbers, 0, 3): 60 total(numbers, 2): 30 total(numbers): 60

 All parameters with defaults must come after all parameters

without them

 (^) Otherwise, matching values to parameters would be ambiguous

Functions are Objects

This means you can:

 Redefine functions

(just as you can

reassign values to

variables)

 Create aliases for

functions

 Pass functions as

parameters

 Store functions in

lists

Figure 8.4: Functions as Objects

Function Object Examples

 (^) Example: apply a function to each value in a list def apply_to_list(function, values): result = [] for v in values: temp = function(v) result.append(temp) return result radii = [0.1, 1.0, 10.0] print apply_to_list(circumference, radii) [0.62831800000000004, 6.2831799999999998, 62.831800000000001]

Function Attributes

 (^) Every function has an attribute called name  (^) The name it was originally defined with  (^) Handy when debugging def sedimentary(rock_name): return rock_name in ['sandstone', 'shale'] sed = sedimentary print 'original name:', sedimentary.name print 'name of alias:', sed.name original name: sedimentary name of alias: sedimentary  (^) Python uses double underscores to mark reserved names  (^) See many more later

Creating Modules

 (^) Every Python file is automatically also a module (or library)  (^) Refer to its contents as geology.thing  (^) Just like the methods and attributes of an object  (^) Put this in geology.py def rock_type(rock_name): if rock_name in ['basalt', 'granite']: return 'igneous' elif rock_name in ['sandstone', 'shale']: return 'sedimentary' else: return 'metamorphic‘  (^) And this in analysis.py import geology for r in ['granite', 'gneiss']: print r, 'is', geology.rock_type(r)  (^) When analysis.py runs, it prints this granite is igneous gneiss is metamorphic