0% found this document useful (0 votes)
19 views18 pages

Chapter 7

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)
19 views18 pages

Chapter 7

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/ 18

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

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


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

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

Effects and results: the return instruction

❖ return without an expression


➢ Let's consider the following function:
def happy_new_year(wishes = True):
print("Three...")
print("Two...")
print("One...")
if not wishes:
return
print("Happy New Year!")
➢ When invoked without any arguments:
happy_new_year()
➢ the function causes a little noise ‒ the output will look like this: Three...
Two...
One...
Happy New Year! 4
ITBS103

2
Effects and results: the return instruction

❖ return without an expression

➢ Providing False as an argument:

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

Effects and results: the return instruction


❖ return with an expression

➢ The second return variant is extended with an expression:


def function():
return expression
➢ There are two consequences of using it:
❑ it causes the immediate termination of the function's execution (nothing new compared to the
first variant)
❑ moreover, the function will evaluate the expression's value and will return it (hence the name
once again) as the function's result.
➢ Yes, we already know ‒ this example isn't really sophisticated: The snippet writes the
following text to the console:
def boring_function():
Output

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

➢ Let's investigate it for a while.


➢ Analyze the figure below:
➢ The return instruction, enriched with the expression (the expression is
very simple here), "transports" the expression's value to the place where
the function has been invoked.

➢ The result may be freely used here, e.g., to be assigned to a variable.


➢ It may also be completely ignored and lost without a trace.
➢ Note, we're not being too polite here - the function returns a value, and we ignore it (we don't use it in any way):

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

Effects and results: the return instruction

➢ Is it punishable? Not at all.


➢ The only disadvantage is that the result has been irretrievably lost.
➢ Don't forget:
❑ you are always allowed to ignore the function's result, and be satisfied with
the function's effect (if the function has any)
❑ if a function is intended to return a useful result, it must contain the second
variant of the return instruction.
➢ Wait a minute ‒ does this mean that there are useless results, too? Yes, in some
sense.

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)

➢ will cause a runtime error, described by the following diagnostic message:

TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

➢ Note: None is a keyword.


➢ There are only two kinds of circumstances when None can be safely used:
❑ when you assign it to a variable (or return it as a function's result)
❑ when you compare it with a variable to diagnose its internal state. 9
ITBS103

A few words about None


➢ Just like here:
value = None
if value is None:
print("Sorry, you don't carry any value")
➢ Don't forget this: if a function doesn't return a certain value using a return expression clause, it
is assumed that it implicitly returns None.
➢ Let's test it.
➢ Take a look at the code in the editor.
def strange_function(n):
if(n % 2 == 0):
True
return True Output
None
print(strange_function(2))
print(strange_function(1))
Don't be surprised next time you see None as a function result ‒ it may be the symptom of
a subtle mistake inside the function. 10
ITBS103

10

5
Effects and results: lists and functions

➢ There are two additional questions that should be answered here.


➢ The first is: may a list be sent to a function as an argument?
➢ Of course it may! Any entity recognizable by Python can play the role of a function argument, although it
has to be assured that the function is able to cope with it.
➢ So, if you pass a list to a function, the function has to handle it like a list.
➢ A function like this one here:
def list_sum(lst):
s=0
for elem in lst:
s += elem
return s

➢ and invoked like this: print(list_sum([5, 4, 3])) Output 12

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

Effects and results: lists and functions

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

➢ Now you can write functions with and without results.


➢ Let's dive a little deeper into the issues connected with variables in functions. This is essential for
creating effective and safe functions.
12
ITBS103

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

LAB How many primes in the range from 1 to 20?

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

LAB miles and gallons to liters and km code

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

def multiply(a, b):


return a * b
print(multiply(3, 4)) # outputs: 12
def multiply(a, b):
return
print(multiply(3, 4)) # outputs: None

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

3. You can use a list as a function's argument, e.g.:

def hi_everybody(my_list):
for name in my_list:
print("Hi,", name)
hi_everybody(["Adam", "John", "Lucy"])

4. A list can be a function result, too, e.g.:

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

Question : What is the output of the following snippet?

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

Question : What is the output of the following snippet?

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

➢ Let's start with a definition:


➢ The scope of a name (e.g., a variable name) is the part of a code where the name is properly recognizable.
➢ For example, the scope of a function's parameter is the function itself. The parameter is inaccessible outside the
function.
➢ Let's check it. Look at the code in the editor. What will happen when you run it?

def scope_test(): Traceback (most recent call last):


x = 123 File "main.py", line 6, in <module>
Output
print(x)
scope_test() NameError: name 'x' is not defined
print(x)

➢ The program will fail when run.

➢ 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

Functions and scopes

➢ 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

➢ Let's make a small change to the code:

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

Functions and scopes: the global keyword


➢ Look at the code in the editor.

Do I know that variable?


Output 2
2

➢ We've added global to the function.

➢ 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

How the function interacts with its arguments

The following example will shed some light on the issue:

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)

It seems that the former rule still works.

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

Question : What is the output of the following snippet?

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

You might also like