SlideShare a Scribd company logo
1 of 23
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

An Introduction To Python - Python, Print()
An Introduction To Python - Python, Print()An Introduction To Python - Python, Print()
An Introduction To Python - Python, Print()Blue Elephant Consulting
 
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 MaintenanceBlue Elephant Consulting
 
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 ReviewBlue Elephant Consulting
 
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 DesignBlue Elephant Consulting
 
An Introduction To Python - Variables, Math
An Introduction To Python - Variables, MathAn Introduction To Python - Variables, Math
An Introduction To Python - Variables, MathBlue Elephant Consulting
 
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 DataBlue Elephant Consulting
 
An Introduction To Software Development - Implementation
An Introduction To Software Development - ImplementationAn Introduction To Software Development - Implementation
An Introduction To Software Development - ImplementationBlue Elephant Consulting
 
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 AlgorithmsBlue Elephant Consulting
 

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

11.C++Polymorphism [Autosaved].pptx
11.C++Polymorphism [Autosaved].pptx11.C++Polymorphism [Autosaved].pptx
11.C++Polymorphism [Autosaved].pptxAtharvPotdar2
 
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 ReviewBlue Elephant Consulting
 
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, RecursionBlue Elephant Consulting
 
React Development with the MERN Stack
React Development with the MERN StackReact Development with the MERN Stack
React Development with the MERN StackTroy Miles
 
Graphics on the Go
Graphics on the GoGraphics on the Go
Graphics on the GoGil Irizarry
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: ServersidenessWebExpo
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme SwiftMovel
 
React Native One Day
React Native One DayReact Native One Day
React Native One DayTroy Miles
 
Test Driven Development with JavaFX
Test Driven Development with JavaFXTest Driven Development with JavaFX
Test Driven Development with JavaFXHendrik Ebbers
 
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 .docxDIPESH30
 
Lists and scrollbars
Lists and scrollbarsLists and scrollbars
Lists and scrollbarsmyrajendra
 
Lecture 1 interfaces and polymorphism
Lecture 1    interfaces and polymorphismLecture 1    interfaces and polymorphism
Lecture 1 interfaces and polymorphismNada G.Youssef
 

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

Nalasopara TRusted Virar-Vasai-Housewife Call Girls✔✔9833754194 Gorgeous Mode...
Nalasopara TRusted Virar-Vasai-Housewife Call Girls✔✔9833754194 Gorgeous Mode...Nalasopara TRusted Virar-Vasai-Housewife Call Girls✔✔9833754194 Gorgeous Mode...
Nalasopara TRusted Virar-Vasai-Housewife Call Girls✔✔9833754194 Gorgeous Mode...priyasharma62062
 
Technology industry / Finnish economic outlook
Technology industry / Finnish economic outlookTechnology industry / Finnish economic outlook
Technology industry / Finnish economic outlookTechFinland
 
Garia ^ (Call Girls) in Kolkata - Book 8005736733 Call Girls Available 24 Hou...
Garia ^ (Call Girls) in Kolkata - Book 8005736733 Call Girls Available 24 Hou...Garia ^ (Call Girls) in Kolkata - Book 8005736733 Call Girls Available 24 Hou...
Garia ^ (Call Girls) in Kolkata - Book 8005736733 Call Girls Available 24 Hou...HyderabadDolls
 
✂️ 👅 Independent Bhubaneswar Escorts Odisha Call Girls With Room Bhubaneswar ...
✂️ 👅 Independent Bhubaneswar Escorts Odisha Call Girls With Room Bhubaneswar ...✂️ 👅 Independent Bhubaneswar Escorts Odisha Call Girls With Room Bhubaneswar ...
✂️ 👅 Independent Bhubaneswar Escorts Odisha Call Girls With Room Bhubaneswar ...Call Girls Mumbai
 
Russian Call Girls New Bhubaneswar Whatsapp Numbers 9777949614 Russian Escor...
Russian Call Girls New Bhubaneswar Whatsapp Numbers 9777949614  Russian Escor...Russian Call Girls New Bhubaneswar Whatsapp Numbers 9777949614  Russian Escor...
Russian Call Girls New Bhubaneswar Whatsapp Numbers 9777949614 Russian Escor...jabtakhaidam7
 
cost-volume-profit analysis.ppt(managerial accounting).pptx
cost-volume-profit analysis.ppt(managerial accounting).pptxcost-volume-profit analysis.ppt(managerial accounting).pptx
cost-volume-profit analysis.ppt(managerial accounting).pptxazadalisthp2020i
 
Female Russian Escorts Mumbai Call Girls-((ANdheri))9833754194-Jogeshawri Fre...
Female Russian Escorts Mumbai Call Girls-((ANdheri))9833754194-Jogeshawri Fre...Female Russian Escorts Mumbai Call Girls-((ANdheri))9833754194-Jogeshawri Fre...
Female Russian Escorts Mumbai Call Girls-((ANdheri))9833754194-Jogeshawri Fre...priyasharma62062
 
Thane Call Girls , 07506202331 Kalyan Call Girls
Thane Call Girls , 07506202331 Kalyan Call GirlsThane Call Girls , 07506202331 Kalyan Call Girls
Thane Call Girls , 07506202331 Kalyan Call GirlsPriya Reddy
 
Kurla Capable Call Girls ,07506202331, Sion Affordable Call Girls
Kurla Capable Call Girls ,07506202331, Sion Affordable Call GirlsKurla Capable Call Girls ,07506202331, Sion Affordable Call Girls
Kurla Capable Call Girls ,07506202331, Sion Affordable Call GirlsPriya Reddy
 
Bhayandar Capable Call Girls ,07506202331,Mira Road Beautiful Call Girl
Bhayandar Capable Call Girls ,07506202331,Mira Road Beautiful Call GirlBhayandar Capable Call Girls ,07506202331,Mira Road Beautiful Call Girl
Bhayandar Capable Call Girls ,07506202331,Mira Road Beautiful Call GirlPriya Reddy
 
Pension dashboards forum 1 May 2024 (1).pdf
Pension dashboards forum 1 May 2024 (1).pdfPension dashboards forum 1 May 2024 (1).pdf
Pension dashboards forum 1 May 2024 (1).pdfHenry Tapper
 
Seeman_Fiintouch_LLP_Newsletter_May-2024.pdf
Seeman_Fiintouch_LLP_Newsletter_May-2024.pdfSeeman_Fiintouch_LLP_Newsletter_May-2024.pdf
Seeman_Fiintouch_LLP_Newsletter_May-2024.pdfAshis Kumar Dey
 
Q1 2024 Conference Call Presentation vF.pdf
Q1 2024 Conference Call Presentation vF.pdfQ1 2024 Conference Call Presentation vF.pdf
Q1 2024 Conference Call Presentation vF.pdfAdnet Communications
 
Bhubaneswar🌹Ravi Tailkes ❤CALL GIRLS 9777949614 💟 CALL GIRLS IN bhubaneswar ...
Bhubaneswar🌹Ravi Tailkes  ❤CALL GIRLS 9777949614 💟 CALL GIRLS IN bhubaneswar ...Bhubaneswar🌹Ravi Tailkes  ❤CALL GIRLS 9777949614 💟 CALL GIRLS IN bhubaneswar ...
Bhubaneswar🌹Ravi Tailkes ❤CALL GIRLS 9777949614 💟 CALL GIRLS IN bhubaneswar ...Call Girls Mumbai
 
Call Girls in Benson Town / 8250092165 Genuine Call girls with real Photos an...
Call Girls in Benson Town / 8250092165 Genuine Call girls with real Photos an...Call Girls in Benson Town / 8250092165 Genuine Call girls with real Photos an...
Call Girls in Benson Town / 8250092165 Genuine Call girls with real Photos an...kajal
 
Webinar on E-Invoicing for Fintech Belgium
Webinar on E-Invoicing for Fintech BelgiumWebinar on E-Invoicing for Fintech Belgium
Webinar on E-Invoicing for Fintech BelgiumFinTech Belgium
 
Turbhe Fantastic Escorts📞📞9833754194 Kopar Khairane Marathi Call Girls-Kopar ...
Turbhe Fantastic Escorts📞📞9833754194 Kopar Khairane Marathi Call Girls-Kopar ...Turbhe Fantastic Escorts📞📞9833754194 Kopar Khairane Marathi Call Girls-Kopar ...
Turbhe Fantastic Escorts📞📞9833754194 Kopar Khairane Marathi Call Girls-Kopar ...priyasharma62062
 
[[Nerul]] MNavi Mumbai Honoreble Call Girls Number-9833754194-Panvel Best Es...
[[Nerul]] MNavi Mumbai Honoreble  Call Girls Number-9833754194-Panvel Best Es...[[Nerul]] MNavi Mumbai Honoreble  Call Girls Number-9833754194-Panvel Best Es...
[[Nerul]] MNavi Mumbai Honoreble Call Girls Number-9833754194-Panvel Best Es...priyasharma62062
 
Dubai Call Girls Deira O525547819 Dubai Call Girls Bur Dubai Multiple
Dubai Call Girls Deira O525547819 Dubai Call Girls Bur Dubai MultipleDubai Call Girls Deira O525547819 Dubai Call Girls Bur Dubai Multiple
Dubai Call Girls Deira O525547819 Dubai Call Girls Bur Dubai Multiplekojalpk89
 

Recently uploaded (20)

Nalasopara TRusted Virar-Vasai-Housewife Call Girls✔✔9833754194 Gorgeous Mode...
Nalasopara TRusted Virar-Vasai-Housewife Call Girls✔✔9833754194 Gorgeous Mode...Nalasopara TRusted Virar-Vasai-Housewife Call Girls✔✔9833754194 Gorgeous Mode...
Nalasopara TRusted Virar-Vasai-Housewife Call Girls✔✔9833754194 Gorgeous Mode...
 
Technology industry / Finnish economic outlook
Technology industry / Finnish economic outlookTechnology industry / Finnish economic outlook
Technology industry / Finnish economic outlook
 
Garia ^ (Call Girls) in Kolkata - Book 8005736733 Call Girls Available 24 Hou...
Garia ^ (Call Girls) in Kolkata - Book 8005736733 Call Girls Available 24 Hou...Garia ^ (Call Girls) in Kolkata - Book 8005736733 Call Girls Available 24 Hou...
Garia ^ (Call Girls) in Kolkata - Book 8005736733 Call Girls Available 24 Hou...
 
✂️ 👅 Independent Bhubaneswar Escorts Odisha Call Girls With Room Bhubaneswar ...
✂️ 👅 Independent Bhubaneswar Escorts Odisha Call Girls With Room Bhubaneswar ...✂️ 👅 Independent Bhubaneswar Escorts Odisha Call Girls With Room Bhubaneswar ...
✂️ 👅 Independent Bhubaneswar Escorts Odisha Call Girls With Room Bhubaneswar ...
 
Call Girls in Tilak Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in Tilak Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in Tilak Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in Tilak Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
 
Russian Call Girls New Bhubaneswar Whatsapp Numbers 9777949614 Russian Escor...
Russian Call Girls New Bhubaneswar Whatsapp Numbers 9777949614  Russian Escor...Russian Call Girls New Bhubaneswar Whatsapp Numbers 9777949614  Russian Escor...
Russian Call Girls New Bhubaneswar Whatsapp Numbers 9777949614 Russian Escor...
 
cost-volume-profit analysis.ppt(managerial accounting).pptx
cost-volume-profit analysis.ppt(managerial accounting).pptxcost-volume-profit analysis.ppt(managerial accounting).pptx
cost-volume-profit analysis.ppt(managerial accounting).pptx
 
Female Russian Escorts Mumbai Call Girls-((ANdheri))9833754194-Jogeshawri Fre...
Female Russian Escorts Mumbai Call Girls-((ANdheri))9833754194-Jogeshawri Fre...Female Russian Escorts Mumbai Call Girls-((ANdheri))9833754194-Jogeshawri Fre...
Female Russian Escorts Mumbai Call Girls-((ANdheri))9833754194-Jogeshawri Fre...
 
Thane Call Girls , 07506202331 Kalyan Call Girls
Thane Call Girls , 07506202331 Kalyan Call GirlsThane Call Girls , 07506202331 Kalyan Call Girls
Thane Call Girls , 07506202331 Kalyan Call Girls
 
Kurla Capable Call Girls ,07506202331, Sion Affordable Call Girls
Kurla Capable Call Girls ,07506202331, Sion Affordable Call GirlsKurla Capable Call Girls ,07506202331, Sion Affordable Call Girls
Kurla Capable Call Girls ,07506202331, Sion Affordable Call Girls
 
Bhayandar Capable Call Girls ,07506202331,Mira Road Beautiful Call Girl
Bhayandar Capable Call Girls ,07506202331,Mira Road Beautiful Call GirlBhayandar Capable Call Girls ,07506202331,Mira Road Beautiful Call Girl
Bhayandar Capable Call Girls ,07506202331,Mira Road Beautiful Call Girl
 
Pension dashboards forum 1 May 2024 (1).pdf
Pension dashboards forum 1 May 2024 (1).pdfPension dashboards forum 1 May 2024 (1).pdf
Pension dashboards forum 1 May 2024 (1).pdf
 
Seeman_Fiintouch_LLP_Newsletter_May-2024.pdf
Seeman_Fiintouch_LLP_Newsletter_May-2024.pdfSeeman_Fiintouch_LLP_Newsletter_May-2024.pdf
Seeman_Fiintouch_LLP_Newsletter_May-2024.pdf
 
Q1 2024 Conference Call Presentation vF.pdf
Q1 2024 Conference Call Presentation vF.pdfQ1 2024 Conference Call Presentation vF.pdf
Q1 2024 Conference Call Presentation vF.pdf
 
Bhubaneswar🌹Ravi Tailkes ❤CALL GIRLS 9777949614 💟 CALL GIRLS IN bhubaneswar ...
Bhubaneswar🌹Ravi Tailkes  ❤CALL GIRLS 9777949614 💟 CALL GIRLS IN bhubaneswar ...Bhubaneswar🌹Ravi Tailkes  ❤CALL GIRLS 9777949614 💟 CALL GIRLS IN bhubaneswar ...
Bhubaneswar🌹Ravi Tailkes ❤CALL GIRLS 9777949614 💟 CALL GIRLS IN bhubaneswar ...
 
Call Girls in Benson Town / 8250092165 Genuine Call girls with real Photos an...
Call Girls in Benson Town / 8250092165 Genuine Call girls with real Photos an...Call Girls in Benson Town / 8250092165 Genuine Call girls with real Photos an...
Call Girls in Benson Town / 8250092165 Genuine Call girls with real Photos an...
 
Webinar on E-Invoicing for Fintech Belgium
Webinar on E-Invoicing for Fintech BelgiumWebinar on E-Invoicing for Fintech Belgium
Webinar on E-Invoicing for Fintech Belgium
 
Turbhe Fantastic Escorts📞📞9833754194 Kopar Khairane Marathi Call Girls-Kopar ...
Turbhe Fantastic Escorts📞📞9833754194 Kopar Khairane Marathi Call Girls-Kopar ...Turbhe Fantastic Escorts📞📞9833754194 Kopar Khairane Marathi Call Girls-Kopar ...
Turbhe Fantastic Escorts📞📞9833754194 Kopar Khairane Marathi Call Girls-Kopar ...
 
[[Nerul]] MNavi Mumbai Honoreble Call Girls Number-9833754194-Panvel Best Es...
[[Nerul]] MNavi Mumbai Honoreble  Call Girls Number-9833754194-Panvel Best Es...[[Nerul]] MNavi Mumbai Honoreble  Call Girls Number-9833754194-Panvel Best Es...
[[Nerul]] MNavi Mumbai Honoreble Call Girls Number-9833754194-Panvel Best Es...
 
Dubai Call Girls Deira O525547819 Dubai Call Girls Bur Dubai Multiple
Dubai Call Girls Deira O525547819 Dubai Call Girls Bur Dubai MultipleDubai Call Girls Deira O525547819 Dubai Call Girls Bur Dubai Multiple
Dubai Call Girls Deira O525547819 Dubai Call Girls Bur Dubai Multiple
 

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.