Python Functions
Python Functions
• What is Function?
• Why we need Functions?
• What is Function call?
• How python gives different way to write function?
We have already used several functions
• Python gives huge set of library function and very easy to use.
Stored (and reused) Steps
def
hello(): Program:
print 'Hello' Output:
def thing():
print 'Fun' print 'Hello’
print 'Fun’ Hello
hello() Fun
thing()
print 'Zip’ Zip
print “Zip” thing()
Hello
Fun
hello()
We call these reusable pieces of code “functions”.
Python Functions
• There are two kinds of functions in Python.
• Built-in functions that are provided as part of Python - input(), type(),
float(), int() ...
def max(inp):
blah
“Hello world” blah ‘w’
for x in y: (a string)
(a string)
blah
blah
def print_lyrics():
print "I'm a lumberjack, and I'm okay.”
print 'I sleep all night and I work all day.' Hello
Yo
print 'Yo' 7
x=x+2
print x
Definitions and Uses
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() Hello
x=x+2 Yo
print x 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
def greet():
return "Hello” Hello Glenn
Hello Sally
print greet(), "Glenn”
print greet(), "Sally"
>>> def greet(lang):
Return Value ... if lang == 'es':
... return 'Hola’
... elif lang == 'fr':
... return 'Bonjour’
• A “fruitful” function is one ... else:
that produces a result (or ... return 'Hello’
return value) ... >>> print greet('en'),'Glenn’
Hello Glenn
• The return statement ends >>> print greet('es'),'Sally’
the function execution and Hola Sally
“sends back” the result of >>> print greet('fr'),'Michael’
the function Bonjour Michael
>>>
Arguments, Parameters, and Results
>>> big = max('Hello world') Parameter
>>> print big'w'
def max(inp):
blah
“Hello world” blah ‘w’
for x in y:
Argument blah
Result
blah
return ‘w’
Multiple Parameters / Arguments
• We can define more than
one parameter in the
function definition
def addtwo(a, b):
• We simply add more added = a + b
arguments when we call the return added
function x = addtwo(3, 5)
print x
• Make a library of common stuff that you do over and over - perhaps
share this with your friends...
Exercise
475 = 40 * 10 + 5 * 15
Summary
• Functions
• Built-In Functions
• Type conversion (int, float)
• Math functions (sin, sqrt)
• Try / except (again)
• Arguments
Reference
Python for Everybody,