functions

87
Functions Python Functions Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See http://software-carpentry.org/license.html for more information.

Upload: marieswaran-ramasamy

Post on 24-Jun-2015

164 views

Category:

Technology


1 download

DESCRIPTION

Python - Functions

TRANSCRIPT

Page 1: Functions

Functions

Python

Functions

Copyright © Software Carpentry 2010

This work is licensed under the Creative Commons Attribution License

See http://software-carpentry.org/license.html for more information.

Page 2: Functions

A programming language should not include

everything anyone might ever want

Python Functions

Page 3: Functions

A programming language should not include

everything anyone might ever want

Instead, it should make it easy for people to createInstead, it should make it easy for people to create

what they need to solve specific problems

Python Functions

Page 4: Functions

A programming language should not include

everything anyone might ever want

Instead, it should make it easy for people to createInstead, it should make it easy for people to create

what they need to solve specific problems

Define functions to create higher-level operations

Python Functions

Page 5: Functions

A programming language should not include

everything anyone might ever want

Instead, it should make it easy for people to createInstead, it should make it easy for people to create

what they need to solve specific problems

Define functions to create higher-level operations

"Create a language in which the solution to your

original problem is trivial."

Python Functions

original problem is trivial."

Page 6: Functions

Define functions using def

Python Functions

Page 7: Functions

Define functions using def

defdefdefdef greet():

returnreturnreturnreturn 'Good evening, master'

Python Functions

Page 8: Functions

Define functions using def

defdefdefdef greet():

returnreturnreturnreturn 'Good evening, master'

temp = greet()

printprintprintprint temp

Good evening, master

Python Functions

Page 9: Functions

Give them parameters

Python Functions

Page 10: Functions

Give them parameters

defdefdefdef greet(name):

answer = 'Hello, ' + name

returnreturnreturnreturn answer

Python Functions

Page 11: Functions

Give them parameters

defdefdefdef greet(name):

answer = 'Hello, ' + name

temp

'doctor'

returnreturnreturnreturn answer

temp = 'doctor'

Python Functions

stackstackstackstack valuevaluevaluevalue

Page 12: Functions

Give them parameters

defdefdefdef greet(name):

answer = 'Hello, ' + name

temp

'doctor'

name

returnreturnreturnreturn answer

temp = 'doctor'

result = greet(temp)

Python Functions

stackstackstackstack valuevaluevaluevalue

Page 13: Functions

Give them parameters

defdefdefdef greet(name):

answer = 'Hello, ' + name

temp

'doctor'

'Hello, doctor'

name

answer

returnreturnreturnreturn answer

temp = 'doctor'

result = greet(temp)

Python Functions

stackstackstackstack valuevaluevaluevalue

Page 14: Functions

Give them parameters

defdefdefdef greet(name):

answer = 'Hello, ' + name

temp

'doctor'

'Hello, doctor'

returnreturnreturnreturn answer

temp = 'doctor'

result = greet(temp)

Python Functions

stackstackstackstack valuevaluevaluevalue

result

Page 15: Functions

Each function call creates a new stack frame

Python Functions

Page 16: Functions

Each function call creates a new stack frame

defdefdefdef add(a):

b = a + 1b = a + 1

returnreturnreturnreturn b

defdefdefdef double(c):

d = 2 * add(c)

returnreturnreturnreturn d

Python Functions

stackstackstackstack valuevaluevaluevalue

Page 17: Functions

Each function call creates a new stack frame

defdefdefdef add(a):

b = a + 1b = a + 1

returnreturnreturnreturn b

defdefdefdef double(c):

d = 2 * add(c)

returnreturnreturnreturn d

val = 10

10

val

Python Functions

val = 10

stackstackstackstack valuevaluevaluevalue

Page 18: Functions

Each function call creates a new stack frame

defdefdefdef add(a):

b = a + 1b = a + 1

returnreturnreturnreturn b

defdefdefdef double(c):

d = 2 * add(c)

returnreturnreturnreturn d

val = 10

10

c

valdouble

double

double

double

Python Functions

val = 10

result = double(val)

stackstackstackstack valuevaluevaluevalue

Page 19: Functions

Each function call creates a new stack frame

defdefdefdef add(a):

b = a + 1b = a + 1

returnreturnreturnreturn b

defdefdefdef double(c):

d = 2 * add(c)

returnreturnreturnreturn d

val = 10

10

a

c

valdouble

double

double

double

add

add

add

add

Python Functions

val = 10

result = double(val)

stackstackstackstack valuevaluevaluevalue

Page 20: Functions

Each function call creates a new stack frame

defdefdefdef add(a):

b = a + 1b = a + 1

returnreturnreturnreturn b

defdefdefdef double(c):

d = 2 * add(c)

returnreturnreturnreturn d

val = 10

10

11

a

b

c

valdouble

double

double

double

add

add

add

add

Python Functions

val = 10

result = double(val)

printprintprintprint resultstackstackstackstack valuevaluevaluevalue

result

Page 21: Functions

Each function call creates a new stack frame

defdefdefdef add(a):

b = a + 1b = a + 1

returnreturnreturnreturn b

defdefdefdef double(c):

d = 2 * add(c)

returnreturnreturnreturn d

val = 10

10

22

c

d

valdouble

double

double

double

Python Functions

val = 10

result = double(val)

printprintprintprint resultstackstackstackstack valuevaluevaluevalue

result

Page 22: Functions

Each function call creates a new stack frame

defdefdefdef add(a):

b = a + 1b = a + 1

returnreturnreturnreturn b

defdefdefdef double(c):

d = 2 * add(c)

returnreturnreturnreturn d

val = 10

10

22val

Python Functions

val = 10

result = double(val)

printprintprintprint resultstackstackstackstack valuevaluevaluevalue

result

Page 23: Functions

Each function call creates a new stack frame

defdefdefdef add(a):

b = a + 1b = a + 1

returnreturnreturnreturn b

defdefdefdef double(c):

d = 2 * add(c)

returnreturnreturnreturn d

val = 10

10

22val

Python Functions

val = 10

result = double(val)

printprintprintprint result

22stackstackstackstack valuevaluevaluevalue

result

Page 24: Functions

Only see variables in the current and global frames

Python Functions

Page 25: Functions

Only see variables in the current and global frames

Current beats global

Python Functions

Page 26: Functions

Only see variables in the current and global frames

Current beats global

defdefdefdef greet(name):defdefdefdef greet(name):

temp = 'Hello, ' + name

returnreturnreturnreturn temp

temp = 'doctor'

result = greet(temp)

Python Functions

Page 27: Functions

Only see variables in the current and global frames

Current beats global

defdefdefdef greet(name):defdefdefdef greet(name):

temp = 'Hello, ' + name

returnreturnreturnreturn temp

temp = 'doctor'

result = greet(temp) temp

'Hello, doctor'

'doctor'

global

global

global

global

greet

greet

greet

greet

name

temp

Python Functions

stackstackstackstack valuevaluevaluevalue

global

global

global

global

Page 28: Functions

Only see variables in the current and global frames

Current beats global

defdefdefdef greet(name):defdefdefdef greet(name):

temp = 'Hello, ' + name

returnreturnreturnreturn temp

temp = 'doctor'

result = greet(temp)

printprintprintprint resulttemp

'Hello, doctor'

'doctor'

global

global

global

global

Python Functions

Hello, doctor

stackstackstackstack valuevaluevaluevalue

resultglobal

global

global

global

Page 29: Functions

Can pass values in and accept results directly

Python Functions

Page 30: Functions

Can pass values in and accept results directly

defdefdefdef greet(name):

returnreturnreturnreturn 'Hello, ' + name

printprintprintprint greet('doctor')

Python Functions

Page 31: Functions

Can pass values in and accept results directly

defdefdefdef greet(name):

returnreturnreturnreturn 'Hello, ' + name

printprintprintprint greet('doctor')

_x1_

'doctor'

'Hello, doctor'

name

_x2_

Python Functions

stackstackstackstack valuevaluevaluevalue

Page 32: Functions

Can return at any time

Python Functions

Page 33: Functions

Can return at any time

defdefdefdef sign(num):

ifififif num > 0:

returnreturnreturnreturn 1

elifelifelifelif num == 0:

returnreturnreturnreturn 0

else:else:else:else:

return return return return -1

Python Functions

Page 34: Functions

Can return at any time

defdefdefdef sign(num):

ifififif num > 0:

returnreturnreturnreturn 1

elifelifelifelif num == 0:

returnreturnreturnreturn 0

else:else:else:else:

return return return return -1

printprintprintprint sign(3)

Python Functions

1

Page 35: Functions

Can return at any time

defdefdefdef sign(num):

ifififif num > 0:

returnreturnreturnreturn 1

elifelifelifelif num == 0:

returnreturnreturnreturn 0

else:else:else:else:

return return return return -1

printprintprintprint sign(3)

Python Functions

1

printprintprintprint sign(-9)

-1

Page 36: Functions

Can return at any time

defdefdefdef sign(num):

ifififif num > 0:Over-use makes functions

hard to understandreturnreturnreturnreturn 1

elifelifelifelif num == 0:

returnreturnreturnreturn 0

else:else:else:else:

return return return return -1

printprintprintprint sign(3)

hard to understand

Python Functions

1

printprintprintprint sign(-9)

-1

Page 37: Functions

Can return at any time

defdefdefdef sign(num):

ifififif num > 0:Over-use makes functions

hard to understandreturnreturnreturnreturn 1

elifelifelifelif num == 0:

returnreturnreturnreturn 0

else:else:else:else:

return return return return -1

printprintprintprint sign(3)

hard to understand

No prescription possible, but:

Python Functions

1

printprintprintprint sign(-9)

-1

Page 38: Functions

Can return at any time

defdefdefdef sign(num):

ifififif num > 0:Over-use makes functions

hard to understandreturnreturnreturnreturn 1

elifelifelifelif num == 0:

returnreturnreturnreturn 0

else:else:else:else:

return return return return -1

printprintprintprint sign(3)

hard to understand

No prescription possible, but:

– a few at the beginning

to handle special cases

Python Functions

1

printprintprintprint sign(-9)

-1

Page 39: Functions

Can return at any time

defdefdefdef sign(num):

ifififif num > 0:Over-use makes functions

hard to understandreturnreturnreturnreturn 1

elifelifelifelif num == 0:

returnreturnreturnreturn 0

else:else:else:else:

return return return return -1

printprintprintprint sign(3)

hard to understand

No prescription possible, but:

– a few at the beginning

to handle special cases

– one at the end for the

Python Functions

1

printprintprintprint sign(-9)

-1

– one at the end for the

"general" result

Page 40: Functions

Every function returns something

Python Functions

Page 41: Functions

Every function returns something

defdefdefdef sign(num):

ifififif num > 0:

returnreturnreturnreturn 1

elifelifelifelif num == 0:

returnreturnreturnreturn 0

# else:else:else:else:

# return return return return -1

Python Functions

Page 42: Functions

Every function returns something

defdefdefdef sign(num):

ifififif num > 0:

returnreturnreturnreturn 1

elifelifelifelif num == 0:

returnreturnreturnreturn 0

# else:else:else:else:

# return return return return -1

printprintprintprint sign(3)

Python Functions

1

Page 43: Functions

Every function returns something

defdefdefdef sign(num):

ifififif num > 0:

returnreturnreturnreturn 1

elifelifelifelif num == 0:

returnreturnreturnreturn 0

# else:else:else:else:

# return return return return -1

printprintprintprint sign(3)

Python Functions

1

printprintprintprint sign(-9)

None

Page 44: Functions

Every function returns something

defdefdefdef sign(num):

ifififif num > 0:If the function doesn't return

a value, Python returns Nonereturnreturnreturnreturn 1

elifelifelifelif num == 0:

returnreturnreturnreturn 0

# else:else:else:else:

# return return return return -1

printprintprintprint sign(3)

a value, Python returns None

Python Functions

1

printprintprintprint sign(-9)

None

Page 45: Functions

Every function returns something

defdefdefdef sign(num):

ifififif num > 0:If the function doesn't return

a value, Python returns Nonereturnreturnreturnreturn 1

elifelifelifelif num == 0:

returnreturnreturnreturn 0

# else:else:else:else:

# return return return return -1

printprintprintprint sign(3)

a value, Python returns None

Yet another reason why

commenting out blocks of code

is a bad idea...

Python Functions

1

printprintprintprint sign(-9)

None

Page 46: Functions

Functions and parameters don't have types

Python Functions

Page 47: Functions

Functions and parameters don't have types

defdefdefdef double(x):

returnreturnreturnreturn 2 * x

Python Functions

Page 48: Functions

Functions and parameters don't have types

defdefdefdef double(x):

returnreturnreturnreturn 2 * x

printprintprintprint double(2)

4

Python Functions

Page 49: Functions

Functions and parameters don't have types

defdefdefdef double(x):

returnreturnreturnreturn 2 * x

printprintprintprint double(2)

4

printprintprintprint double('two')

twotwo

Python Functions

Page 50: Functions

Functions and parameters don't have types

defdefdefdef double(x):

returnreturnreturnreturn 2 * xOnly use this when the

function's behavior dependsprintprintprintprint double(2)

4

printprintprintprint double('two')

twotwo

function's behavior depends

only on properties that all

possible arguments share

Python Functions

Page 51: Functions

Functions and parameters don't have types

defdefdefdef double(x):

returnreturnreturnreturn 2 * xOnly use this when the

function's behavior dependsprintprintprintprint double(2)

4

printprintprintprint double('two')

twotwo

function's behavior depends

only on properties that all

possible arguments share

ifififif type(arg) == int:

Python Functions

ifififif type(arg) == int:

...

elif typeelif typeelif typeelif type(arg) == str:

...

...

Page 52: Functions

Functions and parameters don't have types

defdefdefdef double(x):

returnreturnreturnreturn 2 * xOnly use this when the

function's behavior dependsprintprintprintprint double(2)

4

printprintprintprint double('two')

twotwo

function's behavior depends

only on properties that all

possible arguments share

Warning sign ifififif type(arg) == int:

Python Functions

Warning sign ifififif type(arg) == int:

...

elif typeelif typeelif typeelif type(arg) == str:

...

...

Page 53: Functions

Functions and parameters don't have types

defdefdefdef double(x):

returnreturnreturnreturn 2 * xOnly use this when the

function's behavior dependsprintprintprintprint double(2)

4

printprintprintprint double('two')

twotwo

function's behavior depends

only on properties that all

possible arguments share

Warning sign ifififif type(arg) == int:

Python Functions

Warning sign

There's a better

way to do this

ifififif type(arg) == int:

...

elif typeelif typeelif typeelif type(arg) == str:

...

...

Page 54: Functions

Values are copied into parameters

Python Functions

Page 55: Functions

Values are copied into parameters

Which means lists are aliased

Python Functions

Page 56: Functions

Values are copied into parameters

Which means lists are aliased

defdefdefdef appender(a_string, a_list):defdefdefdef appender(a_string, a_list):

a_string += 'turing'

a_list.append('turing')

Python Functions

Page 57: Functions

Values are copied into parameters

Which means lists are aliased

defdefdefdef appender(a_string, a_list):defdefdefdef appender(a_string, a_list):

a_string += 'turing'

a_list.append('turing')

string_val = 'alan'

list_val = ['alan']

appender(string_val, list_val)

Python Functions

Page 58: Functions

Values are copied into parameters

Which means lists are aliased

defdefdefdef appender(a_string, a_list):defdefdefdef appender(a_string, a_list):

a_string += 'turing'

a_list.append('turing')

string_val = 'alan'

list_val = ['alan']

appender(string_val, list_val)string_val

'alan'

['alan']

Python Functions

stackstackstackstack valuevaluevaluevalue

list_val

Page 59: Functions

Values are copied into parameters

Which means lists are aliased

defdefdefdef appender(a_string, a_list):defdefdefdef appender(a_string, a_list):

a_string += 'turing'

a_list.append('turing')

string_val = 'alan'

list_val = ['alan']

appender(string_val, list_val)string_val

'alan'

['alan']

a_string

a_list

Python Functions

stackstackstackstack valuevaluevaluevalue

list_val

Page 60: Functions

Values are copied into parameters

Which means lists are aliased

defdefdefdef appender(a_string, a_list):defdefdefdef appender(a_string, a_list):

a_string += 'turing'

a_list.append('turing')

string_val = 'alan'

list_val = ['alan']

appender(string_val, list_val)string_val

'alan'

'alanturing'

['alan']

a_string

a_list

Python Functions

stackstackstackstack valuevaluevaluevalue

list_val

Page 61: Functions

Values are copied into parameters

Which means lists are aliased

defdefdefdef appender(a_string, a_list):defdefdefdef appender(a_string, a_list):

a_string += 'turing'

a_list.append('turing')

string_val = 'alan'

list_val = ['alan']

appender(string_val, list_val)string_val

'alan'

'alanturing'

['alan',

a_string

a_list

Python Functions

stackstackstackstack valuevaluevaluevalue

list_val 'turing']

Page 62: Functions

Values are copied into parameters

Which means lists are aliased

defdefdefdef appender(a_string, a_list):defdefdefdef appender(a_string, a_list):

a_string += 'turing'

a_list.append('turing')

string_val = 'alan'

list_val = ['alan']

appender(string_val, list_val)

printprintprintprint string_val

string_val

'alan'

['alan',

Python Functions

printprintprintprint string_val

alan

printprintprintprint list_val

['alan', 'turing']stackstackstackstack valuevaluevaluevalue

list_val 'turing']

Page 63: Functions

Can define default parameter values

Python Functions

Page 64: Functions

Can define default parameter values

defdefdefdef adjust(value, amount=2.0):

returnreturnreturnreturn value * amount

Python Functions

Page 65: Functions

Can define default parameter values

defdefdefdef adjust(value, amount=2.0):

returnreturnreturnreturn value * amount

printprintprintprint adjust(5)

10

Python Functions

Page 66: Functions

Can define default parameter values

defdefdefdef adjust(value, amount=2.0):

returnreturnreturnreturn value * amount

printprintprintprint adjust(5)

10

printprintprintprint adjust(5, 1.001)

5.005

Python Functions

Page 67: Functions

More readable than multiple functions

Python Functions

Page 68: Functions

More readable than multiple functions

defdefdefdef adjust_general(value, amount):

returnreturnreturnreturn value * amount

defdefdefdef adjust_default(value):

returnreturnreturnreturn adjust_general(value, 2.0)

Python Functions

Page 69: Functions

Parameters that have defaults must come after

parameters that do not

Python Functions

Page 70: Functions

Parameters that have defaults must come after

parameters that do not

defdefdefdef triplet(left='venus', middle, right='mars'):

returnreturnreturnreturn '%s %s %s' % (left, middle, right)

Python Functions

Page 71: Functions

Parameters that have defaults must come after

parameters that do not

defdefdefdef triplet(left='venus', middle, right='mars'):

returnreturnreturnreturn '%s %s %s' % (left, middle, right)

printprintprintprint triplet('earth')

venus earth mars

OK so far...

Python Functions

Page 72: Functions

Parameters that have defaults must come after

parameters that do not

defdefdefdef triplet(left='venus', middle, right='mars'):

returnreturnreturnreturn '%s %s %s' % (left, middle, right)

printprintprintprint triplet('earth')

venus earth mars

printprintprintprint triplet('pluto', 'earth')

OK so far...

?

Python Functions

printprintprintprint triplet('pluto', 'earth') ?

Page 73: Functions

Parameters that have defaults must come after

parameters that do not

defdefdefdef triplet(left='venus', middle, right='mars'):

returnreturnreturnreturn '%s %s %s' % (left, middle, right)

printprintprintprint triplet('earth')

venus earth mars

printprintprintprint triplet('pluto', 'earth')

OK so far...

?

Python Functions

printprintprintprint triplet('pluto', 'earth')

triplet('pluto', 'earth', 'mars')

?

Page 74: Functions

Parameters that have defaults must come after

parameters that do not

defdefdefdef triplet(left='venus', middle, right='mars'):

returnreturnreturnreturn '%s %s %s' % (left, middle, right)

printprintprintprint triplet('earth')

venus earth mars

printprintprintprint triplet('pluto', 'earth')

OK so far...

?

Python Functions

printprintprintprint triplet('pluto', 'earth')

triplet('venus', 'pluto', 'earth')

triplet('pluto', 'earth', 'mars')

?

Page 75: Functions

"When should I write a function?"

Python Functions

Page 76: Functions

"When should I write a function?"

Human short term memory can hold 7± 2 items

Python Functions

Page 77: Functions

"When should I write a function?"

Human short term memory can hold 7± 2 items

If someone has to keep more than a dozen thingsIf someone has to keep more than a dozen things

in their mind at once to understand a block of code,

it's too long

Python Functions

Page 78: Functions

"When should I write a function?"

Human short term memory can hold 7± 2 items

If someone has to keep more than a dozen thingsIf someone has to keep more than a dozen things

in their mind at once to understand a block of code,

it's too long

Break it into comprehensible pieces with functions

Python Functions

Page 79: Functions

"When should I write a function?"

Human short term memory can hold 7± 2 items

If someone has to keep more than a dozen thingsIf someone has to keep more than a dozen things

in their mind at once to understand a block of code,

it's too long

Break it into comprehensible pieces with functions

Even if each function is only called once

Python Functions

Even if each function is only called once

Page 80: Functions

Example

forforforfor x inininin range(1, GRID_WIDTH-1):

forforforfor y inininin range(1, GRID_HEIGHT-1):

ifififif (density[x-1][y] > density_threshold) or \

(density[x+1][y] > density_threshold):

ifififif (flow[x][y-1] < flow_threshold) or\

(flow[x][y+1] < flow_threshold):

temp = (density[x-1][y] + density[x+1][y]) / 2

ifififif abs(temp - density[x][y]) > update_threshold:

density[x][y] = temp

Python Functions

Page 81: Functions

Refactoring #1: grid interior

forforforfor x inininin grid_interior(GRID_WIDTH):

forforforfor y inininin grid_interior(GRID_HEIGHT):

ifififif (density[x-1][y] > density_threshold) or \

(density[x+1][y] > density_threshold):

ifififif (flow[x][y-1] > flow_threshold) or\

(flow[x][y+1] > flow_threshold):

temp = (density[x-1][y] + density[x+1][y]) / 2

ifififif abs(temp - density[x][y]) > update_threshold:

density[x][y] = temp

Python Functions

Page 82: Functions

Refactoring #2: tests on X and Y axes

forforforfor x inininin grid_interior(GRID_WIDTH):

forforforfor y inininin grid_interior(GRID_HEIGHT):

ifififif density_exceeds(density, x, y, density_threshold):

ifififif flow_exceeds(flow, x, y, flow_threshold):

temp = (density[x-1][y] + density[x+1][y]) / 2

ifififif abs(temp - density[x][y]) > tolerance:

density[x][y] = temp

Python Functions

Page 83: Functions

Refactoring #3: update rule

forforforfor x inininin grid_interior(GRID_WIDTH):

forforforfor y inininin grid_interior(GRID_HEIGHT):

ifififif density_exceeds(density, x, y, density_threshold):

ifififif flow_exceeds(flow, x, y, flow_threshold):

update_on_tolerance(density, x, y, tolerance)

Python Functions

Page 84: Functions

Refactoring #3: update rule

forforforfor x inininin grid_interior(GRID_WIDTH):

forforforfor y inininin grid_interior(GRID_HEIGHT):

ifififif density_exceeds(density, x, y, density_threshold):

ifififif flow_exceeds(flow, x, y, flow_threshold):

update_on_tolerance(density, x, y, tolerance)

Good programmers will write this first

Python Functions

Page 85: Functions

Refactoring #3: update rule

forforforfor x inininin grid_interior(GRID_WIDTH):

forforforfor y inininin grid_interior(GRID_HEIGHT):

Good programmers will write this first

Then write the functions it implies

ifififif density_exceeds(density, x, y, density_threshold):

ifififif flow_exceeds(flow, x, y, flow_threshold):

update_on_tolerance(density, x, y, tolerance)

Python Functions

Page 86: Functions

Refactoring #3: update rule

forforforfor x inininin grid_interior(GRID_WIDTH):

forforforfor y inininin grid_interior(GRID_HEIGHT):

Good programmers will write this first

Then write the functions it implies

ifififif density_exceeds(density, x, y, density_threshold):

ifififif flow_exceeds(flow, x, y, flow_threshold):

update_on_tolerance(density, x, y, tolerance)

Python Functions

Then refactor any overlap

Page 87: Functions

October 2010

created by

Greg Wilson

October 2010

Copyright © Software Carpentry 2010

This work is licensed under the Creative Commons Attribution License

See http://software-carpentry.org/license.html for more information.