0% found this document useful (0 votes)
4 views

Lesson 5 Functions

Lesson 5 focuses on modular programming in Python, emphasizing the importance of functions for organizing and managing code as programs grow in complexity. It covers defining functions, passing values, returning results, and the use of global variables, along with practical exercises to reinforce these concepts. The lesson concludes with a review and a preview of the next lesson on Python modules.

Uploaded by

Qombuter Agafari
Copyright
© © All Rights Reserved
Available Formats
Download as ODP, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Lesson 5 Functions

Lesson 5 focuses on modular programming in Python, emphasizing the importance of functions for organizing and managing code as programs grow in complexity. It covers defining functions, passing values, returning results, and the use of global variables, along with practical exercises to reinforce these concepts. The lesson concludes with a review and a preview of the next lesson on Python modules.

Uploaded by

Qombuter Agafari
Copyright
© © All Rights Reserved
Available Formats
Download as ODP, PDF, TXT or read online on Scribd
You are on page 1/ 48

Lesson 5: Modular Programming With

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

So far, we’ve dealt with function that come built in


with Python. Such as print() , input(), type(), range()


and the functions in the math & str library.
The creators of Python figured that many programmers

would want some way to get input from their users.



For that reason, they created the input function. It's input's job to get user
information and store it in whatever variable is on the left side of the equal sign.

You don’t have to worry about the code because it is
all contained inside the function Python provides. And
that is the beauty of functions.

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:

Let’s go one by one with the components.


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

You probably noticed that the previous function


didn't receive any values or return any values



Instead, it did some printing.

Other programming languages like to call
functions like that procedures or subroutines and
reserve the name functions for things that return
values.

Python skips over this distinction and just labels
everything as a function.

Technically, every Python function does return a
value. You’ll learn about that later in this lesson.
18
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

data types, that's where you put the variable


names that you want to use.

If you happen to have more than one parameter
in your list, just separate each one with a
comma.

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:

The interesting thing about writing a function like this in


Python is that when you call print_value, it doesn't matter


whether you pass it a string or a number.
Either way, the function will work and print whatever value

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

variable name in the calling


statement and a second
variable name in the function's
parameter list.

This is okay because you’re
passing the value, Pat, stored
in name, which is then stored
in the variable value inside the
function.

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,

and then call on it to see exactly what's happening.

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,

you're creating a local variable.


This is a variable that can only be used inside the function.


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

For that, you can use the


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.

Here’s a lambda function that accepts two values.


38
Some exercises:

Write a Python function to find the Max of two


numbers.

39
Some exercises:


A possible solution.


Now use this to calculate Max of three.

40
Some exercises:


Here’s a solution:-

Write a function that calculates factorial of a


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

You might also like