Python Concepts/Functions
Objective[edit | edit source]
|
Lesson[edit | edit source]Functions[edit | edit source]A function is a way of reusing a block of code so that it can be used more than once. Functions give the programmer the ability to reduce code redundancy and eliminate hours of wasted work. Each function allows the code to be centralized, where one change to the function will affect everything that depends on it. Functions can be used to divide and conquer tasks that would seem otherwise impossible to accomplish! Creating A Function[edit | edit source]To create a function, use the def hello():
print("Hello, world!")
The code above assigns and creates the function called Now that you've created the function nothing should visibly happen. To actually invoke or call the function, you'll need to use the function's name followed by the parentheses as shown in the script below. def hello():
print("Hello, world!")
hello()
The output should be: Hello, world! Adding the command Function Parameters[edit | edit source]At this point, you might be wondering why we need to have those pointless parentheses when we call the function. Wouldn't def square(x):
print(x**2)
square(2)
square(3)
square(4)
The following output should be: 4 9 16
def square(x):
print(x**2)
square(2)
square(3)
square(4)
print(x) # x doesn't exist outside of square!
A function can take multiple arguments with any two adjacent arguments separated by a comma if more than one exists as demonstrated in the next example. def somemath(x, y):
print((x**2)+y)
somemath(2, 3)
somemath(3, 2)
The following output should be: 7 11 Default Parameters[edit | edit source]Having parameters is great, but it can be repetitive to continue to use them over and over, again. We can define a default value for a parameter by setting its value when you define the parameter. Take the script below for example. def woof(x=0):
print(x)
woof(1)
woof()
woof(23)
The output should be: 1 0 23 Did you see the second time we called Positional Arguments[edit | edit source]
def f3 (arg1, arg2=None, arg3=None) :
# This function expects at least one argument and a maximum of three.
print ('arg1 =', arg1, '. arg2 =', arg2, '. arg3 =', arg3,'.')
f3 (1, *(2,3))
f3 (1, *[2,3])
f3 (1, *{2,3})
f3 (1, 2,3)
In all four function calls above numbers arg1 = 1 . arg2 = 2 . arg3 = 3 .
The following syntax accepts a variable number of arguments: def f3 (*args) :
print ('Length = {}, args = {}, isinstance(args,tuple): {}'
.format(len(args), args, isinstance(args,tuple)))
f3()
f3(1)
f3(1,2)
f3(1,2,3)
f3('0', 1, {'one':1, 'two':2}, [1,2,3])
Length = 0, args = (), isinstance(args,tuple): True
Length = 1, args = (1,), isinstance(args,tuple): True
Length = 2, args = (1, 2), isinstance(args,tuple): True
Length = 3, args = (1, 2, 3), isinstance(args,tuple): True
Length = 4, args = ('0', 1, {'one': 1, 'two': 2}, [1, 2, 3]), isinstance(args,tuple): True
Python's syntax accepts required and optional arguments and a variable number of arguments: def f5 (arg1, arg2=None, *arg3) :
print ('arg1 =', arg1, '. arg2 =', arg2, '. arg3 =', arg3)
f5(1)
f5(1,2)
f5(1,2,3)
f5(1,2,3,4)
arg1 = 1 . arg2 = None . arg3 = ()
arg1 = 1 . arg2 = 2 . arg3 = ()
arg1 = 1 . arg2 = 2 . arg3 = (3,)
arg1 = 1 . arg2 = 2 . arg3 = (3, 4)
Parameters are part of the function definition. When the function is invoked, arguments are passed to the function and each argument passed must correspond to a parameter in the definition of the function. Keyword Arguments[edit | edit source]
def f2 (**kwargs) :
or def f2 (arg1, arg2, arg..., **kwargs) :
We saw keyword arguments used in Dictionaries:Other operations on dictionaries This lesson shows by examples how they may be passed and received. def f2 (**kwargs) :
print ('\nf2: isinstance(kwargs, dict):', isinstance(kwargs, dict))
for arg in kwargs :
print (' arg =', arg, ', isinstance(arg,str):', isinstance(arg,str))
break
for arg in kwargs :
print (' kwargs[{}] = {}.'.format(arg, kwargs[arg]))
f2(**{'one':1, 'two':2, 'three':3})
f2(one=1,two=2,three=3)
The result is: f2: isinstance(kwargs, dict): True
arg = one , isinstance(arg,str): True
kwargs[one] = 1.
kwargs[two] = 2.
kwargs[three] = 3.
f2: isinstance(kwargs, dict): True
arg = one , isinstance(arg,str): True
kwargs[one] = 1.
kwargs[two] = 2.
kwargs[three] = 3.
The following example shows how (optional) positional arguments and (optional) keyword arguments may be passed to a given function upon invocation. def f6 (arg1, arg2=None, *var, **kwargs) :
print ( 'arg1 = {}. arg2 = {}. var = {}. kwargs = {}.\n'
.format (arg1, arg2, var, kwargs)
)
f6(0) # At least one argument is required for f6().
f6(0, one=1, two=2)
f6(0,1, one=1, two=2)
f6(0,1,2, one=1, two=2)
f6(0,1,2,3, one=1, two=2)
f6(0,1,2,3,4, one=1, two=2)
f6(0,[1,2],3,4, one=1, two=2) # arg2 is passed as list.
f6(0,*[1,2],3,4, one=1, two=2) # arg2 is unpacked.
arg1 = 0. arg2 = None. var = (). kwargs = {}.
arg1 = 0. arg2 = None. var = (). kwargs = {'one': 1, 'two': 2}.
arg1 = 0. arg2 = 1. var = (). kwargs = {'one': 1, 'two': 2}.
arg1 = 0. arg2 = 1. var = (2,). kwargs = {'one': 1, 'two': 2}.
arg1 = 0. arg2 = 1. var = (2, 3). kwargs = {'one': 1, 'two': 2}.
arg1 = 0. arg2 = 1. var = (2, 3, 4). kwargs = {'one': 1, 'two': 2}.
arg1 = 0. arg2 = [1, 2]. var = (3, 4). kwargs = {'one': 1, 'two': 2}.
arg1 = 0. arg2 = 1. var = (2, 3, 4). kwargs = {'one': 1, 'two': 2}.
Returning A Value[edit | edit source]If we wanted to use the value that the square function gives us, we would rewrite it to use the >>> def square(x):
... return x**2
...
Which can then be used to do such fun things as: >>> print(square(3))
9
or >>> print(square(square(3)))
81
or even in statements such as: >>> 10 + square(2)
14
and >>> y = square(10)
>>> y
100
If the function is to return a value, the |
Assignments[edit | edit source]
|
|
References
[edit | edit source]1. Python's documentation:
"4.6. Defining Functions", "4.7. More on Defining Functions", "4.7.2. Keyword Arguments", "function", "parameter", "argument", "6.3.4. Calls", "8.6. Function definitions", "What is the difference between arguments and parameters?", "Functional Programming HOWTO"
2. Python's methods:
3. Python's built-in functions: