Anda di halaman 1dari 15

Python Functions

PFE610S
NUST 2019
Python Function
• A function is a block of code that performs a specific task.
• Some programming languages make a distinction between a function (that performs a task
returns a value) and a procedure (that performs a task and does not return a value).
• In Python there is no such difference every block of code declared (or precedent) by the key
word def and followed by a function name is a function.
• i.e. we only have functions in python

Function declaration: Example:


def function_name(argument(s) or arguments_list): def add(a, b):
Function_body return a + b

• ‘a’ and ‘b’ are called function’s arguments, and “(a, b)” is termed the argument list.
• The argument list can be void (i.e. no arguments) also the return can be None (i.e. no return
value)
• Programming languages have build in functions e.g. the print(), range(), input(), and others are
Python build in functions.
Function Definition
• A function is a named block of statements that
can be executed/called within a program.
• Some functions we have already used are:
– Print(), format(), range(), etc
• When a function is called Python stops what it is
doing, runs the function, then continues from
where it stopped.
• Functions enable reuse and modularity of code.
• Functions help us to write longer/more complex
programs.
Function Definition and Calling/Use
• Functions can be defined and used in any order, as long as they are used
after definition.
Function definition:
Calling/using/invoking a function:
def function_name(argument(s)):
function_name(parameters list)
Function_body (statements)

example: Argument list

def multiply(a, b): Function definition


c = a*b
Function body
return c
Function's return value

multiply(4, 5) Function call/invocation/use

Parameter list
Parameters and Arguments
• Every function can have a list of parameters in its definition
called the formal parameters
• Whenever the function is called/invoked a value must be
provided for each of the formal parameters called the
arguments
• Within the function body, the parameters can be used like
variables.
def function_A(a, b, c):
print(a) a, b, c are parameters (formal parameters)
print(b+c)
1, 2, 3 are arguments or actual parameters
Function_A(1, 2, 3)
Pass-By-Value
• Only a copy of the value of a parameter is ever sent
to
• a function.
• So if there is an original variable, it cannot be
changed by the function changing the parameter.
def function_A(a): Output:
a=a+1 12
print(a) 11

b = 11
Function_A(b)
print(b)
Scope and Local Variables
• New variables can be created and used within functions but
they disappear when the function ends these variables are
called local variables

def function_A(a):
a=1
Function scope
print(a)

b = 11
Function_A(b)
print(a) # this will results in an error because ‘a’ is not
# known outside the scope of the function functionA()
Global Variables
• Global variables can be accessed but not changed.
• Use the global statement to allow changes to a global variable.
• A global variable is visible and can be changed anywhere in the
program

def function_A(a):
global b # b is a global variable
b=2
print(a, b)
b=2

b = 11
Function_A(b) # this will produce 11 2
Local Variable
• Local variables names (and parameters) that are the same as global
variable names temporarily hide the global variables.

global b
b = 11
def function_A(a, b):
a=1
b=1 # this is a local variable
print(a, b)
b=2 # this is also a local variable
a=2

Function_A(b)
print(b) # this will output 11
Return Values
• Functions can return values just like mathematical functions.
f(x) = x + 2, y = f(2) = 4
• Use the return statement with an expression.
• Can be used anywhere in function and will return
• immediately.

def square(x):
return x*x
y = square(12)
print(y)
The Docstring
• Functions should be documented by specifying their purpose in a
string immediately after the header or function definition.
• It is recommended that you use """ (triple quotes – for multi-line
strings) for all docstrings.
• Use function__name.__doc__ to check the docstring.

def square(x):
"""Returns the square of x. """ # this is a doc string
return x*x
def cube(x):
"""Returns the cube of x. x can be any numerical value"""
return x*x*x
print(square.__doc__) # prints "Returns the square of x. "
The Main Function
• Common practice is to wrap a program into a function called
"main", then invoke this function to execute the program.

# square program

def square(x):
"""Return the square of x. """
return x*x

def main():
print(square (2))

if __name__ == ‘__main__ ’:
main()
Writing Your Own Modules
• Any file with functions can be imported.
• Check __name__ variable
– if it is "__main__", then this file was executed
– otherwise, this file was imported

Filename is my_square.py Filename is import_test.py

# square module # test square module


def square(x): import my_square # importing the my_square module
"""Return the square of x. """
return x*x def main():
b = my_square.square(3))
def main(): print(a. square(3))
print(square (2))
if __name__ == "__main__": if __name__ == "__main__":
main() main()
Python Lambda Function
• A lambda function is a small anonymous function. A lambda function can take any number of arguments,
but can only have one expression.
Syntax:
lambda arguments : expression

# 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))
• Lambda functions can take any number of arguments:

example:
x = lambda a, b : a * b
print(x(5, 6))

• The power of lambda is better shown when you use them as an anonymous function inside another
function. Say you have a function definition that takes one argument, and that argument will be multiplied
with an unknown number.
example: mydoubler my_function(2) mytripler = my_function(3)
def my_function(n):
return lambda a : a * n print(mydoubler(11)) print(mytripler(11))
22 33
Reference

1. https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/Python1_Basics.html#zz-8.

2. https://docs.python.org/3/tutorial/controlflow.html#defining-functions

3. https://www.w3schools.com/python/python_functions.asp

Anda mungkin juga menyukai