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

Viewers also liked

Viewers also liked (14)

An Introduction To Python - Python, Print()
An Introduction To Python - Python, Print()An Introduction To Python - Python, Print()
An Introduction To Python - Python, Print()
 
An Introduction To Python - FOR Loop
An Introduction To Python - FOR LoopAn Introduction To Python - FOR Loop
An Introduction To Python - FOR Loop
 
An Introduction To Python - Lists, Part 1
An Introduction To Python - Lists, Part 1An Introduction To Python - Lists, Part 1
An Introduction To Python - Lists, Part 1
 
An Introduction To Software Development - Software Support and Maintenance
An Introduction To Software Development - Software Support and MaintenanceAn Introduction To Software Development - Software Support and Maintenance
An Introduction To Software Development - Software Support and Maintenance
 
An Introduction To Python - Python Midterm Review
An Introduction To Python - Python Midterm ReviewAn Introduction To Python - Python Midterm Review
An Introduction To Python - Python Midterm Review
 
An Introduction To Software Development - Architecture & Detailed Design
An Introduction To Software Development - Architecture & Detailed DesignAn Introduction To Software Development - Architecture & Detailed Design
An Introduction To Software Development - Architecture & Detailed Design
 
An Introduction To Python - Graphics
An Introduction To Python - GraphicsAn Introduction To Python - Graphics
An Introduction To Python - Graphics
 
An Introduction To Python - Variables, Math
An Introduction To Python - Variables, MathAn Introduction To Python - Variables, Math
An Introduction To Python - Variables, Math
 
An Introduction To Python - Working With Data
An Introduction To Python - Working With DataAn Introduction To Python - Working With Data
An Introduction To Python - Working With Data
 
An Introduction To Software Development - Implementation
An Introduction To Software Development - ImplementationAn Introduction To Software Development - Implementation
An Introduction To Software Development - Implementation
 
An Introduction To Python - WHILE Loop
An Introduction To  Python - WHILE LoopAn Introduction To  Python - WHILE Loop
An Introduction To Python - WHILE Loop
 
An Introduction To Python - Files, Part 1
An Introduction To Python - Files, Part 1An Introduction To Python - Files, Part 1
An Introduction To Python - Files, Part 1
 
An Introduction To Python - Tables, List Algorithms
An Introduction To Python - Tables, List AlgorithmsAn Introduction To Python - Tables, List Algorithms
An Introduction To Python - Tables, List Algorithms
 
An Introduction To Python - Dictionaries
An Introduction To Python - DictionariesAn Introduction To Python - Dictionaries
An Introduction To Python - Dictionaries
 

Similar to An Introduction To Python - Functions, Part 2

Lab11bRevf.docLab 11b Alien InvasionCS 122 • 15 Points .docx
Lab11bRevf.docLab 11b Alien InvasionCS 122 • 15 Points .docxLab11bRevf.docLab 11b Alien InvasionCS 122 • 15 Points .docx
Lab11bRevf.docLab 11b Alien InvasionCS 122 • 15 Points .docx
DIPESH30
 
Lists and scrollbars
Lists and scrollbarsLists and scrollbars
Lists and scrollbars
myrajendra
 

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

11.C++Polymorphism [Autosaved].pptx
11.C++Polymorphism [Autosaved].pptx11.C++Polymorphism [Autosaved].pptx
11.C++Polymorphism [Autosaved].pptx
 
Intro To C++ - Class #19: Functions
Intro To C++ - Class #19: FunctionsIntro To C++ - Class #19: Functions
Intro To C++ - Class #19: Functions
 
An Introduction To Python - Final Exam Review
An Introduction To Python - Final Exam ReviewAn Introduction To Python - Final Exam Review
An Introduction To Python - Final Exam Review
 
Intro To C++ - Class #20: Functions, Recursion
Intro To C++ - Class #20: Functions, RecursionIntro To C++ - Class #20: Functions, Recursion
Intro To C++ - Class #20: Functions, Recursion
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
React Development with the MERN Stack
React Development with the MERN StackReact Development with the MERN Stack
React Development with the MERN Stack
 
Graphics on the Go
Graphics on the GoGraphics on the Go
Graphics on the Go
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme Swift
 
3d7b7 session4 c++
3d7b7 session4 c++3d7b7 session4 c++
3d7b7 session4 c++
 
React Native One Day
React Native One DayReact Native One Day
React Native One Day
 
Test Driven Development with JavaFX
Test Driven Development with JavaFXTest Driven Development with JavaFX
Test Driven Development with JavaFX
 
visiblity and scope.pptx
visiblity and scope.pptxvisiblity and scope.pptx
visiblity and scope.pptx
 
Lab11bRevf.docLab 11b Alien InvasionCS 122 • 15 Points .docx
Lab11bRevf.docLab 11b Alien InvasionCS 122 • 15 Points .docxLab11bRevf.docLab 11b Alien InvasionCS 122 • 15 Points .docx
Lab11bRevf.docLab 11b Alien InvasionCS 122 • 15 Points .docx
 
Lists and scrollbars
Lists and scrollbarsLists and scrollbars
Lists and scrollbars
 
Unit iii
Unit iiiUnit iii
Unit iii
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
 
Lecture 1 interfaces and polymorphism
Lecture 1    interfaces and polymorphismLecture 1    interfaces and polymorphism
Lecture 1 interfaces and polymorphism
 
Function
Function Function
Function
 

Recently uploaded

Monthly Economic Monitoring of Ukraine No. 232, May 2024
Monthly Economic Monitoring of Ukraine No. 232, May 2024Monthly Economic Monitoring of Ukraine No. 232, May 2024
一比一原版BCU毕业证伯明翰城市大学毕业证成绩单如何办理
一比一原版BCU毕业证伯明翰城市大学毕业证成绩单如何办理一比一原版BCU毕业证伯明翰城市大学毕业证成绩单如何办理
一比一原版BCU毕业证伯明翰城市大学毕业证成绩单如何办理
ydubwyt
 
PD ARRAY THEORY FOR INTERMEDIATE (1).pdf
PD ARRAY THEORY FOR INTERMEDIATE (1).pdfPD ARRAY THEORY FOR INTERMEDIATE (1).pdf
PD ARRAY THEORY FOR INTERMEDIATE (1).pdf
JerrySMaliki
 
一比一原版Adelaide毕业证阿德莱德大学毕业证成绩单如何办理
一比一原版Adelaide毕业证阿德莱德大学毕业证成绩单如何办理一比一原版Adelaide毕业证阿德莱德大学毕业证成绩单如何办理
一比一原版Adelaide毕业证阿德莱德大学毕业证成绩单如何办理
zsewypy
 

Recently uploaded (20)

how do I get a legit pi buyer in the internet (2024)
how do I get a legit pi buyer in the internet (2024)how do I get a legit pi buyer in the internet (2024)
how do I get a legit pi buyer in the internet (2024)
 
where can I purchase things with pi coins online
where can I purchase things with pi coins onlinewhere can I purchase things with pi coins online
where can I purchase things with pi coins online
 
Juspay Case study(Doubling Revenue Juspay's Success).pptx
Juspay Case study(Doubling Revenue Juspay's Success).pptxJuspay Case study(Doubling Revenue Juspay's Success).pptx
Juspay Case study(Doubling Revenue Juspay's Success).pptx
 
Monthly Economic Monitoring of Ukraine No. 232, May 2024
Monthly Economic Monitoring of Ukraine No. 232, May 2024Monthly Economic Monitoring of Ukraine No. 232, May 2024
Monthly Economic Monitoring of Ukraine No. 232, May 2024
 
The new type of smart, sustainable entrepreneurship and the next day | Europe...
The new type of smart, sustainable entrepreneurship and the next day | Europe...The new type of smart, sustainable entrepreneurship and the next day | Europe...
The new type of smart, sustainable entrepreneurship and the next day | Europe...
 
what is the best method to sell pi coins in 2024
what is the best method to sell pi coins in 2024what is the best method to sell pi coins in 2024
what is the best method to sell pi coins in 2024
 
Commercial Bank Economic Capsule - May 2024
Commercial Bank Economic Capsule - May 2024Commercial Bank Economic Capsule - May 2024
Commercial Bank Economic Capsule - May 2024
 
Bitcoin Masterclass TechweekNZ v3.1.pptx
Bitcoin Masterclass TechweekNZ v3.1.pptxBitcoin Masterclass TechweekNZ v3.1.pptx
Bitcoin Masterclass TechweekNZ v3.1.pptx
 
9th issue of our inhouse magazine Ingenious May 2024.pdf
9th issue of our inhouse magazine Ingenious May 2024.pdf9th issue of our inhouse magazine Ingenious May 2024.pdf
9th issue of our inhouse magazine Ingenious May 2024.pdf
 
How can I sell my pi coins in Indonesia?
How can I  sell my pi coins in Indonesia?How can I  sell my pi coins in Indonesia?
How can I sell my pi coins in Indonesia?
 
Falcon Invoice Discounting: Optimizing Returns with Minimal Risk
Falcon Invoice Discounting: Optimizing Returns with Minimal RiskFalcon Invoice Discounting: Optimizing Returns with Minimal Risk
Falcon Invoice Discounting: Optimizing Returns with Minimal Risk
 
Monthly Market Risk Update: May 2024 [SlideShare]
Monthly Market Risk Update: May 2024 [SlideShare]Monthly Market Risk Update: May 2024 [SlideShare]
Monthly Market Risk Update: May 2024 [SlideShare]
 
how can I transfer pi coins to someone in a different country.
how can I transfer pi coins to someone in a different country.how can I transfer pi coins to someone in a different country.
how can I transfer pi coins to someone in a different country.
 
how can I send my pi coins to Binance exchange
how can I send my pi coins to Binance exchangehow can I send my pi coins to Binance exchange
how can I send my pi coins to Binance exchange
 
Most Profitable Cryptocurrency to Invest in 2024.pdf
Most Profitable Cryptocurrency to Invest in 2024.pdfMost Profitable Cryptocurrency to Invest in 2024.pdf
Most Profitable Cryptocurrency to Invest in 2024.pdf
 
Summary of financial results for 1Q2024
Summary of financial  results for 1Q2024Summary of financial  results for 1Q2024
Summary of financial results for 1Q2024
 
how to sell pi coins in Canada, Uk and Australia
how to sell pi coins in Canada, Uk and Australiahow to sell pi coins in Canada, Uk and Australia
how to sell pi coins in Canada, Uk and Australia
 
一比一原版BCU毕业证伯明翰城市大学毕业证成绩单如何办理
一比一原版BCU毕业证伯明翰城市大学毕业证成绩单如何办理一比一原版BCU毕业证伯明翰城市大学毕业证成绩单如何办理
一比一原版BCU毕业证伯明翰城市大学毕业证成绩单如何办理
 
PD ARRAY THEORY FOR INTERMEDIATE (1).pdf
PD ARRAY THEORY FOR INTERMEDIATE (1).pdfPD ARRAY THEORY FOR INTERMEDIATE (1).pdf
PD ARRAY THEORY FOR INTERMEDIATE (1).pdf
 
一比一原版Adelaide毕业证阿德莱德大学毕业证成绩单如何办理
一比一原版Adelaide毕业证阿德莱德大学毕业证成绩单如何办理一比一原版Adelaide毕业证阿德莱德大学毕业证成绩单如何办理
一比一原版Adelaide毕业证阿德莱德大学毕业证成绩单如何办理
 

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

  1. 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.