SlideShare a Scribd company logo
1 of 25
Functions
Chapter 4
Python for Everybody
www.py4e.com
Stored (and reused) Steps
Output:
Hello
Fun
Zip
Hello
Fun
Program:
def thing():
print('Hello')
print('Fun')
thing()
print('Zip')
thing()
def
print('Hello')
print('Fun')
thing()
We call these reusable pieces of code “functions”
thing():
thing()
print('Zip')
Python Functions
• There are two kinds of functions in Python.
- Built-in functions that are provided as part of Python - print(),
input(), type(), float(), int() ...
- Functions that we define ourselves and then use
• We treat function names as “new” reserved words
(i.e., we avoid them as variable names)
Function Definition
• In Python a function is some reusable code that takes
arguments(s) as input, does some computation, and then returns
a result or results
• We define a function using the def reserved word
• We call/invoke the function by using the function name,
parentheses, and arguments in an expression
>>> big = max('Hello world')
>>> print(big)
w
>>> tiny = min('Hello world')
>>> print(tiny)
>>>
big = max('Hello world')
Argument
'w'
Result
Assignment
Max Function
>>> big = max('Hello world')
>>> print(big)
w
max()
function
'Hello world'
(a string)
'w'
(a string)
A function is some
stored code that we
use. A function takes
some input and
produces an output.
Guido wrote this code
Max Function
>>> big = max('Hello world')
>>> print(big)
w
def max(inp):
blah
blah
for x in inp:
blah
blah
'Hello world'
(a string)
'w'
(a string)
A function is some
stored code that we
use. A function takes
some input and
produces an output.
Guido wrote this code
Type Conversions
• When you put an integer
and floating point in an
expression, the integer
is implicitly converted to
a float
• You can control this with
the built-in functions int()
and float()
>>> print(float(99) / 100)
0.99
>>> i = 42
>>> type(i)
<class 'int'>
>>> f = float(i)
>>> print(f)
42.0
>>> type(f)
<class 'float'>
>>> print(1 + 2 * float(3) / 4 – 5)
-2.5
>>>
String
Conversions
• You can also use int()
and float() to convert
between strings and
integers
• You will get an error if the
string does not contain
numeric characters
>>> sval = '123'
>>> type(sval)
<class 'str'>
>>> print(sval + 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str'
and 'int'
>>> ival = int(sval)
>>> type(ival)
<class 'int'>
>>> print(ival + 1)
124
>>> nsv = 'hello bob'
>>> niv = int(nsv)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int()
Functions of Our Own…
Building our Own Functions
• We create a new function using the def keyword followed by
optional parameters in parentheses
• We indent the body of the function
• This defines the function but does not execute the body of the
function
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')
x = 5
print('Hello')
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')
print('Yo')
x = x + 2
print(x)
Hello
Yo
7
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')
print_lyrics():
Definitions and Uses
• Once we have defined a function, we can call (or invoke) it
as many times as we like
• This is the store and reuse pattern
x = 5
print('Hello')
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')
print('Yo')
print_lyrics()
x = x + 2
print(x)
Hello
Yo
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
7
Arguments
• An argument is a value we pass into the function as its input
when we call the function
• We use arguments so we can direct the function to do different
kinds of work when we call it at different times
• We put the arguments in parentheses after the name of the
function
big = max('Hello world')
Argument
Parameters
A parameter is a variable which
we use in the function definition.
It is a “handle” that allows the
code in the function to access
the arguments for a particular
function invocation.
>>> def greet(lang):
... if lang == 'es':
... print('Hola')
... elif lang == 'fr':
... print('Bonjour')
... else:
... print('Hello')
...
>>> greet('en')
Hello
>>> greet('es')
Hola
>>> greet('fr')
Bonjour
>>>
Return Values
Often a function will take its arguments, do some computation, and
return a value to be used as the value of the function call in the
calling expression. The return keyword is used for this.
def greet():
return "Hello"
print(greet(), "Glenn")
print(greet(), "Sally")
Hello Glenn
Hello Sally
Return Value
• A “fruitful” function is one
that produces a result (or
return value)
• The return statement ends
the function execution and
“sends back” the result of
the function
>>> def greet(lang):
... if lang == 'es':
... return 'Hola'
... elif lang == 'fr':
... return 'Bonjour'
... else:
... return 'Hello'
...
>>> print(greet('en'),'Glenn')
Hello Glenn
>>> print(greet('es'),'Sally')
Hola Sally
>>> print(greet('fr'),'Michael')
Bonjour Michael
>>>
Arguments, Parameters, and
Results
>>> big = max('Hello world')
>>> print(big)
w
def max(inp):
blah
blah
for x in inp:
blah
blah
return 'w'
'Hello world' 'w'
Argument
Parameter
Result
Multiple Parameters / Arguments
• We can define more than one
parameter in the function
definition
• We simply add more arguments
when we call the function
• We match the number and order
of arguments and parameters
def addtwo(a, b):
added = a + b
return added
x = addtwo(3, 5)
print(x)
8
Void (non-fruitful) Functions
• When a function does not return a value, we call it a “void”
function
• Functions that return values are “fruitful” functions
• Void functions are “not fruitful”
To function or not to function...
• Organize your code into “paragraphs” - capture a complete
thought and “name it”
• Don’t repeat yourself - make it work once and then reuse it
• If something gets too long or complex, break it up into logical
chunks and put those chunks in functions
• Make a library of common stuff that you do over and over -
perhaps share this with your friends...
Summary
• Arguments
• Results (fruitful functions)
• Void (non-fruitful) functions
• Why use functions?
• Functions
• Built-In Functions
• Type conversion (int, float)
• String conversions
• Parameters
Exercise
Rewrite your pay computation with time-and-a-
half for overtime and create a function called
computepay which takes two parameters ( hours
and rate).
Enter Hours: 45
Enter Rate: 10
Pay: 475.0
475 = 40 * 10 + 5 * 15
Acknowledgements / Contributions
These slides are Copyright 2010- Charles R. Severance
(www.dr-chuck.com) of the University of Michigan School of
Information and open.umich.edu and made available under a
Creative Commons Attribution 4.0 License. Please maintain this
last slide in all copies of the document to comply with the
attribution requirements of the license. If you make a change,
feel free to add your name and organization to the list of
contributors on this page as you republish the materials.
Initial Development: Charles Severance, University of Michigan
School of Information
… Insert new Contributors and Translators here
...

More Related Content

Similar to Pythonlearn-04-Functions (1).pptx

An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAdam Getchell
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...Maulik Borsaniya
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++Manzoor ALam
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developersJim Roepcke
 
Chapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer ScienceChapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer ScienceKrithikaTM
 
ch-3 funtions - 1 class 12.pdf
ch-3 funtions - 1 class 12.pdfch-3 funtions - 1 class 12.pdf
ch-3 funtions - 1 class 12.pdfzafar578075
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdfprasnt1
 

Similar to Pythonlearn-04-Functions (1).pptx (20)

3. functions modules_programs (1)
3. functions modules_programs (1)3. functions modules_programs (1)
3. functions modules_programs (1)
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
 
CPP06 - Functions
CPP06 - FunctionsCPP06 - Functions
CPP06 - Functions
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
 
UNIT 3 python.pptx
UNIT 3 python.pptxUNIT 3 python.pptx
UNIT 3 python.pptx
 
Python basics
Python basicsPython basics
Python basics
 
Chapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer ScienceChapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer Science
 
Unit2 input output
Unit2 input outputUnit2 input output
Unit2 input output
 
ch-3 funtions - 1 class 12.pdf
ch-3 funtions - 1 class 12.pdfch-3 funtions - 1 class 12.pdf
ch-3 funtions - 1 class 12.pdf
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
 

Recently uploaded

Dubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls DubaiDubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls Dubaihf8803863
 
04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationships04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationshipsccctableauusergroup
 
Brighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data StorytellingBrighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data StorytellingNeil Barnes
 
Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfLars Albertsson
 
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Jack DiGiovanna
 
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024thyngster
 
20240419 - Measurecamp Amsterdam - SAM.pdf
20240419 - Measurecamp Amsterdam - SAM.pdf20240419 - Measurecamp Amsterdam - SAM.pdf
20240419 - Measurecamp Amsterdam - SAM.pdfHuman37
 
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)jennyeacort
 
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...Sapana Sha
 
Industrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfIndustrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfLars Albertsson
 
Call Girls In Dwarka 9654467111 Escorts Service
Call Girls In Dwarka 9654467111 Escorts ServiceCall Girls In Dwarka 9654467111 Escorts Service
Call Girls In Dwarka 9654467111 Escorts ServiceSapana Sha
 
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Callshivangimorya083
 
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...Suhani Kapoor
 
Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...
Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...
Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...ThinkInnovation
 
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptxEMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptxthyngster
 
办理学位证纽约大学毕业证(NYU毕业证书)原版一比一
办理学位证纽约大学毕业证(NYU毕业证书)原版一比一办理学位证纽约大学毕业证(NYU毕业证书)原版一比一
办理学位证纽约大学毕业证(NYU毕业证书)原版一比一fhwihughh
 

Recently uploaded (20)

Dubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls DubaiDubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls Dubai
 
04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationships04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationships
 
Brighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data StorytellingBrighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data Storytelling
 
Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdf
 
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
 
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024
 
20240419 - Measurecamp Amsterdam - SAM.pdf
20240419 - Measurecamp Amsterdam - SAM.pdf20240419 - Measurecamp Amsterdam - SAM.pdf
20240419 - Measurecamp Amsterdam - SAM.pdf
 
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
 
Call Girls in Saket 99530🔝 56974 Escort Service
Call Girls in Saket 99530🔝 56974 Escort ServiceCall Girls in Saket 99530🔝 56974 Escort Service
Call Girls in Saket 99530🔝 56974 Escort Service
 
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
 
Industrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfIndustrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdf
 
Call Girls In Dwarka 9654467111 Escorts Service
Call Girls In Dwarka 9654467111 Escorts ServiceCall Girls In Dwarka 9654467111 Escorts Service
Call Girls In Dwarka 9654467111 Escorts Service
 
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
 
꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...
꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...
꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...
 
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
 
Decoding Loan Approval: Predictive Modeling in Action
Decoding Loan Approval: Predictive Modeling in ActionDecoding Loan Approval: Predictive Modeling in Action
Decoding Loan Approval: Predictive Modeling in Action
 
Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...
Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...
Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...
 
Deep Generative Learning for All - The Gen AI Hype (Spring 2024)
Deep Generative Learning for All - The Gen AI Hype (Spring 2024)Deep Generative Learning for All - The Gen AI Hype (Spring 2024)
Deep Generative Learning for All - The Gen AI Hype (Spring 2024)
 
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptxEMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
 
办理学位证纽约大学毕业证(NYU毕业证书)原版一比一
办理学位证纽约大学毕业证(NYU毕业证书)原版一比一办理学位证纽约大学毕业证(NYU毕业证书)原版一比一
办理学位证纽约大学毕业证(NYU毕业证书)原版一比一
 

Pythonlearn-04-Functions (1).pptx

  • 1. Functions Chapter 4 Python for Everybody www.py4e.com
  • 2. Stored (and reused) Steps Output: Hello Fun Zip Hello Fun Program: def thing(): print('Hello') print('Fun') thing() print('Zip') thing() def print('Hello') print('Fun') thing() We call these reusable pieces of code “functions” thing(): thing() print('Zip')
  • 3. Python Functions • There are two kinds of functions in Python. - Built-in functions that are provided as part of Python - print(), input(), type(), float(), int() ... - Functions that we define ourselves and then use • We treat function names as “new” reserved words (i.e., we avoid them as variable names)
  • 4. Function Definition • In Python a function is some reusable code that takes arguments(s) as input, does some computation, and then returns a result or results • We define a function using the def reserved word • We call/invoke the function by using the function name, parentheses, and arguments in an expression
  • 5. >>> big = max('Hello world') >>> print(big) w >>> tiny = min('Hello world') >>> print(tiny) >>> big = max('Hello world') Argument 'w' Result Assignment
  • 6. Max Function >>> big = max('Hello world') >>> print(big) w max() function 'Hello world' (a string) 'w' (a string) A function is some stored code that we use. A function takes some input and produces an output. Guido wrote this code
  • 7. Max Function >>> big = max('Hello world') >>> print(big) w def max(inp): blah blah for x in inp: blah blah 'Hello world' (a string) 'w' (a string) A function is some stored code that we use. A function takes some input and produces an output. Guido wrote this code
  • 8. Type Conversions • When you put an integer and floating point in an expression, the integer is implicitly converted to a float • You can control this with the built-in functions int() and float() >>> print(float(99) / 100) 0.99 >>> i = 42 >>> type(i) <class 'int'> >>> f = float(i) >>> print(f) 42.0 >>> type(f) <class 'float'> >>> print(1 + 2 * float(3) / 4 – 5) -2.5 >>>
  • 9. String Conversions • You can also use int() and float() to convert between strings and integers • You will get an error if the string does not contain numeric characters >>> sval = '123' >>> type(sval) <class 'str'> >>> print(sval + 1) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' >>> ival = int(sval) >>> type(ival) <class 'int'> >>> print(ival + 1) 124 >>> nsv = 'hello bob' >>> niv = int(nsv) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int()
  • 11. Building our Own Functions • We create a new function using the def keyword followed by optional parameters in parentheses • We indent the body of the function • This defines the function but does not execute the body of the function def print_lyrics(): print("I'm a lumberjack, and I'm okay.") print('I sleep all night and I work all day.')
  • 12. x = 5 print('Hello') def print_lyrics(): print("I'm a lumberjack, and I'm okay.") print('I sleep all night and I work all day.') print('Yo') x = x + 2 print(x) Hello Yo 7 print("I'm a lumberjack, and I'm okay.") print('I sleep all night and I work all day.') print_lyrics():
  • 13. Definitions and Uses • Once we have defined a function, we can call (or invoke) it as many times as we like • This is the store and reuse pattern
  • 14. x = 5 print('Hello') def print_lyrics(): print("I'm a lumberjack, and I'm okay.") print('I sleep all night and I work all day.') print('Yo') print_lyrics() x = x + 2 print(x) Hello Yo I'm a lumberjack, and I'm okay. I sleep all night and I work all day. 7
  • 15. Arguments • An argument is a value we pass into the function as its input when we call the function • We use arguments so we can direct the function to do different kinds of work when we call it at different times • We put the arguments in parentheses after the name of the function big = max('Hello world') Argument
  • 16. Parameters A parameter is a variable which we use in the function definition. It is a “handle” that allows the code in the function to access the arguments for a particular function invocation. >>> def greet(lang): ... if lang == 'es': ... print('Hola') ... elif lang == 'fr': ... print('Bonjour') ... else: ... print('Hello') ... >>> greet('en') Hello >>> greet('es') Hola >>> greet('fr') Bonjour >>>
  • 17. Return Values Often a function will take its arguments, do some computation, and return a value to be used as the value of the function call in the calling expression. The return keyword is used for this. def greet(): return "Hello" print(greet(), "Glenn") print(greet(), "Sally") Hello Glenn Hello Sally
  • 18. Return Value • A “fruitful” function is one that produces a result (or return value) • The return statement ends the function execution and “sends back” the result of the function >>> def greet(lang): ... if lang == 'es': ... return 'Hola' ... elif lang == 'fr': ... return 'Bonjour' ... else: ... return 'Hello' ... >>> print(greet('en'),'Glenn') Hello Glenn >>> print(greet('es'),'Sally') Hola Sally >>> print(greet('fr'),'Michael') Bonjour Michael >>>
  • 19. Arguments, Parameters, and Results >>> big = max('Hello world') >>> print(big) w def max(inp): blah blah for x in inp: blah blah return 'w' 'Hello world' 'w' Argument Parameter Result
  • 20. Multiple Parameters / Arguments • We can define more than one parameter in the function definition • We simply add more arguments when we call the function • We match the number and order of arguments and parameters def addtwo(a, b): added = a + b return added x = addtwo(3, 5) print(x) 8
  • 21. Void (non-fruitful) Functions • When a function does not return a value, we call it a “void” function • Functions that return values are “fruitful” functions • Void functions are “not fruitful”
  • 22. To function or not to function... • Organize your code into “paragraphs” - capture a complete thought and “name it” • Don’t repeat yourself - make it work once and then reuse it • If something gets too long or complex, break it up into logical chunks and put those chunks in functions • Make a library of common stuff that you do over and over - perhaps share this with your friends...
  • 23. Summary • Arguments • Results (fruitful functions) • Void (non-fruitful) functions • Why use functions? • Functions • Built-In Functions • Type conversion (int, float) • String conversions • Parameters
  • 24. Exercise Rewrite your pay computation with time-and-a- half for overtime and create a function called computepay which takes two parameters ( hours and rate). Enter Hours: 45 Enter Rate: 10 Pay: 475.0 475 = 40 * 10 + 5 * 15
  • 25. Acknowledgements / Contributions These slides are Copyright 2010- Charles R. Severance (www.dr-chuck.com) of the University of Michigan School of Information and open.umich.edu and made available under a Creative Commons Attribution 4.0 License. Please maintain this last slide in all copies of the document to comply with the attribution requirements of the license. If you make a change, feel free to add your name and organization to the list of contributors on this page as you republish the materials. Initial Development: Charles Severance, University of Michigan School of Information … Insert new Contributors and Translators here ...