Lesson 5 Functions
Lesson 5 Functions
Functions
Introduction to Python Programming
Lesson 5: Modular Programming With
Functions
➢
Lesson Overview
➢
Introduction
➢
Python Functions
➢
Sending Information In
➢
Getting Values Back
➢
Review
Introduction
➢
The programs you’ve created so far have been
small programs that executed statements in a
list, so you haven’t needed to group and organize
your code.
➢
However, as your programs become more
complex, organization will become key in keeping
your code manageable.
Programmers call grouping and organizing code
➢
modular programming.
3
Introduction
➢
A function provides a way to name and group a
set of Python statements.
➢
Then, any time you want to run those statements, you can just call on
that function and they'll run.
➢
For example – remember remember the code you wrote to calculate
averages?
➢
In this lesson, you’ll learn how to define, pass
values to, get results from, and call functions in
your Python programs.
4
Introduction
5
Python Functions: The Parts of a
Function
6
Python Functions: List of Python built in
functions
➢
Here’s a list of the
Python built in
functions.
➢
You can find this
along with what they
do at :
https://docs.python.or
g/3/library/functions.h
tml
7
Python Functions: The Parts of a
Function
➢
They save you time and effort and enable you to
concentrate on more important things—like the
rest of your code!
➢
Python also provides you – like most other
languages- a way to define your own functions.
➢
You can write a set of code, save it in a function,
and then any time you want to run that code, you
just call the function.
8
Python Functions: The General Form of
a Python Function
➢
The general form of a Python function is as
follows:
9
Python Functions: The General Form of
a Python Function
➢
1. The first is the keyword def
for define. You need that to
indicate to python that you are
defining a function here.
➢
2. The parentheses and the
parameter list within them
come next.
➢
The parentheses are required, even if your
function doesn't have any parameters in its
parameter list.
➢
The parameter list is a list of the variables that
the function needs from the calling statement in
order to work correctly.
10
Python Functions: The General Form of
a Python Function
➢
3. Notice the colon at the
end of the first line.
➢
4. The statements inside the
body of our function are
indented.
➢
You're allowed to include as many
statements inside your function as you
like.
➢
However, you need to indent the code so
that Python knows which statements are
a part of the function and which aren't.
11
Python Functions: The General Form of
a Python Function
➢
5.Although it isn't required, it's
strongly recommended that you
include at least one documentation
string (docstring) as the first line of
your Python functions.
➢
This string literal is just a single line enclosed in
three sets of double quotes that gives the purpose
of the function.
➢
Although it doesn't affect the functionality of your
code, there are tools that will go through your
programs and use these strings to generate
documentation for your programs.
➢
This helps others (who may want to use your code)
have a clear understanding of how to use it.
12
Python Functions: The General Form of
a Python Function
➢
Be sure to define your
function before placing the
line of code in the file that
calls it.
➢
Typically, programmers will
define all of their functions
at the beginning of a file and
then have all of the calling
statements together at the
end of the file.
13
Python Functions: Creating a Function
➢
Let’s start with a small
function that displays a
welcome message.
➢
If you ran the sample
code above, you’ll notice
that nothing prints
onscreen.
➢
That's because you just
defined the function, you
didn't call it.
14
Python Functions: Calling a Function
➢
Calling a function is simply
writing a line of code that
uses the name of the
function and any arguments
that you want stored in the
parameter list.
➢
For the welcome function,
the call might look
something like this:>
➢
Remember that the
parentheses are required,
even though you aren't
passing any values to the
function.
15
Python Functions: Calling a Function
➢
Now that you’ve
defined print_welcome,
you can use those
statements whenever
you want, by simply
calling the function.
➢
For example, you
might have a program
file that does
something like the
picture. Try to run it.
16
Python Functions: Calling a Function
➢
The sequence of
execution (or control
flow) for a function is
shown in the following
diagram:
17
Sending Information In: Passing Values
to Functions
➢
First, you need to learn how to pass values into
a function.
You can make a list of parameters inside the
➢
parentheses.
And since Python doesn't require you to use
➢
19
Sending Information In: Passing Values
to Functions
➢
For example, maybe you want to write a function
that will print whatever value is passed to it. This
function might look something like:
you pass it
20
Sending Information In: Passing Values
to Functions
➢
You can call the function by
passing it a string and a
number as is shown to the
right and see how it behaves.
Notice that you have one
➢
21
Sending Information In: Passing Values
to Functions
➢
It doesn't make much sense to pass strings in
numeric calculations, so why does Python allow me
to do this?
➢
The answer lies in Python's flexibility.
➢
Because you aren't required to specify a data type for the variables in
your parameter list, you’re allowed to pass any value we want.
➢
While this may cause problems at times, this flexibility is really a powerful
feature.
➢
Unfortunately, with power comes responsibility. This just means that you'll
need to be careful when you call on a math function so that you get the
results you expect.
22
Sending Information In: Modifying
Variables Inside a Function
➢
What happens if you attempted to change the value
inside the function.
➢
And what would happen outside the function call?
Let's write a new function that makes such a change,
➢
23
Sending Information In: Modifying
Variables Inside a Function
➢
When you try this out, you'll see
that in fact the final print
statement displays the value 5.
➢
Again, if you think about
passing values the way it was
described earlier (by copying the
value of the variable into the
new variable inside the function)
then it should make sense.
➢
That's because you’re modifying
the variable that is inside the
function and never touching the
variable that is outside.
24
Sending Information In: Modifying
Variables Inside a Function
➢
What would happen if you changed that final print
statement so that it tries to print the value of the
value variable, instead of the number variable?
➢
It wouldn’t run. That's because of the variable's scope.
➢
The scope of a variable is where the variable is active
in the program.
When you list a variable in a function's parameter list,
➢
➢
When you leave the function, this variable is destroyed, and you cannot access it
anymore.
25
Sending Information In: Global Variables
➢
The ability of functions to make a copy of a value
and store it in a local variable while the function
is running is generally seen as a good thing.
➢
Typically, you don't want to have to worry about
passing a variable over to a function and not
know whether the function is changing the value
or not.
➢
But what happens if this is exactly what you
want? That is, what happens if you want to have
a function modify the contents of a variable that
is not part of the parameter list?
26
Sending Information In: Global Variables
global statement.
➢
This statement tells Python
that you're going to want to
access and be able to modify a
variable that isn't part of the
current function.
➢
To use the global statement,
just put the keyword global,
followed by the list of variables
that you want to access.
➢
The code to the right shows
that.
27
Sending Information In: Global Variables
➢
Comment out the line as
shown to the right to
check how that affects
the code.
➢
Next we will see
functions that return a
value or “fruitful
functions”.
28
Getting Values Back: Returning Values
from Functions
➢
Passing a value back or returning a value from a
function is done with the keyword return.
➢
You'll just place this keyword, followed by the
value you want returned, at the end of your
function.
➢
It is important to note that once Python reaches
the return statement, control will pass back to
the statement that called the function.
➢
This means that any code you put after the
return statement will never be executed.
29
Getting Values Back: Returning Values
from Functions
➢
Here’s a function that
returns the square of a
number.
➢
You could also just write
return num*num instead
of the two lines of code
or the result variable.
➢
You can call the function
to do the squares of the
first ten numbers by
using the second code.
30
Getting Values Back: All Python
Functions Return a Value
➢
In some programming languages there’s a
distinction between between functions that
return values and those that don't.
➢
Python doesn’t differentiate between functions
that way; technically all Python functions return
a value.
➢
That's because at the end of every function,
there's an implied statement that says return
None.
31
Getting Values Back: All Python
Functions Return a Value
➢
Here’s a demonstration.
32
Getting Values Back: Default Arguments
➢
There may be times when you
want to allow a function to be
called with fewer arguments than
is required in a parameter list.
➢
This is called a default argument.
➢
In this case, you need to provide
a default value in your parameter
list, which is done by placing an
equal sign and a value next to the
variable in your parameter list.
33
Getting Values Back: Default Arguments
➢
The purpose of a default value may not be clear based on
the preceding example, but there are times when it may
be quite helpful.
➢
For example, maybe you want a function that will print a prompt and then allow the
user a specified number of chances to enter either yes or no. You could use default
arguments here.
34
Getting Values Back: Keyword
Arguments
➢
You can use keyword
arguments to specify
which variables in the
function's parameter list
should be storing which
values.
➢
You're allowed to call
the functions with the
parameters out of order,
as is shown in the
second function call.
35
Python Lambda/Anonymous Function
➢
In Python, a lambda function
is a special type of function
without the function name.
➢
We use the lambda keyword
instead of def to create a
lambda function. Here's the
syntax to declare the lambda
function:
➢
arguments(s) is any value
passed to the lambda
function.
➢
Expression is the expression
that executed and returned.
36
Python Lambda/Anonymous Function
➢
Here’s an example – we create the lambda
function and store it in the variable greet – then
we call it.
37
Python lambda Function with an
Argument
➢
Here’s a lambda function that accepts one value.
38
Some exercises:
numbers.
39
Some exercises:
➢
A possible solution.
➢
Now use this to calculate Max of three.
40
Some exercises:
➢
Here’s a solution:-
number:
41
Some exercises:
➢
Here’s a solution:-
➢
Write a program to check whether a string is a
palindrome.
42
Some exercises:
➢
Here’s a solution:-
➢
Write a program that uses recursion to count
from a user input n to 1. When it reaches 1 – it
should display “Blast Off”.
43
Some exercises:
➢
Here’s a solution:-
➢
Write a program to check if a number is prime.
44
Some exercises:
➢
Here’s a solution:-
45
Some exercises:
➢
Here’s a program that generates a password.
➢
Modify it so it uses functions and it asks the user for
the length and the type of characters he wants
included in the final password.
46
Lesson 5 Review
➢
In this lesson, you learned how to define and call
on your own functions.
➢
You also found out how to pass data back and
forth between function calls and function
definitions.
➢
In the next lesson you’ll learn more about
modules in Python. So far you have been writing
all of your code in a single module.
➢
You’ll take a look at some common modules that
have already been written for you and then move
on and write some of your own.
49
Some exercises:
➢
Modify your temperature converter program so
that it uses functions for the conversions.
➢
The greatest common divisor (GCD) of a and b
is the largest number that dividesboth of them
with no remainder. One way to find the GCD of
two numbers is based on the observation that if
r is the remainder whena is divided by b, then
gcd(a, b) = gcd(b, r). As a base case, we can use
gcd(a, 0) = a. Write a function called gcd that
takes parameters a and b and returns their
greatest common divisor.
50