Unit 4
Unit 4
Differentiate
arguments and
keyword
Objectives
arguments
Identify the
types of variable
scopes
Create a
program that
uses functions
Python − a block of code which only executes
when called
Function − where data can be passed
− can return data as result
▪ def
− keyword used to define a function
function definition
function call
Arguments − information passed into a function
− specified after the function name
or args and inside the parentheses
− separated by a comma
▪ Functions perspective:
− parameter : variable inside the parentheses in the
function definition
− argument : value sent to the function when called
Number of Arguments
Arbitrary Arguments *args
Keyword − order of arguments does not
matter
Arguments
or kwargs
Arbitrary Keyword Arguments **kwargs
Default Parameter Value
Passing List as Argument
Return Values
Recursion − function calls itself
5 + sumOfNum(4)
4 + sumOfNum(3)
3 + sumOfNum(2)
2 + sumOfNum(1)
1
− specifies the region where a variable can be
accessed
o local
o global
o nonlocal
Variable Scope
▪ sum : created inside
the add_num function
and can only be
accessed within (local)
▪ nonlocal
− keyword to create nonlocal variables
o used in nested functions when local scope is not
defined
Random ▪ Python has a built-in random module
that can be used to generate random
Number numbers
− a small anonymous function
− can take any number of arguments, but can only
have one expression
Lambda Function
Why use lambda in a function?
− the power of lambda is better shown when used as an
anonymous function inside another function
− example: a function takes one argument, and that
argument will be multiplied with an unknown number
mydoubler = lambda a : a * 2
▪ Use lambda functions when an anonymous function
is needed for a short period of time.