SlideShare a Scribd company logo
1 of 23
Function in Python
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'
hello()
print “Zip”
We call these reusable pieces of code “functions”.
hello():
hello()
Python Functions
• There are two kinds of functions in Python.
• Built-in functions that are provided as part of Python -
raw_input(), type(), float(), int() ...
• Functions that we define ourselves and then use
• We treat the of the built-in function names as "new" reserved
words (i.e. we avoid them as variable names)
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,
parenthesis and arguments in an expression
>>> big = max('Hello world')
>>> print bigw>>> 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 y:
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)
<type 'int'>
>>> f = float(i)
>>> print f
42.0
>>> type(f)
<type '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)
<type '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)
<type '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()
Building our Own Functions
• We create a new function using the def keyword followed by
optional parameters in parenthesis.
• 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 parenthesis after the name of the
function
big = max('Hello world')
Argument
Parameters
• A parameter is a variable
which we use in the
function definition that 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 y:
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
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 up 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...
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
Summary
• Functions
• Built-In Functions
• Type conversion (int, float)
• Math functions (sin, sqrt)
• Try / except (again)
• Arguments
• Parameters

More Related Content

What's hot

Python- Regular expression
Python- Regular expressionPython- Regular expression
Python- Regular expressionMegha V
 
FUNCTIONS IN PYTHON[RANDOM FUNCTION]
FUNCTIONS IN PYTHON[RANDOM FUNCTION]FUNCTIONS IN PYTHON[RANDOM FUNCTION]
FUNCTIONS IN PYTHON[RANDOM FUNCTION]vikram mahendra
 
Exception handling and function in python
Exception handling and function in pythonException handling and function in python
Exception handling and function in pythonTMARAGATHAM
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python amiable_indian
 
What is Python Lambda Function? Python Tutorial | Edureka
What is Python Lambda Function? Python Tutorial | EdurekaWhat is Python Lambda Function? Python Tutorial | Edureka
What is Python Lambda Function? Python Tutorial | EdurekaEdureka!
 
Python Lambda Function
Python Lambda FunctionPython Lambda Function
Python Lambda FunctionMd Soyaib
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in PythonSujith Kumar
 
Python functions
Python functionsPython functions
Python functionsAliyamanasa
 
Python Generators
Python GeneratorsPython Generators
Python GeneratorsAkshar Raaj
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++Sachin Yadav
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Edureka!
 

What's hot (20)

Python functions
Python functionsPython functions
Python functions
 
Python- Regular expression
Python- Regular expressionPython- Regular expression
Python- Regular expression
 
FUNCTIONS IN PYTHON[RANDOM FUNCTION]
FUNCTIONS IN PYTHON[RANDOM FUNCTION]FUNCTIONS IN PYTHON[RANDOM FUNCTION]
FUNCTIONS IN PYTHON[RANDOM FUNCTION]
 
Exception handling and function in python
Exception handling and function in pythonException handling and function in python
Exception handling and function in python
 
Pointers in c++ by minal
Pointers in c++ by minalPointers in c++ by minal
Pointers in c++ by minal
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
Unary operator overloading
Unary operator overloadingUnary operator overloading
Unary operator overloading
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Python
PythonPython
Python
 
What is Python Lambda Function? Python Tutorial | Edureka
What is Python Lambda Function? Python Tutorial | EdurekaWhat is Python Lambda Function? Python Tutorial | Edureka
What is Python Lambda Function? Python Tutorial | Edureka
 
Python Lambda Function
Python Lambda FunctionPython Lambda Function
Python Lambda Function
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
 
Python functions
Python functionsPython functions
Python functions
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
 
Python Generators
Python GeneratorsPython Generators
Python Generators
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
 

Similar to Function in Python [Autosaved].ppt

Pythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptxPythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptxleavatin
 
Notes5
Notes5Notes5
Notes5hccit
 
Chapter 2 Python Language Basics, IPython.pptx
Chapter 2 Python Language Basics, IPython.pptxChapter 2 Python Language Basics, IPython.pptx
Chapter 2 Python Language Basics, IPython.pptxSovannDoeur
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
 
An Intro to Python in 30 minutes
An Intro to Python in 30 minutesAn Intro to Python in 30 minutes
An Intro to Python in 30 minutesSumit Raj
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptRajasekhar364622
 
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱Mohammad Reza Kamalifard
 
python chapter 1
python chapter 1python chapter 1
python chapter 1Raghu nath
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2Raghu nath
 
Python tutorialfeb152012
Python tutorialfeb152012Python tutorialfeb152012
Python tutorialfeb152012Shani729
 
Python programing
Python programingPython programing
Python programinghamzagame
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developersJim Roepcke
 
Lec2_cont.pptx galgotias University questions
Lec2_cont.pptx galgotias University questionsLec2_cont.pptx galgotias University questions
Lec2_cont.pptx galgotias University questionsYashJain47002
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingMuthu Vinayagam
 

Similar to Function in Python [Autosaved].ppt (20)

Pythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptxPythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptx
 
Python
PythonPython
Python
 
Functions in python3
Functions in python3Functions in python3
Functions in python3
 
Notes5
Notes5Notes5
Notes5
 
Unit2 input output
Unit2 input outputUnit2 input output
Unit2 input output
 
Chapter 2 Python Language Basics, IPython.pptx
Chapter 2 Python Language Basics, IPython.pptxChapter 2 Python Language Basics, IPython.pptx
Chapter 2 Python Language Basics, IPython.pptx
 
2 Functions2.pptx
2 Functions2.pptx2 Functions2.pptx
2 Functions2.pptx
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
An Intro to Python in 30 minutes
An Intro to Python in 30 minutesAn Intro to Python in 30 minutes
An Intro to Python in 30 minutes
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
 
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
 
python chapter 1
python chapter 1python chapter 1
python chapter 1
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2
 
Python tutorialfeb152012
Python tutorialfeb152012Python tutorialfeb152012
Python tutorialfeb152012
 
Python programing
Python programingPython programing
Python programing
 
Python basic
Python basicPython basic
Python basic
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
 
Lec2_cont.pptx galgotias University questions
Lec2_cont.pptx galgotias University questionsLec2_cont.pptx galgotias University questions
Lec2_cont.pptx galgotias University questions
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
 
P4 2018 io_functions
P4 2018 io_functionsP4 2018 io_functions
P4 2018 io_functions
 

Recently uploaded

Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
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
 
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
 
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
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
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
 
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
 
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
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 

Recently uploaded (20)

Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
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
 
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
 
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
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
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
 
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
 
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
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
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
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 

Function in Python [Autosaved].ppt

  • 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' hello() print “Zip” We call these reusable pieces of code “functions”. hello(): hello()
  • 3. Python Functions • There are two kinds of functions in Python. • Built-in functions that are provided as part of Python - raw_input(), type(), float(), int() ... • Functions that we define ourselves and then use • We treat the of the built-in function names as "new" reserved words (i.e. we avoid them as variable names)
  • 4. 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, parenthesis and arguments in an expression
  • 5. >>> big = max('Hello world') >>> print bigw>>> 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 y: 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) <type 'int'> >>> f = float(i) >>> print f 42.0 >>> type(f) <type '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) <type '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) <type '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()
  • 10. Building our Own Functions • We create a new function using the def keyword followed by optional parameters in parenthesis. • 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.'
  • 11. 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():
  • 12. 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
  • 13. 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
  • 14. 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 parenthesis after the name of the function big = max('Hello world') Argument
  • 15. Parameters • A parameter is a variable which we use in the function definition that 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 >>>
  • 16. 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
  • 17. 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 >>>
  • 18. Arguments, Parameters, and Results >>> big = max('Hello world') >>> print big'w' def max(inp): blah blah for x in y: blah blah return ‘w’ “Hello world” ‘w’ Argument Parameter Result
  • 19. 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
  • 20. 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"
  • 21. 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 up 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...
  • 22. 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
  • 23. Summary • Functions • Built-In Functions • Type conversion (int, float) • Math functions (sin, sqrt) • Try / except (again) • Arguments • Parameters