Chapter 6
Chapter 6
Chapter 6: Functions
Part 1
1
ITBS103
2
ITBS103
1
➢ It often happens that a particular piece of code is repeated many times in your
program. It's repeated either literally, or with only a few minor modifications,
consisting of the use of other variables in the same algorithm. It also happens that
a programmer cannot resist simplifying their work, and begins to clone such pieces
of code using the clipboard and copy-paste operations.
➢ It could end up as greatly frustrating when suddenly it turns out that there was an
error in the cloned code. The programmer will have a lot of drudgery to find all the
places that need corrections. There's also a high risk of the corrections causing
errors.
3
ITBS103
4
ITBS103
2
➢ You can try to cope with the issue by commenting the code extensively, but
soon you find that this dramatically worsens your situation ‒ too many
comments make the code larger and harder to read. Some say that
a well-written function should be viewed entirely in one glance.
➢ A good, attentive developer divides the code (or more accurately: the
problem) into well-isolated pieces, and encodes each of them in the form
of a function.
5
ITBS103
3
Decomposition
7
ITBS103
➢ This kind of decomposition has a different purpose to the one described previously
‒ it's not only about sharing the work, but also about sharing the
responsibility among many developers.
➢ Each of them writes a clearly defined and described set of functions, which
when combined into the module (we'll tell you about this a bit later) will give the
final product.
➢ This leads us directly to the third condition: if you're going to divide the work among
multiple programmers, decompose the problem to allow the product to be
implemented as a set of separately written functions packed together in
different modules.
8
ITBS103
4
Where do the functions come from?
In general, functions come from at least three places:
❖ Python: from Python itself ‒ numerous functions (like print()) are an integral part of
Python, and are always available without any additional effort on behalf of the programmer;
we call these functions built-in functions;
❖ Modules: from Python's preinstalled modules ‒ a lot of functions, very useful ones, but
used significantly less often than built-in ones, are available in a number of modules
installed together with Python; the use of these functions requires some additional steps
from the programmer in order to make them fully accessible (we'll tell you about this in a
while);
❖ Code: directly from your code ‒ you can write your own functions, place them inside your
code, and use them freely;
❖ there is one other possibility, but it's connected with classes, so we'll omit it for now. 9
ITBS103
10
5
Your first function
➢ We're ready to define our prompting function. We'll name it message ‒ here it is:
def message():
print("Enter a value: ")
➢ The function is extremely simple, but fully usable. We've named it message, but you can label it
according to your taste. Let's use it.
➢ Our code contains the function definition now:
def message():
print("Enter a value: ")
print("We start here.")
print("We end here.")
Note: we don't use the function at all ‒ there's no invocation of it inside the code.
When you run it, you see the following output:
We start here.
11
We end here. ITBS103
11
➢ This means that Python reads the function's definitions and remembers them but won't launch any of them
without your permission.
➢ We've modified the code now ‒ we've inserted the function's invocation between the start and end messages:
def message():
print("Enter a value: ")
print("We start here.")
message()
print("We end here.")
We start here.
Enter a value:
We end here.
12
6
How functions work
13
We've moved the function to the end of the code. Is Python able to find it when the execution reaches the
invocation?
No, it isn't. The error message will read:
Don't try to force Python to look for functions you didn't deliver at the right time.
14
ITBS103
14
7
How functions work
➢ The second catch sounds a little simpler:
➢ You mustn't have a function and a variable of the same name.
➢ The following snippet is erroneous:
def message():
print("Enter a value: ")
message = 1
➢ Assigning a value to the name message causes Python to forget its previous role. The function
named message becomes unavailable.
➢ Fortunately, you're free to mix your code with functions ‒ you're not obliged to put all your functions at
the top of your source file.
➢ Look at the snippet: print("We start here.")
def message():
It may look strange, print("Enter a value: ")
but it's completely message()
print("We end here.")
correct, and works as
15
intended. ITBS103
15
➢ Let's return to our primary example, and employ the function for the right job, like here:
def message():
print("Enter a value: ")
message()
a = int(input())
message()
b = int(input())
message()
c = int(input())
➢ Modifying the prompting message is now easy and clear - you can do it by changing the code in just
one place ‒ inside the function's body.
➢ Open the editor and try to do it yourself.
16
ITBS103
16
8
SECTION SUMMARY
1. A function is a block of code that performs a specific task when the function is called (invoked). You can
use functions to make your code reusable, better organized, and more readable. Functions can have
parameters and return values.
2. There are at least four basic types of functions in Python:
✓ built-in functions which are an integral part of Python (such as the print() function). You can see a
complete list of built-in Python functions at https://docs.python.org/3/library/functions.html.
✓ the ones that come from pre-installed modules (you'll learn about them in the Python Essentials
2 course)
✓ user-defined functions which are written by users for users ‒ you can write your own functions and
use them freely in your code,
✓ the lambda functions (you'll learn about them in the Python Essentials 2 course.)
3. You can define your own function using the def keyword and the following syntax:
17
SECTION SUMMARY
➢ You can define a function which doesn't take any arguments, e.g.:
➢ You can define a function which takes arguments, too, just like the one-parameter function below:
def hello(name): # defining a function
print("Hello,", name) # body of the function
➢ We'll tell you more about parametrized functions in the next section. Don't worry.
18
ITBS103
18
9
SECTION QUIZ
Question 3: What will happen when you run the code below?
def hi():
print("hi") An exception is thrown (the NameError exception to be
Output more precise).
hi(5)
19
ITBS103
19
Section 2
How functions communicate with their environment
In this section you will learn about parameterless and parameterized functions, as well as how
to write one-, two-, and three-parameter functions and pass arguments to them. Let's begin!
20
ITBS103
20
10
Parameterized functions
➢ A parameter is actually a variable, but there are two important factors that make parameters different and
special:
✓ parameters exist only inside functions in which they have been defined, and the only place where
the parameter can be defined is a space between a pair of parentheses in the def statement;
✓ assigning a value to the parameter is done at the time of the function's invocation, by specifying
the corresponding argument.
def function(parameter): ###
➢ Don't forget:
✓ parameters live inside functions (this is their natural environment)
✓ arguments exist outside functions, and are carriers of values passed to corresponding parameters.
We have to rebuild the def statement ‒ this is what it looks like now:
The definition specifies that our function operates on just one parameter named number. You can use it as
an ordinary variable, but only inside the function ‒ it isn't visible anywhere else.
21
ITBS103
21
Parameterized functions
22
11
Parameterized functions
def message(number):
print("Enter a number:", number) Output Enter a number: 1
message(1)
Can you see how it works? The value of the argument used during invocation (1) has been
passed into the function, setting the initial value of the parameter named number.
23
ITBS103
23
Parameterized functions
def message(number):
number*=2
print("Enter a number:", number) Enter a number: 8
Output
4
number = 4
message(number)
print(number)
➢ A situation like this activates a mechanism called shadowing:
✓ parameter x shadows any variable of the same name, but...
✓ ... only inside the function defining the parameter.
➢ The parameter named number is a completely different entity from the variable 24
24
12
Parameterized functions
➢ function can have as many parameters as you want, but the more parameters you have, the harder it
is to memorize their roles and purposes.
➢ Let's modify the function ‒ it has two parameters now:
➢ This also means that invoking the function will require two arguments.
➢ The first new parameter is intended to carry the name of the desired value.
➢ Here it is:
def message(what, number):
print("Enter", what, "number", number)
Enter telephone number 11
message("telephone", 11) Output Enter price number 5
message("price", 5) Enter number number number
message("number", "number")
Run the code, modify it, add more parameters, and see how this affects the 25
output. ITBS103
25
➢ A technique which assigns the ith (first, second, and so on) argument to the ith (first, second, and
so on) function parameter is called positional parameter passing, while arguments passed in
this way are named positional arguments.
➢ You've used it already, but Python can offer a lot more. We're going to tell you about it now.
my_function(1, 2, 3)
➢ Note: positional parameter passing is intuitively used by people in many social occasions. For
example, it may be generally accepted that when we introduce ourselves we mention our first
name(s) before our last name, e.g., "My name's John Doe."
➢ Incidentally, Hungarians do it in reverse order.
26
ITBS103
26
13
Positional parameter passing
Let's implement that social custom in Python. The following function will be responsible for introducing
somebody:
def introduction(first_name, last_name):
print("Hello, my name is", first_name, last_name)
introduction("Luke", "Skywalker")
introduction("Jesse", "Quick")
introduction("Clark", "Kent")
➢ Can you guess the output? Run the code and find out if you're right.
➢ Now imagine that the same function is being used in Hungary. In this case, the code would look like this:
def introduction(first_name, last_name): ➢ The output will look different. Can you guess
print("Hello, my name is", first_name, last_name)
it?
introduction("Skywalker", "Luke") ➢ Run the code to see if you're right here, too.
introduction("Quick", "Jesse")
introduction("Kent", "Clark") Are you surprised?
➢ Can you make the function more culture- 27
ITBS103 independent?
27
➢ Python offers another convention for passing arguments, where the meaning of the argument
is dictated by its name, not by its position ‒ it's called keyword argument passing.
❑ Take a look at the snippet:
➢ The concept is clear ‒ the values passed to the parameters are preceded by the target
parameters' names, followed by the = sign.
➢ The position doesn't matter here ‒ each argument's value knows its destination on the basis
of the name used.
➢ You should be able to predict the output. Run the code to check if you're right. 28
ITBS103
28
14
Keyword argument passing
introduction(surname="Skywalker", first_name="Luke")
29
ITBS103
29
➢ You can mix both styles if you want ‒ there is only one unbreakable rule: you have to
put positional arguments before keyword arguments.
➢ If you think for a moment, you'll certainly guess why.
➢ To show you how it works, we'll use the following simple three-parameter function:
def adding(a, b, c):
print(a, "+", b, "+", c, "=", a + b + c)
➢ Its purpose is to evaluate and present the sum of all its arguments.
➢ The function, when invoked in the following way:
adding(1, 2, 3)
➢ will output:
1+2+3=6
30
15
Mixing positional and keyword arguments
➢ Of course, you can replace such an invocation with a purely keyword
variant, like this:
adding(c = 1, a = 2, b = 3)
➢ Our program will output a line like this:
2+3+1=6
Note the order of the values.
adding(3, c = 1, b = 2)
➢ Let's analyze it:
❑ the argument (3) for the a parameter is passed using the positional way;
❑ the arguments for c and b are specified as keyword ones.
❑ This is what you'll see in the console:
3+2+1=6
31
ITBS103
31
➢ Be careful, and beware of mistakes. If you try to pass more than one value to one argument, all
you'll get is a runtime error.
➢ Look at the invocation below - it seems that we've tried to set a twice:
adding(3, a = 1, b = 2)
Python's response:
➢ Look at the snipet below. A code like this is fully correct, but it doesn't make much sense:
adding(4, 3, c = 2)
Everything is right, but leaving in just one keyword argument looks a bit weird ‒ what do you think?
32
ITBS103
32
16
Parametrized functions – more details
➢ It happens at times that a particular parameter's values are in use more often than others. Such
arguments may have their default (predefined) values taken into consideration when their
corresponding arguments have been omitted.
➢ They say that the most popular English last name is Smith. Let's try to take this into account.
➢ The default parameter's value is set using clear and pictorial syntax:
def introduction(first_name, last_name="Smith"):
print("Hello, my name is", first_name, last_name)
➢ You only have to extend the parameter's name with the = sign, followed by the default value.
➢ Let's invoke the function as usual:
introduction("James", "Doe")
Can you guess the output of the program? Run it and check if you're right.
➢ And? Everything looks the same, but when you invoke the function in a way that looks a bit
suspicious at first sight, like this: introduction("Henry") 33
ITBS103
33
or this: introduction(first_name="William")
➢ there will be no error, and both invocations will succeed, while the console will show the
following output:
Hello, my name is Henry Smith
Hello, my name is William Smith
Test it.
➢ You can go further if it's useful. Both parameters have their default values now, look at the
code below:
def introduction(first_name="John", last_name="Smith"):
print("Hello, my name is", first_name, last_name)
34
17
Parametrized functions – more details
➢ If you use one keyword argument, the remaining one will take the default value:
introduction(last_name="Hopkins")
Test it.
Congratulations ‒ you have just learned some basic techniques for communicating with functions.
35
ITBS103
35
SECTION SUMMARY
1. You can pass information to functions by using parameters. Your functions can have as many
parameters as you need.
An example of a one-parameter function:
def hi(name):
print("Hi,", name)
hi("Greg")
An example of a two-parameter function:
hi_all("Sebastian", "Konrad")
36
ITBS103
36
18
SECTION SUMMARY
s = input("Street: ")
p_c = input("Postal Code: ")
c = input("City: ")
address(s, c, p_c)
37
ITBS103
37
SECTION SUMMARY
Ex. 3
def subtra(a, b):
print(a - b)
subtra(5, b=2) # outputs: 3
subtra(5, 2) # outputs: 3
38
ITBS103
38
19
SECTION SUMMARY
➢ It's important to remember that positional arguments mustn't follow keyword arguments.
That's why if you try to run the following snippet:
39
SECTION QUIZ
40
20
SECTION QUIZ
add_numbers(a=1, c=3)
Output
SyntaxError - a non-default argument (c) follows a default argument (b=2).
41
ITBS103
41
21