SlideShare a Scribd company logo
An Introduction To Software
Development Using Python
Spring Semester, 2014
Class #18:
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
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
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
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 = chocolate
return (flavor)
Image Credit: www.fotosearch.com
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 variable
and 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
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
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
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
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
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
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
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
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
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 pyramid
14 # @param baseLength a float indicating the length of one side of the pyramid’s base
15 # @return the volume of the pyramid as a float
16 #
17 def pyramidVolume(height, baseLength)
18 baseArea = baseLength * baseLength
19 return height * baseArea / 3
20
21 # Start the program.
22 print("Volume:", pyramidVolume(146, 55000)
23 print("Volume:", pyramidVolume(136, 55000)
Image Credit: oldcatman-xxx.com
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
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
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
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
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
What’s In Your Python Toolbox?
print() math strings I/O IF/Else elif While For
Lists And / Or Functions
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/
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/

More Related Content

PPTX
An Introduction To Python - Functions, Part 1
PDF
Introduction to Python decorators
PPTX
Xamarin.Forms or Write Once, Run Anywhere
KEY
System settings
KEY
Jumpstart Your Development with ZopeSkel
PPT
PPTX
An Introduction To Python - Nested Branches, Multiple Alternatives
PPTX
An Introduction To Python - Lists, Part 2
An Introduction To Python - Functions, Part 1
Introduction to Python decorators
Xamarin.Forms or Write Once, Run Anywhere
System settings
Jumpstart Your Development with ZopeSkel
An Introduction To Python - Nested Branches, Multiple Alternatives
An Introduction To Python - Lists, Part 2

Viewers also liked (14)

PPTX
An Introduction To Python - Python, Print()
PPTX
An Introduction To Python - FOR Loop
PPTX
An Introduction To Python - Lists, Part 1
PPTX
An Introduction To Software Development - Software Support and Maintenance
PPTX
An Introduction To Python - Python Midterm Review
PPTX
An Introduction To Software Development - Architecture & Detailed Design
PPTX
An Introduction To Python - Graphics
PPTX
An Introduction To Python - Variables, Math
PPTX
An Introduction To Python - Working With Data
PPTX
An Introduction To Software Development - Implementation
PPTX
An Introduction To Python - WHILE Loop
PPTX
An Introduction To Python - Files, Part 1
PPTX
An Introduction To Python - Tables, List Algorithms
PPTX
An Introduction To Python - Dictionaries
An Introduction To Python - Python, Print()
An Introduction To Python - FOR Loop
An Introduction To Python - Lists, Part 1
An Introduction To Software Development - Software Support and Maintenance
An Introduction To Python - Python Midterm Review
An Introduction To Software Development - Architecture & Detailed Design
An Introduction To Python - Graphics
An Introduction To Python - Variables, Math
An Introduction To Python - Working With Data
An Introduction To Software Development - Implementation
An Introduction To Python - WHILE Loop
An Introduction To Python - Files, Part 1
An Introduction To Python - Tables, List Algorithms
An Introduction To Python - Dictionaries
Ad

Similar to An Introduction To Python - Functions, Part 2 (20)

PPTX
11.C++Polymorphism [Autosaved].pptx
PPTX
Intro To C++ - Class #19: Functions
PPTX
An Introduction To Python - Final Exam Review
PPTX
Intro To C++ - Class #20: Functions, Recursion
PPT
web program -Life cycle of a servlet.ppt
PPTX
Introduction of function in c programming.pptx
PPTX
Mod_5 of Java 5th module notes for ktu students
PPTX
Python Basic for Data science enthusiast
PPT
270_2_C Functions_Pepper_in C_programming.ppt
PPTX
ExamRevision_FinalSession_C++ notes.pptx
PPT
PDF
React Development with the MERN Stack
PPTX
Graphics on the Go
PDF
PDF
Douglas Crockford: Serversideness
PPT
3d7b7 session4 c++
PDF
React Native One Day
PDF
Test Driven Development with JavaFX
PPTX
visiblity and scope.pptx
DOCX
Lab11bRevf.docLab 11b Alien InvasionCS 122 • 15 Points .docx
11.C++Polymorphism [Autosaved].pptx
Intro To C++ - Class #19: Functions
An Introduction To Python - Final Exam Review
Intro To C++ - Class #20: Functions, Recursion
web program -Life cycle of a servlet.ppt
Introduction of function in c programming.pptx
Mod_5 of Java 5th module notes for ktu students
Python Basic for Data science enthusiast
270_2_C Functions_Pepper_in C_programming.ppt
ExamRevision_FinalSession_C++ notes.pptx
React Development with the MERN Stack
Graphics on the Go
Douglas Crockford: Serversideness
3d7b7 session4 c++
React Native One Day
Test Driven Development with JavaFX
visiblity and scope.pptx
Lab11bRevf.docLab 11b Alien InvasionCS 122 • 15 Points .docx
Ad

Recently uploaded (20)

PPT
KPMG FA Benefits Report_FINAL_Jan 27_2010.ppt
PPTX
Who’s winning the race to be the world’s first trillionaire.pptx
PPTX
Unilever_Financial_Analysis_Presentation.pptx
PPTX
The discussion on the Economic in transportation .pptx
PDF
how_to_earn_50k_monthly_investment_guide.pdf
PPTX
Introduction to Managemeng Chapter 1..pptx
PDF
6a Transition Through Old Age in a Dynamic Retirement Distribution Model JFP ...
PDF
discourse-2025-02-building-a-trillion-dollar-dream.pdf
PDF
caregiving tools.pdf...........................
PPTX
4.5.1 Financial Governance_Appropriation & Finance.pptx
PDF
Dr Tran Quoc Bao the first Vietnamese speaker at GITEX DigiHealth Conference ...
PPTX
Session 14-16. Capital Structure Theories.pptx
PPTX
Introduction to Customs (June 2025) v1.pptx
PPTX
FL INTRODUCTION TO AGRIBUSINESS CHAPTER 1
PPTX
OAT_ORI_Fed Independence_August 2025.pptx
PDF
Chapter 9 IFRS Ed-Ed4_2020 Intermediate Accounting
PDF
Understanding University Research Expenditures (1)_compressed.pdf
PDF
Lecture1.pdf buss1040 uses economics introduction
PPTX
How best to drive Metrics, Ratios, and Key Performance Indicators
PDF
HCWM AND HAI FOR BHCM STUDENTS(1).Pdf and ptts
KPMG FA Benefits Report_FINAL_Jan 27_2010.ppt
Who’s winning the race to be the world’s first trillionaire.pptx
Unilever_Financial_Analysis_Presentation.pptx
The discussion on the Economic in transportation .pptx
how_to_earn_50k_monthly_investment_guide.pdf
Introduction to Managemeng Chapter 1..pptx
6a Transition Through Old Age in a Dynamic Retirement Distribution Model JFP ...
discourse-2025-02-building-a-trillion-dollar-dream.pdf
caregiving tools.pdf...........................
4.5.1 Financial Governance_Appropriation & Finance.pptx
Dr Tran Quoc Bao the first Vietnamese speaker at GITEX DigiHealth Conference ...
Session 14-16. Capital Structure Theories.pptx
Introduction to Customs (June 2025) v1.pptx
FL INTRODUCTION TO AGRIBUSINESS CHAPTER 1
OAT_ORI_Fed Independence_August 2025.pptx
Chapter 9 IFRS Ed-Ed4_2020 Intermediate Accounting
Understanding University Research Expenditures (1)_compressed.pdf
Lecture1.pdf buss1040 uses economics introduction
How best to drive Metrics, Ratios, and Key Performance Indicators
HCWM AND HAI FOR BHCM STUDENTS(1).Pdf and ptts

An Introduction To Python - Functions, Part 2

  • 1. An Introduction To Software Development Using Python Spring Semester, 2014 Class #18: Functions, Part 2
  • 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
  • 3. 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
  • 4. 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
  • 5. 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 = chocolate return (flavor) Image Credit: www.fotosearch.com
  • 6. 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 variable and 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
  • 7. 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
  • 8. 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
  • 9. 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
  • 10. 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
  • 11. 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
  • 12. 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
  • 13. 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
  • 14. 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
  • 15. 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 pyramid 14 # @param baseLength a float indicating the length of one side of the pyramid’s base 15 # @return the volume of the pyramid as a float 16 # 17 def pyramidVolume(height, baseLength) 18 baseArea = baseLength * baseLength 19 return height * baseArea / 3 20 21 # Start the program. 22 print("Volume:", pyramidVolume(146, 55000) 23 print("Volume:", pyramidVolume(136, 55000) Image Credit: oldcatman-xxx.com
  • 16. 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
  • 17. 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
  • 18. 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
  • 19. 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
  • 20. 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
  • 21. What’s In Your Python Toolbox? print() math strings I/O IF/Else elif While For Lists And / Or Functions
  • 22. 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/
  • 23. 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/

Editor's Notes

  • #2: New name for the class I know what this means Technical professionals are who get hired This means much more than just having a narrow vertical knowledge of some subject area. It means that you know how to produce an outcome that I value. I’m willing to pay you to do that.