0% found this document useful (0 votes)
34 views21 pages

Chapter 6

Uploaded by

www.tooo18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views21 pages

Chapter 6

Uploaded by

www.tooo18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Kingdom of Saudi Arabia ‫المملكة العربية السعودية‬

Ministry of education ‫وزارة التعليم‬


Qassim University ‫جامعة القصيم‬
Applied College ‫الكلية التطبيقية‬

Chapter 6: Functions

Part 1

1
ITBS103

Why do we need functions?


➢ You've come across functions many times so far, but the view on their merits that we
have given you has been rather one-sided. You've only invoked functions by using them
as tools to make life easier, and to simplify time-consuming and tedious tasks.
➢ When you want some data to be printed on the console, you use print(). When you
want to read the value of a variable, you use input(), coupled with either int() or float().
➢ You've also made use of some methods, which are in fact functions, but declared in a
very specific way.
➢ Now you'll learn how to write and use your own functions. We'll write several functions
together, from the very simple to the rather complex, which will require your focus and
attention.

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

Why do we need functions?


➢ We can now define the first condition which can help you decide when to start
writing your own functions: if a particular fragment of the code begins to appear in
more than one place, consider the possibility of isolating it in the form of a
function invoked from the points where the original code was placed before.
➢ It may happen that the algorithm you're going to implement is so complex that your
code begins to grow in an uncontrolled manner, and suddenly you notice that you're
not able to navigate through it so easily anymore.

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

Why do we need functions?

➢ This considerably simplifies the work of the program, because


each piece of code can be encoded separately, and tested
separately. The process described here is often
called decomposition.
➢ We can now state the second condition: if a piece of code
becomes so large that reading and understating it may
cause a problem, consider dividing it into separate, smaller
problems, and implement each of them in the form of a
separate function.
➢ This decomposition continues until you get a set of short
functions, easy to understand and test.
6
ITBS103

3
Decomposition

➢ It often happens that the problem is so large and complex


that it cannot be assigned to a single developer, and a team
of developers have to work on it. The problem must be split
between several developers in a way that ensures their
efficient and seamless cooperation.
➢ It seems inconceivable that more than one programmer
should write the same piece of code at the same time, so
the job has to be dispersed among all the team members.

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

Your first function


➢ You need to define it. The word define is significant here.
➢ This is what the simplest function definition looks like:
def function_name():
function_body
✓ It always starts with the keyword def (for define)
✓ next after def goes the name of the function (the rules for naming functions are exactly the same as for
naming variables)
✓ after the function name, there's a place for a pair of parentheses (they contain nothing here, but that will
change soon)
✓ the line has to be ended with a colon;
✓ the line directly after def begins the function body ‒ a couple (at least one) of necessarily nested instructions,
which will be executed every time the function is invoked; note: the function ends where the nesting ends, so
you have to be careful. 10
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

Your first function

➢ 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.")

➢ The output looks different now:

We start here.
Enter a value:
We end here.

Test the code, modify it, experiment with it. 12


ITBS103

12

6
How functions work

➢ Look at the picture on the right.


➢ It tries to show you the whole process:
✓ when you invoke a function, Python remembers the
place where it happened and jumps into the invoked
(‫ )استدعاء‬function;
✓ the body of the function is then executed;
✓ reaching the end of the function forces Python
to return to the place directly after the point of
invocation (‫)استدعاء‬.
➢ There are two, very important, catches. Here's the first of them:
➢ You mustn't invoke a function which is not known at the moment of invocation.
➢ Remember - Python reads your code from top to bottom. It's not going to look ahead in order to find a
function you forgot to put in the right place ("right" means "before invocation".)
➢ We've inserted an error into this code ‒ can you see the difference? 13
ITBS103

13

How functions work

print("We start here.")


message()
print("We end here.")
def message():
print("Enter a value: ")

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:

NameError: name 'message' is not defined

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

How functions work

➢ 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:

def your_function(optional parameters):


# the body of the function
17
ITBS103

17

SECTION SUMMARY

➢ You can define a function which doesn't take any arguments, e.g.:

def message(): # defining a function


print("Hello") # body of the function

message() # calling the function

➢ 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

name = input("Enter your name: ")

hello(name) # calling the function

➢ We'll tell you more about parametrized functions in the next section. Don't worry.
18
ITBS103

18

9
SECTION QUIZ

Question 1: The input() function is an example of a:


a) user-defined function
b) built-in function

Question 2: What happens when you try to invoke a


function before you define it? Example:
hi()
An exception will be thrown (the TypeError exception to
Output be more precise) - the hi() function doesn't take any
def hi():
arguments.
print("hi!")

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:

def message(number): ###

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

Let's now improve the function's body:


def message(number):
print("Enter a number:", number)
➢ We've made use of the parameter. Note: we haven't assigned the parameter with any value. Is it correct?
➢ Yes, it is.
➢ A value for the parameter will arrive from the function's environment.
➢ Remember: specifying one or more parameters in a function's definition is also a requirement, and
you have to fulfil it during invocation. You must provide as many arguments as there are defined
parameters.
➢ Failure to do so will cause an error.
➢ Try to run the code in the editor.
Traceback (most recent call last):
def message(number): File "main.py", line 4, in <module>
print("Enter a number:", number) Output message()
TypeError: message() missing 1 required positional
message() argument: 'number' 22
ITBS103

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

➢ We have to make you sensitive to one important circumstance.


➢ It's legal, and possible, to have a variable named the same as a function's parameter.
➢ The snippet illustrates the phenomenon:

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

named number. ITBS103

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:

def message(what, number):


print("Enter", what, "number", number)

➢ 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

Positional parameter passing

➢ 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.

def my_function(a, b, c):


print(a, b, c)

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

Keyword argument passing

➢ 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:

def introduction(first_name, last_name):


print("Hello, my name is", first_name, last_name)

introduction(first_name = "James", last_name = "Bond")


introduction(last_name = "Skywalker", first_name = "Luke")

➢ 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

➢ Of course, you mustn't use a non-existent parameter name.


➢ The following snippet will cause a runtime error:

def introduction(first_name, last_name):


print("Hello, my name is", first_name, last_name)

introduction(surname="Skywalker", first_name="Luke")

➢ This is what Python will tell you:

TypeError: introduction() got an unexpected keyword argument 'surname'

Try it out yourself.

29
ITBS103

29

Mixing positional and keyword arguments

➢ 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

➢ It was ‒ as you may suspect ‒ a pure example of positional argument passing. 30


ITBS103

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.

➢ Let's try to mix both styles now.


➢ Look at the function invocation below:

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

Mixing positional and keyword arguments

➢ 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:

TypeError: adding() got multiple values for argument 'a'

➢ 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

Parametrized functions – more details

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)

➢ This makes the following invocation absolutely valid:


introduction()
➢ And this is the expected output:
Hello, my name is John Smith 34
ITBS103

34

17
Parametrized functions – more details

➢ If you use one keyword argument, the remaining one will take the default value:

introduction(last_name="Hopkins")

The output is:

Hello, my name is John 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:

def hi_all(name_1, name_2):


print("Hi,", name_2)
print("Hi,", name_1)

hi_all("Sebastian", "Konrad")
36
ITBS103

36

18
SECTION SUMMARY

➢ An example of a three-parameter function:

def address(street, city, postal_code):


print("Your address is:", street, "St.,", city, postal_code)

s = input("Street: ")
p_c = input("Postal Code: ")
c = input("City: ")
address(s, c, p_c)

37
ITBS103

37

SECTION SUMMARY

2. You can pass arguments to a function using the following Ex. 1


def subtra(a, b):
techniques: print(a - b)
❑ positional argument passing in which the order of subtra(5, 2) # outputs: 3
subtra(2, 5) # outputs: -3
arguments passed matters (Ex. 1)
❑ keyword (named) argument passing in which the order of Ex. 2
def subtra(a, b):
arguments passed doesn't matter (Ex. 2) print(a - b)
❑ a mix of positional and keyword argument passing (Ex. 3.) subtra(a=5, b=2) # outputs: 3
subtra(b=2, a=5) # outputs: 3

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:

def subtra(a, b):


print(a - b)

subtra(5, b=2) # outputs: 3


subtra(a=5, 2) # Syntax Error

➢ Python will not let you do it by signalling a SyntaxError.


3. You can use the keyword argument-passing technique to pre-define a value for a given argument:

def name(first_name, last_name="Smith"):


print(first_name, last_name)

name("Andy") # outputs: Andy Smith


name("Betty", "Johnson") # outputs: Betty Johnson (the keyword argument replaced by
"Johnson") 39
ITBS103

39

SECTION QUIZ

Question 1: What is the output of the following snippet?


def intro(a="James Bond", b="Bond"):
print("My name is", b + ".", a + ".")
Output My name is Bond. James Bond.
intro()

Question 2: What is the output of the following snippet?

def intro(a="James Bond", b="Bond"):


print("My name is", b + ".", a + ".")
Output My name is Sean Connery. James Bond.
intro(b="Sean Connery")

Question 3: What is the output of the following snippet?

def intro(a, b="Bond"):


print("My name is", b + ".", a + ".")
Output My name is Bond. Susan.
intro("Susan")
40
ITBS103

40

20
SECTION QUIZ

Question 1: What is the output of the following snippet?

def add_numbers(a, b=2, c):


print(a + b + c)

add_numbers(a=1, c=3)

Output
SyntaxError - a non-default argument (c) follows a default argument (b=2).

41
ITBS103

41

21

You might also like