SlideShare a Scribd company logo
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
Ad

More Related Content

What's hot (20)

CLTL python course: Object Oriented Programming (1/3)
CLTL python course: Object Oriented Programming (1/3)CLTL python course: Object Oriented Programming (1/3)
CLTL python course: Object Oriented Programming (1/3)
Rubén Izquierdo Beviá
 
Introduction to python programming, Why Python?, Applications of Python
Introduction to python programming, Why Python?, Applications of PythonIntroduction to python programming, Why Python?, Applications of Python
Introduction to python programming, Why Python?, Applications of Python
Pro Guide
 
Loops in Python
Loops in PythonLoops in Python
Loops in Python
AbhayDhupar
 
Python programming
Python  programmingPython  programming
Python programming
Ashwin Kumar Ramasamy
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
Akhil Kaushik
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 
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!
 
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Edureka!
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...
Edureka!
 
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | EdurekaWhat is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
Edureka!
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
Ahmed Farag
 
Python-Functions.pptx
Python-Functions.pptxPython-Functions.pptx
Python-Functions.pptx
Karudaiyar Ganapathy
 
Loops in Python.pptx
Loops in Python.pptxLoops in Python.pptx
Loops in Python.pptx
Guru Nanak Dev University, Amritsar
 
Python libraries
Python librariesPython libraries
Python libraries
Prof. Dr. K. Adisesha
 
Packages In Python Tutorial
Packages In Python TutorialPackages In Python Tutorial
Packages In Python Tutorial
Simplilearn
 
Python Basics.pdf
Python Basics.pdfPython Basics.pdf
Python Basics.pdf
FaizanAli561069
 
Python Modules
Python ModulesPython Modules
Python Modules
Nitin Reddy Katkam
 
Python file handling
Python file handlingPython file handling
Python file handling
Prof. Dr. K. Adisesha
 
Python Lambda Function
Python Lambda FunctionPython Lambda Function
Python Lambda Function
Md Soyaib
 
CLTL python course: Object Oriented Programming (1/3)
CLTL python course: Object Oriented Programming (1/3)CLTL python course: Object Oriented Programming (1/3)
CLTL python course: Object Oriented Programming (1/3)
Rubén Izquierdo Beviá
 
Introduction to python programming, Why Python?, Applications of Python
Introduction to python programming, Why Python?, Applications of PythonIntroduction to python programming, Why Python?, Applications of Python
Introduction to python programming, Why Python?, Applications of Python
Pro Guide
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
Akhil Kaushik
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 
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!
 
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Edureka!
 
Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...
Edureka!
 
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | EdurekaWhat is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
Edureka!
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
Ahmed Farag
 
Packages In Python Tutorial
Packages In Python TutorialPackages In Python Tutorial
Packages In Python Tutorial
Simplilearn
 
Python Lambda Function
Python Lambda FunctionPython Lambda Function
Python Lambda Function
Md Soyaib
 

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

Py-slides-3 easyforbeginnerspythoncourse.pptx
Py-slides-3 easyforbeginnerspythoncourse.pptxPy-slides-3 easyforbeginnerspythoncourse.pptx
Py-slides-3 easyforbeginnerspythoncourse.pptx
mohamedsamydeveloper
 
Pythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptxPythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptx
leavatin
 
Python Learn Function with example programs
Python Learn Function with example programsPython Learn Function with example programs
Python Learn Function with example programs
GeethaPanneer
 
Pythonlearn-02-Expressions123AdvanceLevel.pptx
Pythonlearn-02-Expressions123AdvanceLevel.pptxPythonlearn-02-Expressions123AdvanceLevel.pptx
Pythonlearn-02-Expressions123AdvanceLevel.pptx
AninditaSarkarNaha
 
03-Variables, Expressions and Statements (1).pdf
03-Variables, Expressions and Statements (1).pdf03-Variables, Expressions and Statements (1).pdf
03-Variables, Expressions and Statements (1).pdf
MirHazarKhan1
 
Introduction to Python Prog. - Lecture 2
Introduction to Python Prog. - Lecture 2Introduction to Python Prog. - Lecture 2
Introduction to Python Prog. - Lecture 2
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Python
PythonPython
Python
Vishal Sancheti
 
Functions in python3
Functions in python3Functions in python3
Functions in python3
Lakshmi Sarvani Videla
 
python2oxhvoudhuSGFsughusgdogusuosFU.pdf
python2oxhvoudhuSGFsughusgdogusuosFU.pdfpython2oxhvoudhuSGFsughusgdogusuosFU.pdf
python2oxhvoudhuSGFsughusgdogusuosFU.pdf
rohithzach
 
Notes5
Notes5Notes5
Notes5
hccit
 
Unit2 input output
Unit2 input outputUnit2 input output
Unit2 input output
deepak kumbhar
 
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
SovannDoeur
 
2 Functions2.pptx
2 Functions2.pptx2 Functions2.pptx
2 Functions2.pptx
RohitYadav830391
 
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 minutes
Sumit Raj
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
Rajasekhar364622
 
CHAPTER 01 FUNCTION in python class 12th.pptx
CHAPTER 01 FUNCTION in python class 12th.pptxCHAPTER 01 FUNCTION in python class 12th.pptx
CHAPTER 01 FUNCTION in python class 12th.pptx
PreeTVithule1
 
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
Mohammad Reza Kamalifard
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2
Raghu nath
 
python chapter 1
python chapter 1python chapter 1
python chapter 1
Raghu nath
 
Py-slides-3 easyforbeginnerspythoncourse.pptx
Py-slides-3 easyforbeginnerspythoncourse.pptxPy-slides-3 easyforbeginnerspythoncourse.pptx
Py-slides-3 easyforbeginnerspythoncourse.pptx
mohamedsamydeveloper
 
Pythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptxPythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptx
leavatin
 
Python Learn Function with example programs
Python Learn Function with example programsPython Learn Function with example programs
Python Learn Function with example programs
GeethaPanneer
 
Pythonlearn-02-Expressions123AdvanceLevel.pptx
Pythonlearn-02-Expressions123AdvanceLevel.pptxPythonlearn-02-Expressions123AdvanceLevel.pptx
Pythonlearn-02-Expressions123AdvanceLevel.pptx
AninditaSarkarNaha
 
03-Variables, Expressions and Statements (1).pdf
03-Variables, Expressions and Statements (1).pdf03-Variables, Expressions and Statements (1).pdf
03-Variables, Expressions and Statements (1).pdf
MirHazarKhan1
 
python2oxhvoudhuSGFsughusgdogusuosFU.pdf
python2oxhvoudhuSGFsughusgdogusuosFU.pdfpython2oxhvoudhuSGFsughusgdogusuosFU.pdf
python2oxhvoudhuSGFsughusgdogusuosFU.pdf
rohithzach
 
Notes5
Notes5Notes5
Notes5
hccit
 
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
SovannDoeur
 
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 minutes
Sumit Raj
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
Rajasekhar364622
 
CHAPTER 01 FUNCTION in python class 12th.pptx
CHAPTER 01 FUNCTION in python class 12th.pptxCHAPTER 01 FUNCTION in python class 12th.pptx
CHAPTER 01 FUNCTION in python class 12th.pptx
PreeTVithule1
 
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
Mohammad Reza Kamalifard
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2
Raghu nath
 
python chapter 1
python chapter 1python chapter 1
python chapter 1
Raghu nath
 
Ad

Recently uploaded (20)

History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast BrooklynBridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
i4jd41bk
 
What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)
jemille6
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
The History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptxThe History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
Ancient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian HistoryAncient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian History
Virag Sontakke
 
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE  BY sweety Tamanna Mahapatra MSc PediatricAPGAR SCORE  BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
SweetytamannaMohapat
 
Drugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdfDrugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdf
crewot855
 
*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
Cultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptxCultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptx
UmeshTimilsina1
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
Arshad Shaikh
 
Ajanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of HistoryAjanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of History
Virag Sontakke
 
E-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26ASE-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26AS
Abinash Palangdar
 
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast BrooklynBridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
i4jd41bk
 
What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)
jemille6
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
Ancient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian HistoryAncient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian History
Virag Sontakke
 
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE  BY sweety Tamanna Mahapatra MSc PediatricAPGAR SCORE  BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
SweetytamannaMohapat
 
Drugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdfDrugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdf
crewot855
 
*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
Cultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptxCultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptx
UmeshTimilsina1
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
Arshad Shaikh
 
Ajanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of HistoryAjanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of History
Virag Sontakke
 
E-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26ASE-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26AS
Abinash Palangdar
 
Ad

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
  翻译: