an introduction to python - functions, part 2

23
An Introduction To Software Development Using Python Spring Semester, 2014 Class #18: Functions, Part 2

Upload: blue-elephant-consulting

Post on 28-Jul-2015

399 views

Category:

Economy & Finance


2 download

TRANSCRIPT

Page 1: An Introduction To Python - Functions, Part 2

An Introduction To Software Development

Using Python

Spring Semester, 2014

Class #18:Functions, Part 2

Page 2: An Introduction To Python - Functions, Part 2

Function Parameter Passing

• When a function is called, variables are created for receiving the function’s arguments.

• These variables are called parameter variables.

• The values that are supplied to the function when it is called are the arguments of the call.

• Each parameter variable is initialized with the corresponding argument.

Image Credit: clipartzebra.com

Page 3: An Introduction To Python - Functions, Part 2

Parameter Passing: An Example

1. Function Call myFlavor = selectFlavor(yogurt)

2. Initializing functional parameter variable myFlavor = selectFlavor(yogurt)

3. About to return to the caller selection = input(“Please enter flavor of yogurt you would like:”)

return selection

4. After function call myFlavor = selectFlavor(yogurt)

Image Credit: www.clipartpanda.com

Page 4: An Introduction To Python - Functions, Part 2

What Happens The Next Time That We Call This

Function?• A new parameter variable is created. (The previous parameter

variable was removed when the first call to selectFlavor returned.)

• It is initialized with yogurt value, and the process repeats.

• After the second function call is complete, its variables are again removed

Image Credit: www.clker.com

Page 5: An Introduction To Python - Functions, Part 2

What If … You Try To Modify Argument

Parameters?• When the function returns, all of its

variables are removed.

• Any values that have been assigned to them are simply forgotten.

• In Python, a function can never change the contents of a variable that was passed as an argument.

• When you call a function with a variable as argument, you don’t actually pass the variable, just the value that it contains.

selectFlavor(yogurt): if yogurt : yogurt = False else: yogurt = True flavor = chocolatereturn (flavor)

Image Credit: www.fotosearch.com

Page 6: An Introduction To Python - Functions, Part 2

Return Values

• You use the return statement to specify the result of a function.

• The return statement can return the value of any expression.

• Instead of saving the return value in a variableand returning the variable, it is often possible to eliminate the variable and return the value of a more complex expression:

return ((numConesWanted*5)**2)

Image Credit: www.dreamstime.com

Page 7: An Introduction To Python - Functions, Part 2

Multiple Returns

• When the return statement is processed, the function exits immediately.

• Every branch of a function should return a value.

selectFlavor(yogurt): if not(yogurt) : return (noFlavor) else: myFlavor = input(“Enter your yogurt flavor”) return (myFlavor)

Image Credit: www.clker.com

Page 8: An Introduction To Python - Functions, Part 2

Multiple Returns: Mistakes

• What happens when you forget to include a return statement on a path?

• The compiler will not report this as an error. Instead, the special value None will be returned from the function.

selectFlavor(yogurt): if not(yogurt) : numNoYogurts += numNoYogurts else: myFlavor = input(“Enter your yogurt flavor”) return (myFlavor)

Image Credit: www.clipartpanda.com

Page 9: An Introduction To Python - Functions, Part 2

Using Single-Line Compound Statements

• Compounds statements in Python are generally written across several lines.

• The header is on one line and the body on the following lines, with each body statement indented to the same level.

• When the body contains a single statement, however, compound statements may be written on a single line.

if digit == 1 : return "one"

if digit == 1 : return "one"

Image Credit: www.clipartpanda.com

Page 10: An Introduction To Python - Functions, Part 2

Using Single-Line Compound Statements

• This form can be very useful in functions that select a single value from among a collection and return it. For example, the single-line form used here produces condensed code that is easy to read:

if digit == 1 : return "one"if digit == 2 : return "two"if digit == 3 : return "three"if digit == 4 : return "four"if digit == 5 : return "five"if digit == 6 : return "six"if digit == 7 : return "seven"if digit == 8 : return "eight"if digit == 9 : return "nine"

Image Credit: www.clipartbest.com

Page 11: An Introduction To Python - Functions, Part 2

Example: Implementing A Function

• Suppose that you are helping archaeologists who research Egyptian pyramids.

• You have taken on the task of writing a function that determines the volume of a pyramid, given its height and base length.

Image Credit: www.morethings.com

Page 12: An Introduction To Python - Functions, Part 2

Inputs & Parameter Types

• What are your inputs?– the pyramid’s height and base length

• Types of the parameter variables and the return value.– The height and base length can both be floating-point numbers. – The computed volume is also a floating-point number

## Computes the volume of a pyramid whose base is square.# @param height a float indicating the height of the pyramid# @param baseLength a float indicating the length of one side of the pyramid’s base# @return the volume of the pyramid as a float

def pyramidVolume(height, baseLength) :

Image Credit: egypt.mrdonn.org

Page 13: An Introduction To Python - Functions, Part 2

Pseudocode For Calculating The Volume

• An Internet search yields the fact that the volume of a pyramid is computed as: volume = 1/3 x height x base area

• Because the base is a square, we have base area = base length x base length

• Using these two equations, we can compute the volume from the arguments.

Image Credit: munezoxcence.blogspot.com

Page 14: An Introduction To Python - Functions, Part 2

Implement the Function Body

• The function body is quite simple. • Note the use of the return statement to

return the result.

def pyramidVolume(height, baseLength) : baseArea = baseLength * baseLength return height * baseArea / 3

Image Credit: imgkid.com

Page 15: An Introduction To Python - Functions, Part 2

Let’s Calculate!Question: How Tall Was the Great Pyramid?

Answer: The tallest of a cluster of three pyramids at Giza, the Great Pyramid was originally about 146 meters tall, but it has lost about 10 meters in height over the millennia. Erosion and burial in sand contribute to the shrinkage. The base of the Great Pyramid is about 55,000 meters.

## Computes the volume of a pyramid whose base is a square.13 # @param height a float indicating the height of the pyramid14 # @param baseLength a float indicating the length of one side of the pyramid’s base15 # @return the volume of the pyramid as a float16 #17 def pyramidVolume(height, baseLength)18 baseArea = baseLength * baseLength19 return height * baseArea / 32021 # Start the program.22 print("Volume:", pyramidVolume(146, 55000)23 print("Volume:", pyramidVolume(136, 55000)

Image Credit: oldcatman-xxx.com

Page 16: An Introduction To Python - Functions, Part 2

Scope Of Variables

• The scope of a variable is the part of the program in which you can access it.

• For example, the scope of a function’s parameter variable is the entire function.

def main() : print(cubeVolume(10))

def cubeVolume(sideLength) : return sideLength ** 3

Image Credit: www.clipartpanda.com

Page 17: An Introduction To Python - Functions, Part 2

Local Variables

• A variable that is defined within a function is called a local variable.

• When a local variable is defined in a block, it becomes available from that point until the end of the function in which it is defined.

def main() : sum = 0 for i in range(11) : square = i * i sum = sum + square

print(square, sum)

Image Credit: www.fotosearch.com

Page 18: An Introduction To Python - Functions, Part 2

Scope Problem

• Note the scope of the variable sideLength.

• The cubeVolume function attempts to read thevariable, but it cannot—the scope of sideLength does not extend outside the main function.

def main() : sideLength = 10 result = cubeVolume() print(result)

def cubeVolume() : return sideLength ** 3 # Error

main()

Image Credit: www.lexique.co.uk

Page 19: An Introduction To Python - Functions, Part 2

Variable Reuse

• It is possible to use the same variable name more than once in a program.

• Each result variable is defined in a separate function, and their scopes do not overlap

def main() : result = square(3) + square(4) print(result)

def square(n) : result = n * n return result

main()

Image Credit: www.clipartguide.com

Page 20: An Introduction To Python - Functions, Part 2

Global Variables

• Python also supports global variables: variables that are defined outside functions.

• A global variable is visible to all functions that are defined after it.

• However, any function that wishes to update a global variable must include a global declaration, like this:

• If you omit the global declaration, then the balance variable inside the withdraw function is considered a local variable.

balance = 10000 # A global variable

def withdraw(amount) :

global balance # This function intends to update the global variable

if balance >= amount : balance = balance - amount

Image Credit: galleryhip.com

Page 21: An Introduction To Python - Functions, Part 2

What’s In Your Python Toolbox?

print() math strings I/O IF/Else elif While For

Lists And / Or Functions

Page 22: An Introduction To Python - Functions, Part 2

What We Covered Today

1. Parameter passing

2. Return

3. Scope of variables

Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/

Page 23: An Introduction To Python - Functions, Part 2

What We’ll Be Covering Next Time

1. Files, Part 1

Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/