Python Functions
Python Functions
2
Why Write Functions?
• Reusability
• Fewer errors introduced when code isn’t rewritten
• Reduces complexity of code
• Programs are easier to maintain
• Programs are easier to understand
3
Types of Functions
Different types of functions in Python:
Python built-in functions, Python recursion function, Python
lambda function, and Python user-defined functions with their
syntax and examples.
4
User-Defined Functions
• Python lets us group a sequence of statements into a single
entity, called a function.
• A Python function may or may not have a name.
5
Function Elements
• Before we can use functions we have to define them.
• So there are two main elements to functions:
1. Define the function. The function definition can appear at the
beginning or end of the program file.
def my_function():
print("Hello from a function")
2. Invoke or call the function. This usually happens in the body
of the main() function, but sub-functions can call other sub-
functions too.
main()
my_function()
6
Rules for naming function
(identifier)
• We follow the same rules when naming a function as we do
when naming a variable.
• It can begin with either of the following: A-Z, a-z, and
underscore(_).
• The rest of it can contain either of the following: A-Z, a-z,
digits(0-9), and underscore(_).
• A reserved keyword may not be chosen as an identifier.
• It is good practice to name a Python function according to
what it does.
7
Function definitions
• A function definition has two major parts: the definition
head and the definition body.
• The definition head in Python has three main parts: the
keyword def, the identifier or name of the function, and the
parameters in parentheses.
def average(total, num):
• def - keyword
• Average-- identifier
• total, num-- Formal parameters or arguments
• Don’t forget the colon : to mark the start of a statement
bloc
8
Function body
• The colon at the end of the definition head marks the start
of the body, the bloc of statements. There is no symbol to
mark the end of the bloc, but remember that indentation in
Python controls statement blocs.
9
Workshop
Using the small function defined in the last slide, write a command line
program which asks the user for a test score total and the number of
students taking the test. The program should print the test score average.
• Example: Function Flow - happy.py
# Simple illustration of functions.
def happy():
print "Happy Birthday to you!"
def sing(person):
happy()
print "Happy birthday, dear", person + "."
def main():
sing(“Sunny")
print
main()
10
Parameters or Arguments
• The terms parameter and argument can be used for the same thing:
information that are passed into a function.
• If you do not know how many keyword arguments that will be passed into
your function, add two asterisk: ** before the parameter name in the function
definition.
• This way the function will receive a dictionary of arguments, and can access
the items accordingly:
def my_function(**name):
print("His last name is " + name["lname"])
13
Scope of variables
• A variable’s scope tells us where in the program it is visible. A
variable may have local or global scope.
• Local Scope- A variable that’s declared inside a function has a local
scope. In other words, it is local to that function.
• Thus it is possible to have two variables named the same within one
source code file, but they will be different variables if they’re in
different functions—and they could be different data types as well.
>>> def func3():
x=7
print(x)
>>> func3()
• Global Scope- When you declare a variable outside python function,
or anything else, it has global scope. It means that it is visible
everywhere within the program.
>>> y=7
>>> def func4():
print(y)
>>> func4() 14
Scope of variables, cont.
15
Functions: Return values
• Some functions don’t have any parameters or any return values, such as
functions that just display. But…
• “return” keyword lets a function return a value, use the return statement:
def square(x): # x is Formal parameter
return x * x #Return value
16
Return value used as
argument:
• Example of calculating a hypotenuse
num1, num2 = 10, 14
Hypotenuse = math.sqrt(sum_of_squares(num1, num2))
def sum_of_squares(x,y):
t = (x*x) + (y * y)
return t
17
Functions modifying
parameters
• So far we’ve seen that functions can accept values (actual parameters), process
data, and return a value to the calling function. But the variables that were
handed to the invoked function weren’t changed. The called function just
worked on the VALUES of those actual parameters, and then returned a new
value, which is usually stored in a variable by the calling function. This is called
passing parameters by value
18
Modifying parameters, cont.
• Some programming languages, like C++, allow passing parameters by reference.
Essentially this means that special syntax is used when defining and calling
functions so that the function parameters refer to the memory location of the
original variable, not just the value stored there.
• Schematic of passing by value
19
Schematic of passing by reference
• Using memory location, actual value of original variable is changed
20
Passing lists in Python
• Python does NOT support passing by reference, BUT…
• Python DOES support passing lists, the values of which can
be changed by subfunctions.
• Example of Python’s mutable parameters
21
Passing lists, cont.
• Because a list is actually a Python object with values associated with it,
when a list is passed as a parameter to a subfunction the memory
location of that list object is actually passed –not all the values of the list.
• When just a variable is passed, only the value is passed, not the memory
location of that variable.
• E.g. if you send a List as an argument, it will still be a List when it reaches the
function:
• Example
def my_function(food):
for x in food:
print(x)
Output:
apple
banana
cherry
22
Recursion
• Python also accepts function recursion, which means a defined function can call
itself.
• Recursion is a common mathematical and programming concept. It means that a
function calls itself. This has the benefit of meaning that you can loop through
data to reach a result.
• The developer should be very careful with recursion as it can be quite easy to slip
into writing a function which never terminates, or one that uses excess amounts of
memory or processor power. However, when written correctly recursion can be a
very efficient and mathematically-elegant approach to programming.
• Example:
def Recursion(k):
if(k > 0):
result = k + Recursion(k - 1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
Recursion(6) 23
Python Lambda
• A lambda function is a small anonymous function.
• The power of lambda is better shown when you use them as an
anonymous function inside another function.
• A lambda function can take any number of arguments, but can only
have one expression.
• Syntax
lambda arguments : expression
• The expression is executed and the result is returned:
• Example
A lambda function that adds 10 to the number passed in as an
argument, and print the result:
x = lambda a : a + 10
print(x(5))
Output: 15
24
Modularize!
25
Conclusion!
Thank you
26