Chapter 7
Chapter 7
Chapter 7: Functions
Part 2
1
ITBS103
Section 3
Returning a result from a function
In this part of the course you will learn about the effects and results of functions,
the return expression, and the None value. You will also learn how to pass lists as function
arguments, how to return lists as function results, and how to assign function results to
variables. Let's go!
➢ All the previously presented functions have some kind of effect ‒ they produce some text and send it
to the console.
➢ Of course, functions ‒ like their mathematical siblings ‒ may have results.
➢ To get functions to return a value (but not only for this purpose) you use the return instruction.
➢ This word gives you a full picture of its capabilities. Note: it's a Python keyword.
➢ The return instruction has two different variants ‒ let's consider them separately.
2
ITBS103
1
Review:
One line code and adding elements to arrays
x=5
if x>0: print(x)
for i in range(5): print(i, end=" ")
def test(y): return y**2
print(test(3))
arr=[1, 3, 5, 7]
b=arr+[9]
print(len(arr))
print(b)
3
ITBS103
2
Effects and results: the return instruction
happy_new_year(False)
➢ will modify the function's behavior ‒ the return instruction will cause its termination
just before the wishes ‒ this is the updated output:
Three...
Two...
One...
5
ITBS103
return 13
x = boring_function()
print("The boring_function has returned its result. It's:", x)
The boring_function has returned its result. It's: 13 6
ITBS103
3
Effects and results: the return instruction
def boring_function():
print("'Boredom Mode' ON.")
return 13 This lesson is interesting!
print("This lesson is interesting!") Output 'Boredom Mode' ON.
boring_function() This lesson is boring...
print("This lesson is boring...")
7
ITBS103
8
ITBS103
4
A few words about None
➢ Let us introduce you to a very curious value (to be honest, a none value) named None.
➢ Its data doesn't represent any reasonable value ‒ actually, it's not a value at all; hence,
it mustn't take part in any expressions.
➢ For example, a snippet like this:
print(None + 2)
10
5
Effects and results: lists and functions
But you should expect problems if you invoke it in this risky way:
print(list_sum(5)) Output TypeError: 'int' object is not iterable
11
ITBS103
11
➢ This is caused by the fact that a single integer value mustn't be iterated through by the for loop.
➢ The second question is: may a list be a function result?
➢ Yes, of course! Any entity recognizable by Python can be a function result.
➢ Look at the code in the editor:
Output [4, 3, 2, 1, 0]
12
6
LAB Prime numbers ‒ how to find them
A natural number is prime if it is greater than 1 and has no divisors other than 1 and itself.
Complicated? Not at all. For example, 8 isn't a prime number, as you can divide it by 2 and 4 (we can't use
divisors equal to 1 and 8, as the definition prohibits this).
On the other hand, 7 is a prime number, as we can't find any legal divisors for it.
Your task is to write a function checking whether a number is prime or not.
The function: is called is_prime; takes one argument (the value to check)
returns True if the argument is a prime number, and False otherwise.
Hint: try to divide the argument by all subsequent values (starting from 2) and check the remainder ‒ if it's zero,
your number cannot be a prime; think carefully about when you should stop the process.
If you need to know the square root of any value, you can utilize the ** operator. Remember: the square root
of x is the same as x0.5
Complete the code in the editor.
Run your code and check whether your output is the same as ours.
13
ITBS103
13
Solution Output 2 3 5 7 11 13 17 19
14
ITBS103
14
7
LAB Converting fuel consumption
➢ A car's fuel consumption may be expressed in many different ways. For example, in Europe, it is shown as the amount
of fuel consumed per 100 kilometers.
➢ In the USA, it is shown as the number of miles traveled by a car using one gallon of fuel.
➢ Your task is to write a pair of functions converting l/100km into mpg, and vice versa.
➢ The functions:
▪ are named liters_100km_to_miles_gallon and miles_gallon_to_liters_100km respectively;
▪ take one argument (the value corresponding to their names)
➢ Complete the code in the editor and run it to check whether your output is the same as ours.
➢ Here is some information to help you: 60.31143162393162
▪ 1 American mile = 1609.344 metres; 31.36194444444444
23.52145833333333
▪ 1 American gallon = 3.785411784 litres. 3.9007393587617467
➢ Expected output: 7.490910297239916
10.009131205673757
15
ITBS103
15
60.31143162393162
31.36194444444444
23.52145833333333
Solution Output 3.9007393587617467
7.490910297239916
10.009131205673757
16
ITBS103
16
8
SECTION SUMMARY
1. You can use the return keyword to tell a function to return some value. The return statement exits the
function, e.g.:
17
ITBS103
17
SECTION SUMMARY
2. The result of a function can be easily assigned to a variable, e.g.:
def wishes():
return "Happy Birthday!
w = wishes()
print(w) # outputs: Happy Birthday!
Look at the difference in output in the following two examples:
# Example 1
def wishes():
print("My Wishes")
return "Happy Birthday"
wishes() # outputs: My Wishes
# Example 2
def wishes():
print("My Wishes")
return "Happy Birthday
print(wishes())
# outputs: My Wishes
# Happy Birthday
18
ITBS103
18
9
SECTION SUMMARY
def hi_everybody(my_list):
for name in my_list:
print("Hi,", name)
hi_everybody(["Adam", "John", "Lucy"])
def create_list(n):
my_list = []
for i in range(n):
my_list.append(i)
return my_list
print(create_list(5))
19
ITBS103
19
SECTION QUIZ
def hi():
return
print("Hi!") Output The function will return an implicit None value.
hi()
def is_int(data):
if type(data) == int:
return True
elif type(data) == float: True
return False Output False
print(is_int(5)) None
print(is_int(5.0))
print(is_int("5"))
20
ITBS103
20
10
SECTION QUIZ
def even_num_lst(ran):
lst = []
for num in range(ran):
if num % 2 == 0: Output [0, 2, 4, 6, 8, 10]
lst.append(num)
return lst
print(even_num_lst(11))
def list_updater(lst):
upd_list = []
for elem in lst:
elem **= 2
upd_list.append(elem) Output [1, 4, 9, 16, 25]
return upd_list
foo = [1, 2, 3, 4, 5]
print(list_updater(foo))
21
ITBS103
21
Section 4
Scopes in Python
In this part of the course you will learn about scopes in Python, and the
global keyword. By the end of the section you will be able to distinguish
between local and global variables, and know how to utilize the
mechanism of namespaces in your programs.
22
ITBS103
22
11
Functions and scopes
➢ This is to be expected.
➢ We're going to conduct some experiments with you to show you how Python constructs scopes, and how you
can use these to your benefit. 23
ITBS103
23
➢ Let's start by checking whether or not a variable created outside any function is visible
inside the functions. In other words, does a variable's name propagate into a function's
body?
➢ Look at the code in the editor. Our guinea pig is there.
Do I know that variable?
Output 1
1
➢ The answer is: a variable existing outside a function has scope inside the
function's body.
➢ This rule has a very important exception. Let's try to find it.
24
ITBS103
24
12
Functions and scopes
Do I know that
Output variable? 2
1
25
ITBS103
25
➢ What's happened?
❑ the var variable created inside the function is not the same as when defined
outside it ‒ it seems that there two different variables of the same name;
❑ moreover, the function's variable shadows the variable coming from the
outside world.
➢ We can make the previous rule more precise and adequate:
A variable existing outside a function has scope inside the function's body,
excluding those which define a variable of the same name.
➢ It also means that the scope of a variable existing outside a function is
supported only when getting its value (reading). Assigning a value forces the
creation of the function's own variable.
➢ Make sure you understand this well and carry out your own experiments.
26
ITBS103
26
13
Functions and scopes: the global keyword
➢ Hopefully, you should now have arrived at the following question: does this mean that a function is not able
to modify a variable defined outside it? This would create a lot of discomfort.
➢ Fortunately, the answer is no.
➢ There's a special Python method which can extend a variable's scope in a way which includes the
function's body (even if you want not only to read the values, but also to modify them).
➢ Such an effect is caused by a keyword named global:
global name
global name1, name2, ...
➢ Using this keyword inside a function with the name (or names separated with commas) of a variable (or
variables), forces Python to refrain from creating a new variable inside the function ‒ the one accessible
from outside will be used instead.
➢ In other words, this name becomes global (it has global scope, and it doesn't matter whether it's the
subject of read or assign). 27
ITBS103
27
➢ This should be sufficient evidence to show that the global keyword does what it
promises.
28
ITBS103
28
14
How the function interacts with its arguments
➢ Now let's find out how the function interacts with its arguments.
➢ The code in the editor should teach you something. As you can see, the function changes the value
of its parameter. Does the change affect the argument?
I got 1
Output I have 2
1
➢ The conclusion is obvious ‒ changing the parameter's value doesn't propagate outside the
function (in any case, not when the variable is a scalar, like in the example).
➢ This also means that a function receives the argument's value, not the argument itself. This is true for
scalars.
➢ Is it worth checking how it works with lists (do you recall the peculiarities of assigning list slices versus
assigning lists as a whole?). 29
ITBS103
29
def my_function(my_list_1):
print("Print #1:", my_list_1)
print("Print #2:", my_list_2) Print #1: [2, 3]
my_list_1 = [0, 1] Print #2: [2, 3]
print("Print #3:", my_list_1) Output Print #3: [0, 1]
print("Print #4:", my_list_2) Print #4: [2, 3]
Print #5: [2, 3]
my_list_2 = [2, 3]
my_function(my_list_2)
print("Print #5:", my_list_2)
30
ITBS103
30
15
How the function interacts with its arguments
➢ Finally, can you see the difference in the example below:
def my_function(my_list_1):
print("Print #1:", my_list_1) Print #1: [2, 3]
print("Print #2:", my_list_2) Print #2: [2, 3]
del my_list_1[0] # Pay attention to this line. Output Print #3: [3]
print("Print #3:", my_list_1) Print #4: [3]
print("Print #4:", my_list_2) Print #5: [3]
my_list_2 = [2, 3]
my_function(my_list_2)
print("Print #5:", my_list_2)
➢ We don't change the value of the parameter my_list_1 (we already know it will not affect the argument),
but instead modify the list identified by it.
➢ Can you explain it?
➢ Let's try:
▪ if the argument is a list, then changing the value of the corresponding parameter doesn't affect the list
(remember: variables containing lists are stored in a different way than scalars)
▪ but if you change a list identified by the parameter (note: the list, not the parameter!), the list will
reflect the change. 31
➢ It's time to write some example functions. You'll do that in the next section.
ITBS103
31
SECTION SUMMARY
1. A variable that exists outside a function has scope inside the function body (Example 1)
unless the function defines a variable of the same name (Example 2, and Example 3), e.g.:
Example 1:
var = 2
def mult_by_var(x): 14
Output
return x * var
print(mult_by_var(7)) # outputs: 14
Example 2:
def mult(x):
var = 5
Output 35
return x * var
print(mult(7)) # outputs: 35
32
ITBS103
32
16
SECTION SUMMARY
Example 3:
def mult(x):
var = 7
return x * var Output 49
var = 3
print(mult(7))
2. A variable that exists inside a function has scope inside the function body (Example 4), e.g.:
Example 4:
11
def adding(x): ERROR!
var = 7 Traceback (most recent call last):
return x + var Output
File "<string>", line 7, in <module>
print(adding(4)) # outputs: 11 NameError: name 'var' is not defined. Did you
print(var) # NameError mean: 'vars'?
33
ITBS103
33
SECTION SUMMARY
3. You can use the global keyword followed by a variable name to make the variable's scope
global, e.g.:
var = 2
print(var) # outputs: 2
def return_var():
global var 2
var = 5 Output 5
return var 5
print(return_var()) # outputs: 5
print(var) # outputs: 5
34
ITBS103
34
17
SECTION QUIZ
def message():
alt = 1
print("Hello, World!") Output NameError: name 'alt' is not defined
print(alt)
a=1
def fun():
a=2 2
print(a) Output
1
fun()
print(a)
35
ITBS103
35
SECTION QUIZ
Question : What is the output of the following snippet?
a=1
def fun():
global a
a=2
2
print(a) Output
3
fun()
a=3
print(a)
a=1
def fun():
global a
a=2
2
print(a) Output
2
a=3
fun()
print(a)
36
ITBS103
36
18