SlideShare a Scribd company logo
1 of 22
An Introduction To Software
Development Using Python
Spring Semester, 2014
Class #17:
Functions, Part 1
The Worst Homework Assignment
EVER!
• Using the 15 sets of patient data that you’ve
been given in Homework #2, sort each one of
them in ascending order based on each of the
11 fields in a record.
Image Credit: luluscottage.blogspot.com
2nd Worst Homework Assignment
EVER!
• Now, using the 15 sets of patient data that
you’ve been given in Homework #2, sort each
one of them in DECENDING order based on
each of the 11 fields in a record.
Image Credit: www.clipartpanda.com343 × 350
We Have A Problem
• We are running a VERY successful ice cream store.
• Creating an ice cream cone is a 3-step process:
1. Select flavor of ice cream
2. Construct cone
3. Add toppings
• As the store owner we have two problems:
consistent quality, minimizing training time.
Image Credit: www.etsy.com
I Got 99 Problems But
Quality Ain't One
• Select flavor of ice cream
– Check inventory for available flavors
– Separate ice cream from yogurt
– Get user selection
• Construct cone
– Select cone type: waffle, sugar, regular
– Determine # of scoops: 1, 2, 3, crazy
• Add toppings
– Check inventory for available flavors
– Separate into regular and premium toppings
– Get user selection
Image Credit: modresdes.com
Training Is Going To Be A Pain
1. Check inventory for available flavors
2. Separate ice cream from yogurt
3. Get user selection
4. Select cone type: waffle, sugar, regular
5. Determine # of scoops: 1, 2, 3, crazy
6. Check inventory for available flavors
7. Separate into regular and premium toppings
8. Get user selection
Image Credit: www.gograph.com
What Is Our Python Code Going To
Look Like?
# drive through order
Check inventory for available flavors
Separate ice cream from yogurt
Get user selection
Select cone type: waffle, sugar, regular
Determine # of scoops: 1, 2, 3, crazy
Check inventory for available flavors
Separate into regular and premium toppings
Get user selection
# walk-up order
Check inventory for available flavors
Separate ice cream from yogurt
Get user selection
Select cone type: waffle, sugar, regular
Determine # of scoops: 1, 2, 3, crazy
Check inventory for available flavors
Separate into regular and premium toppings
Get user selection
# online order
Check inventory for available flavors
Separate ice cream from yogurt
Get user selection
Select cone type: waffle, sugar, regular
Determine # of scoops: 1, 2, 3, crazy
Check inventory for available flavors
Separate into regular and premium toppings
Get user selection
# phone-in order
Check inventory for available flavors
Separate ice cream from yogurt
Get user selection
Select cone type: waffle, sugar, regular
Determine # of scoops: 1, 2, 3, crazy
Check inventory for available flavors
Separate into regular and premium toppings
Get user selection
Image Credit: pixshark.com
There Has To Be A Better Way To
Make Ice Cream Cones!
• In Python, a function packages a computation consisting of multiple steps
into a form that can be easily understood and reused.
– e.g. Select flavor of ice cream, Construct cone, Add toppings
• A function is a sequence of instructions with a name.
• You call a function in order to execute its instructions. For example,
consider the following program statement:
price = round(6.8275, 2) # Sets result to 6.83
Image Credit: www.clipartpanda.com
What Happens When You Call A
Function?
price = round(6.8275, 2)
“Arguments”
Note: Multiple arguments
can be passed to a function.
Only one value can be returned.
Benefits Of Using Functions
• The first reason is reusability. Once a function is
defined, it can be used over and over and over again.
You can invoke the same function many times in your
program, which saves you work.
• A single function can be used in several different
programs. When you need to write a new program,
you can go back to your old programs, find the
functions you need, and reuse those functions in
your new program.
• The second reason is abstraction. If you just want to
use the function in your program, you don't have to
know how it works inside! You don't have to
understand anything about what goes on inside the
function.
How To Create A Function
• When writing this function, you need to
– Pick a name for the function (selectFlavor).
– Define a variable for each argument (yogurt).
• These variables are called the parameter variables.
• Put all this information together along with the def reserved
word to form the first line of the function’s definition:
def selectFlavor(yogurt) :
• This line is called the header of the function.
Image Credit: imgarcade.com
Create The Body Of The Function
• The body contains the statements that are
executed when the function is called.
listOfFlavors = checkInventory()
while flavor in listOfFlavors
print(listOfFlavors[flavor])
if (yogurt) :
selection = input(“Please enter the flavor of yogurt you would like:”)
else :
selection = input(“Please enter the flavor of ice cream you would like:”)
Image Credit: www.pinterest.com
Send The Result Back
• In order to return the result of the function,
use the return statement:
return selection
Image Credit: www.clipartpanda.com
Final Form Of Our Function
def selectFlavor(yogurt) :
listOfFlavors = checkInventory()
while flavor in listOfFlavors
print(listOfFlavors[flavor])
if (yogurt == 1) :
selection = input(“Please enter the flavor of yogurt you would like:”)
else :
selection = input(“Please enter the flavor of ice cream you would like:”)
return selection
Note: A function is a compound statement, which requires the statements
in the body to be indented to the same level.
Image Credit: www.clipartpanda.com
Definition Of A Function
Order Matters!
• Python is an interpreted language. This means
that it needs to “see” a function before you
call it…
myChoice = selectFlavor(0)
myChoice = selectFlavor(0)
Image Credit: www.dreamstime.com
Order Definition Weirdness
• It turns out that you CAN call a function
before it is defined – from another function.
def a() :
c = b(4)
return (c)
def b(d) :
d =10
return(d)
Image Credit: www.acclaimclipart.com
Functions: Going All In
• It is possible to create a Python program that
is all functions…
def main():
temp = a
def a() :
c = b(4)
return (c)
def b(d) :
d =10
return(d)
# start program
main()
Revisiting The Worst Homework
Assignment EVER!
• Using the 15 sets of patient data that you’ve
been given in Homework #2, sort each one of
them in ascending order based on each of the
11 fields in a record…
• … using functions.
Image Credit: www.spiritofthesouth.net
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. Functions, Part 1
Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/
What We’ll Be Covering Next Time
1. Functions, Part 2
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

Similar to An Introduction To Python - Functions, Part 1

An Introduction To Software Development - Final Review
An Introduction To Software Development - Final ReviewAn Introduction To Software Development - Final Review
An Introduction To Software Development - Final ReviewBlue Elephant Consulting
 
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
 
Conjoint Analysis - Part 1/3
Conjoint Analysis - Part 1/3Conjoint Analysis - Part 1/3
Conjoint Analysis - Part 1/3Minha Hwang
 
Summarization and opinion detection in product reviews
Summarization and opinion detection in product reviewsSummarization and opinion detection in product reviews
Summarization and opinion detection in product reviewspapanaboinasuman
 
An Introduction To Software Development - Testing, Continuous integration
An Introduction To Software Development - Testing, Continuous integrationAn Introduction To Software Development - Testing, Continuous integration
An Introduction To Software Development - Testing, Continuous integrationBlue Elephant Consulting
 
URUG Ruby on Rails Workshop - Sesssion 5
URUG Ruby on Rails Workshop - Sesssion 5URUG Ruby on Rails Workshop - Sesssion 5
URUG Ruby on Rails Workshop - Sesssion 5jakemallory
 
The Art of Giving and Receiving Code Reviews
The Art of Giving and Receiving Code ReviewsThe Art of Giving and Receiving Code Reviews
The Art of Giving and Receiving Code ReviewsAlexandra Hill
 
Method based views in django applications
Method based views in django applicationsMethod based views in django applications
Method based views in django applicationsGary Reynolds
 
Droidcon Spain 2105 - One app to rule them all: Methodologies, Tools & Tricks...
Droidcon Spain 2105 - One app to rule them all: Methodologies, Tools & Tricks...Droidcon Spain 2105 - One app to rule them all: Methodologies, Tools & Tricks...
Droidcon Spain 2105 - One app to rule them all: Methodologies, Tools & Tricks...Daniel Gallego Vico
 
Uncovering breaking changes behind UI on mobile applications
Uncovering breaking changes behind UI on mobile applicationsUncovering breaking changes behind UI on mobile applications
Uncovering breaking changes behind UI on mobile applicationsKazuaki Matsuo
 
Make me a sandwich, Tienda
Make me a sandwich, TiendaMake me a sandwich, Tienda
Make me a sandwich, Tiendapolakluk
 
Fundamental Design Patterns.pptx
Fundamental Design Patterns.pptxFundamental Design Patterns.pptx
Fundamental Design Patterns.pptxJUNSHIN8
 
Aki Salmi - Refactoring legacy code: a true story @ I T.A.K.E. Unconference 2...
Aki Salmi - Refactoring legacy code: a true story @ I T.A.K.E. Unconference 2...Aki Salmi - Refactoring legacy code: a true story @ I T.A.K.E. Unconference 2...
Aki Salmi - Refactoring legacy code: a true story @ I T.A.K.E. Unconference 2...Mozaic Works
 
Writing Testable Code
Writing Testable CodeWriting Testable Code
Writing Testable Codejameshalsall
 
Automated testing with Cypress
Automated testing with CypressAutomated testing with Cypress
Automated testing with CypressYong Shean Chong
 
#42 green lantern framework
#42   green lantern framework#42   green lantern framework
#42 green lantern frameworkSrilu Balla
 
User Story Mapping
User Story MappingUser Story Mapping
User Story MappingStefano Leli
 

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

An Introduction To Software Development - Final Review
An Introduction To Software Development - Final ReviewAn Introduction To Software Development - Final Review
An Introduction To Software Development - Final Review
 
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
 
Conjoint Analysis - Part 1/3
Conjoint Analysis - Part 1/3Conjoint Analysis - Part 1/3
Conjoint Analysis - Part 1/3
 
Summarization and opinion detection in product reviews
Summarization and opinion detection in product reviewsSummarization and opinion detection in product reviews
Summarization and opinion detection in product reviews
 
An Introduction To Software Development - Testing, Continuous integration
An Introduction To Software Development - Testing, Continuous integrationAn Introduction To Software Development - Testing, Continuous integration
An Introduction To Software Development - Testing, Continuous integration
 
Intro To C++ - Class #19: Functions
Intro To C++ - Class #19: FunctionsIntro To C++ - Class #19: Functions
Intro To C++ - Class #19: Functions
 
C++ super market
C++ super marketC++ super market
C++ super market
 
URUG Ruby on Rails Workshop - Sesssion 5
URUG Ruby on Rails Workshop - Sesssion 5URUG Ruby on Rails Workshop - Sesssion 5
URUG Ruby on Rails Workshop - Sesssion 5
 
The Art of Giving and Receiving Code Reviews
The Art of Giving and Receiving Code ReviewsThe Art of Giving and Receiving Code Reviews
The Art of Giving and Receiving Code Reviews
 
Method based views in django applications
Method based views in django applicationsMethod based views in django applications
Method based views in django applications
 
Droidcon Spain 2105 - One app to rule them all: Methodologies, Tools & Tricks...
Droidcon Spain 2105 - One app to rule them all: Methodologies, Tools & Tricks...Droidcon Spain 2105 - One app to rule them all: Methodologies, Tools & Tricks...
Droidcon Spain 2105 - One app to rule them all: Methodologies, Tools & Tricks...
 
Performance Tuning with XHProf
Performance Tuning with XHProfPerformance Tuning with XHProf
Performance Tuning with XHProf
 
Uncovering breaking changes behind UI on mobile applications
Uncovering breaking changes behind UI on mobile applicationsUncovering breaking changes behind UI on mobile applications
Uncovering breaking changes behind UI on mobile applications
 
Make me a sandwich, Tienda
Make me a sandwich, TiendaMake me a sandwich, Tienda
Make me a sandwich, Tienda
 
Fundamental Design Patterns.pptx
Fundamental Design Patterns.pptxFundamental Design Patterns.pptx
Fundamental Design Patterns.pptx
 
Aki Salmi - Refactoring legacy code: a true story @ I T.A.K.E. Unconference 2...
Aki Salmi - Refactoring legacy code: a true story @ I T.A.K.E. Unconference 2...Aki Salmi - Refactoring legacy code: a true story @ I T.A.K.E. Unconference 2...
Aki Salmi - Refactoring legacy code: a true story @ I T.A.K.E. Unconference 2...
 
Writing Testable Code
Writing Testable CodeWriting Testable Code
Writing Testable Code
 
Automated testing with Cypress
Automated testing with CypressAutomated testing with Cypress
Automated testing with Cypress
 
#42 green lantern framework
#42   green lantern framework#42   green lantern framework
#42 green lantern framework
 
User Story Mapping
User Story MappingUser Story Mapping
User Story Mapping
 

Recently uploaded

Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 

Recently uploaded (20)

Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 

An Introduction To Python - Functions, Part 1

  • 1. An Introduction To Software Development Using Python Spring Semester, 2014 Class #17: Functions, Part 1
  • 2. The Worst Homework Assignment EVER! • Using the 15 sets of patient data that you’ve been given in Homework #2, sort each one of them in ascending order based on each of the 11 fields in a record. Image Credit: luluscottage.blogspot.com
  • 3. 2nd Worst Homework Assignment EVER! • Now, using the 15 sets of patient data that you’ve been given in Homework #2, sort each one of them in DECENDING order based on each of the 11 fields in a record. Image Credit: www.clipartpanda.com343 × 350
  • 4. We Have A Problem • We are running a VERY successful ice cream store. • Creating an ice cream cone is a 3-step process: 1. Select flavor of ice cream 2. Construct cone 3. Add toppings • As the store owner we have two problems: consistent quality, minimizing training time. Image Credit: www.etsy.com
  • 5. I Got 99 Problems But Quality Ain't One • Select flavor of ice cream – Check inventory for available flavors – Separate ice cream from yogurt – Get user selection • Construct cone – Select cone type: waffle, sugar, regular – Determine # of scoops: 1, 2, 3, crazy • Add toppings – Check inventory for available flavors – Separate into regular and premium toppings – Get user selection Image Credit: modresdes.com
  • 6. Training Is Going To Be A Pain 1. Check inventory for available flavors 2. Separate ice cream from yogurt 3. Get user selection 4. Select cone type: waffle, sugar, regular 5. Determine # of scoops: 1, 2, 3, crazy 6. Check inventory for available flavors 7. Separate into regular and premium toppings 8. Get user selection Image Credit: www.gograph.com
  • 7. What Is Our Python Code Going To Look Like? # drive through order Check inventory for available flavors Separate ice cream from yogurt Get user selection Select cone type: waffle, sugar, regular Determine # of scoops: 1, 2, 3, crazy Check inventory for available flavors Separate into regular and premium toppings Get user selection # walk-up order Check inventory for available flavors Separate ice cream from yogurt Get user selection Select cone type: waffle, sugar, regular Determine # of scoops: 1, 2, 3, crazy Check inventory for available flavors Separate into regular and premium toppings Get user selection # online order Check inventory for available flavors Separate ice cream from yogurt Get user selection Select cone type: waffle, sugar, regular Determine # of scoops: 1, 2, 3, crazy Check inventory for available flavors Separate into regular and premium toppings Get user selection # phone-in order Check inventory for available flavors Separate ice cream from yogurt Get user selection Select cone type: waffle, sugar, regular Determine # of scoops: 1, 2, 3, crazy Check inventory for available flavors Separate into regular and premium toppings Get user selection Image Credit: pixshark.com
  • 8. There Has To Be A Better Way To Make Ice Cream Cones! • In Python, a function packages a computation consisting of multiple steps into a form that can be easily understood and reused. – e.g. Select flavor of ice cream, Construct cone, Add toppings • A function is a sequence of instructions with a name. • You call a function in order to execute its instructions. For example, consider the following program statement: price = round(6.8275, 2) # Sets result to 6.83 Image Credit: www.clipartpanda.com
  • 9. What Happens When You Call A Function? price = round(6.8275, 2) “Arguments” Note: Multiple arguments can be passed to a function. Only one value can be returned.
  • 10. Benefits Of Using Functions • The first reason is reusability. Once a function is defined, it can be used over and over and over again. You can invoke the same function many times in your program, which saves you work. • A single function can be used in several different programs. When you need to write a new program, you can go back to your old programs, find the functions you need, and reuse those functions in your new program. • The second reason is abstraction. If you just want to use the function in your program, you don't have to know how it works inside! You don't have to understand anything about what goes on inside the function.
  • 11. How To Create A Function • When writing this function, you need to – Pick a name for the function (selectFlavor). – Define a variable for each argument (yogurt). • These variables are called the parameter variables. • Put all this information together along with the def reserved word to form the first line of the function’s definition: def selectFlavor(yogurt) : • This line is called the header of the function. Image Credit: imgarcade.com
  • 12. Create The Body Of The Function • The body contains the statements that are executed when the function is called. listOfFlavors = checkInventory() while flavor in listOfFlavors print(listOfFlavors[flavor]) if (yogurt) : selection = input(“Please enter the flavor of yogurt you would like:”) else : selection = input(“Please enter the flavor of ice cream you would like:”) Image Credit: www.pinterest.com
  • 13. Send The Result Back • In order to return the result of the function, use the return statement: return selection Image Credit: www.clipartpanda.com
  • 14. Final Form Of Our Function def selectFlavor(yogurt) : listOfFlavors = checkInventory() while flavor in listOfFlavors print(listOfFlavors[flavor]) if (yogurt == 1) : selection = input(“Please enter the flavor of yogurt you would like:”) else : selection = input(“Please enter the flavor of ice cream you would like:”) return selection Note: A function is a compound statement, which requires the statements in the body to be indented to the same level. Image Credit: www.clipartpanda.com
  • 15. Definition Of A Function
  • 16. Order Matters! • Python is an interpreted language. This means that it needs to “see” a function before you call it… myChoice = selectFlavor(0) myChoice = selectFlavor(0) Image Credit: www.dreamstime.com
  • 17. Order Definition Weirdness • It turns out that you CAN call a function before it is defined – from another function. def a() : c = b(4) return (c) def b(d) : d =10 return(d) Image Credit: www.acclaimclipart.com
  • 18. Functions: Going All In • It is possible to create a Python program that is all functions… def main(): temp = a def a() : c = b(4) return (c) def b(d) : d =10 return(d) # start program main()
  • 19. Revisiting The Worst Homework Assignment EVER! • Using the 15 sets of patient data that you’ve been given in Homework #2, sort each one of them in ascending order based on each of the 11 fields in a record… • … using functions. Image Credit: www.spiritofthesouth.net
  • 20. What’s In Your Python Toolbox? print() math strings I/O IF/Else elif While For Lists And / Or Functions
  • 21. What We Covered Today 1. Functions, Part 1 Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/
  • 22. What We’ll Be Covering Next Time 1. Functions, Part 2 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.