Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

FUNCTIONS

Musarrat Ahmed
1.
Transition headline
Let’s start with the first set of slides
But why do we need a function after all?

1. Abstraction and reusability


➔ Don’t Repeat Yourself (DRY) principle of S/W development

2. Modularity
➔ Complex processes broken up into smaller steps

3. Namespace separation
➔ New namespace for every function

Functions should do one thing. They should
do it well. They should do it only.

~Robert C. Martin
Function Template

Do you see anything missing here?


But where are the data types?

● The Python interpreter does not force you to specify the type of your function’s
arguments or the return value.
● Python lets you send any object as an argument, and pass back any object as a
return value.
● The interpreter doesn’t care or check what type these objects are (only that they
are provided).
● With Python 3, it is possible to indicate the expected types for arguments/return
values.
● However, indicating the types expected does not switch on type checking, as
Python never checks the types of the arguments or any return values.
Docstrings

● When the first statement in the body of a Python function is a string literal, it’s
known as the function’s docstring.
● Used to supply documentation for a function.
● It can contain the function’s purpose, what arguments it takes, information about
return values, or any other useful information.
● Recommended convention is to triple-quote using double-quote characters (""").

● If the docstring fits on one line, then the closing quotes should be on the same
line as the opening quotes.
● A multi-line docstring should consist of a summary line, followed by a
blank line, followed by a more detailed description. The closing quotes
should be on a line by themselves.

● PEP 257 offers conventions on how to format docstrings.


● In the interactive Python interpreter, you can type help(<function_name>)
to display the docstring for <function_name>.
Argument Passing

1. Positional/Required Arguments
➔ In the function definition, you specify a comma-separated list of parameters
inside the parentheses (formal parameters).
➔ When the function is called, you specify a corresponding list of arguments
(actual parameters).
➔ You must specify the same number of arguments in the function call as there
are parameters in the definition, and in exactly the same order.
2. Keyword Arguments
➔ When you’re calling a function, you can specify arguments in the form
<keyword>=<value>. In that case, each <keyword> must match a parameter
in the Python function definition.
➔ Using keyword arguments lifts the restriction on argument order.
➔ The number of arguments and parameters must still match.

➔ When positional and keyword arguments are both present, all the
positional arguments must come first.
➔ Once you’ve specified a keyword argument, there can’t be any
positional arguments to the right of it.

It should be noted that no ethically-trained
software engineer would ever consent to write
a SellNewYork procedure. Basic professional
ethics would instead require him to write a
SellCity procedure, to which New York could be
given as a parameter.

~Nathaniel Borenstein
Default Parameters

● If a parameter specified in a Python function definition has the form


<name>=<value>, then <value> becomes a default value for that parameter.
● Also called optional parameters.
● Any argument to a Python function can be assigned a default value, which can then
be automatically used if the code calling the function fails to supply an alternate
value.
Mutable Default Parameter Values

● Things can get weird if you specify a default parameter value that is a mutable
object (list, dict, set). (String, int, float, bool, tuple are immutable objects)

● Now, what would you expect to happen if f() is called without any parameters a
second and a third time?
You might have expected each subsequent call to also
return the singleton list ['###'], just like the first.
Instead, the return value keeps growing. What happened?

● In Python, default parameter values are defined only once when the function
is defined (i.e when the def statement is executed).
● The default value isn’t re-defined each time the function is called.
● Thus, each time you call f() without a parameter, you’re performing
.append() on the same list.
● Workaround -

The ideal numbers of arguments for a function is
zero (niladic). Next comes one (monadic), followed
closely by two (dyadic). Three arguments (triadic)
should be avoided where possible. More than
three (polyadic) requires very special
justification ‐ and then shouldn't be used
anyway.

~Robert C. Martin
Pass-by-Value or
Pass-by-Reference?
Every piece of data is an object in Python

● Assignment isn’t interpreted the same way in Python as in Pascal, C++ etc.

● In C++ -

x = 5
x = 10

➔ The variable x references a specific memory location.


➔ The first statement puts the value 5 in that location.
➔ The next statement overwrites the 5 and puts 10 there instead.
● In Python -

x = 5
x = 10

➔ The first statement causes x to point to an object whose value is 5.


➔ The next statement reassigns x as a new reference to a different
object whose value is 10 i.e the second assignment rebinds x to a
different object with value 10.

● In Python, when you pass an argument to a function, a similar rebinding


occurs.
● When the statement fx = 10 on line 2 is executed, f() rebinds fx to a new
object whose value is 10.
● The two references, x and fx, are uncoupled from one another.
● Argument passing in Python is somewhat of a hybrid between pass-by-value and
pass-by-reference.
● What gets passed to the function is a reference to an object, but the
reference is passed by value.
● Python’s argument-passing mechanism has been called pass-by-assignment (or
pass-by-object, pass-by-object-reference, or pass-by-sharing).
Takeaways

➢ Passing an immutable object, like an int, str, tuple to a Python function acts
like pass-by-value. The function can’t modify the object in the calling
environment.

➢ Passing a mutable object such as a list, dict, or set acts somewhat—but not
exactly—like pass-by-reference. The function can’t re-assign the object wholesale,
but it can change items in place within the object, and these changes will be
reflected in the calling environment.
The return Statement

● A return statement in a Python function serves two purposes:


➔ It immediately terminates the function and passes execution control back to the
caller.
➔ It provides a mechanism by which the function can pass data back to the caller.

● A function can return any type of object.


● When no return value is given or no return statement exists, a
Python function returns None.
Returning Multiple Values

● The Python return statement can return multiple values.

● When it is invoked, you need to pass the returned values in a simultaneous


assignment.
Function Annotations

The goal of annotations is not to
make life easier for the interpreter;
it’s to make
life easier for the user of your
function.
Why annotations?

● Annotations are a documentation standard, not a type enforcement mechanism.


● The interpreter does not care what type your arguments are, nor does it care what
type of data your function returns.
● What annotations do for programmers using your function is rid them of the need to
read your function’s code to learn what types are expected by, and returned from,
your function.
● Introduced in Python 3.0
● Annotations provide a way to attach metadata to a function’s parameters and return
value.
Writing Annotations

● Adding annotation to a function parameter:


➔ Insert a colon (:) followed by any expression after the parameter name in the
function definition.

● Adding annotation to a return value:


➔ Add the character -> and any expression between the closing parenthesis of the
parameter list and the colon that terminates the function header.
● If you want to assign a default value to a parameter that has an
annotation, then the default value goes after the annotation.

● To read a function’s annotations use the help function. ->


help(function_name)
assert Statement

● Assertions are statements that assert or state a fact confidently in your program.
● For example, while writing a division function, you're confident the divisor
shouldn't be zero, you assert divisor is not equal to zero.
● Used for error checking.
● Boolean expressions that check if the conditions return true or not.
● If it is true, the program does nothing and moves to the next line of code.
● However, if it's false, the program stops and throws an AssertionError.
● Syntax - assert <condition>,[<optional error message>]
Command-line Arguments

● Open cmd/terminal to run your python script. [python3 <file_name>.py]


● Provide command-line arguments after the name of the file.
● Example - python3 sum.py 5 6 7
Global Variables in Python

● Global keyword is used to create a global variable and make changes to the variable
in a local context.
● When we create a variable inside a function, it is local by default.
● When we define a variable outside of a function, it is global by default. You don't
have to use global keyword.
● We use global keyword to read and write a global variable inside a function.
● Use of global keyword outside a function has no effect.
Quiz Time!
1. What will be the output of the a)
following code?

b)

c)

d) None of the mentioned

Ans: (a)
2. What will be the output of the a)
following code?

b)

c)

d) None of the mentioned

Ans: (c)
3. What will be the output of the a) 212
following code? 32

b) 9
27

c) 567
98

d) None of the mentioned

Ans: (b)
4. What will be the output of the a) 4
following code?

b) 5

c) 1

d) Exception

Ans: (a)
5. What will be the output of the a) True
following code?

b) None

c) False

d) Error

Ans: (c)
6. What will be the output of the a) [0]
following code? [1]
[2]

b) [0]
[0,1]
[0,1,2]

c) [1]
[2]
[3]

d) [1]
[1,2]
[1,2,3]

Ans: (b)
7. What will be the output of the a) True
following code?
b) False

c) None

d) Error

Ans: (a)
That’s all.
For now.

You might also like