• No results found

Python - functions. Jan Hnilica Programming 6 1

N/A
N/A
Protected

Academic year: 2021

Share "Python - functions. Jan Hnilica Programming 6 1"

Copied!
24
0
0

Loading.... (view fulltext now)

Full text

(1)
(2)

What is a function

• a function is a subprogram, that can process data and return a value • functions:

1. inbuilt Python functions

• are a part of the Python interpreter, supplied for your use • e.g. the function print(…)

2. your own functions (i.e. functions written by a programmer)

• almost each program (regardless of a programming language) contains some programmer-defined functions

(3)

Definition of a function

• a function must be defined prior its usage in a program • an example: a function calculating an area of a rectangle

def calculate_area(length, width): area = length * width

return area

• the function calculate_area

• takes two arguments – a length and a width of a rectangle • returns an area of the rectangle

arguments = an information passed into a function return value = an information returned from a function

(4)

Definition of a function

def calculate_area(length, width): area = length * width

return area

• a definition consists of two parts:

1. head of the function (first line) containing (in this order):

• the keyword def • name of the function

• a list of arguments in round brackets • a colon

2. body of the function

• sequence of statements, all statements are indented

(5)

Call of a function

# definition

def calculate_area(length, width): area = length * width

return area

# usage

l = int(input("enter a length: ")) w = int(input("enter a width: "))

a = calculate_area(l, w) # call of a function

print("area is", a)

• a function is called by writing its name followed by its arguments in round brackets

• the following program asks a user to enter the length and width of rectangle and calls a function to calculate its area

(6)

What happens when a function is called?

• normally a program is executed line by line by the interpreter (Python)

• when a function call is encountered, the Python pauses the execution of the main thread and makes a branch into the body of the function

• when the function finishes, the execution continues on the next line of the program • note that a function can call another function

# program statement 1 statement 2 function(...) statement 3 statement 4 ... # function def function(...): statement 1 statement 2 statement 3

(7)

The return statement

return expression

• returns a value from a function

# definition – the function returns larger from two numbers

def maximum(a, b): if a > b:

return a else:

return b

# function call in a program

larger = maximum(x, y)

• when a function reaches a return statement, it finishes immediately (remaining statements, if any, are skipped)

(8)

Functions returning no value

# definition def draw_line(length): for i in range(length): print("-", end = "") # call draw_line(15)

• in fact, such functions return None

• they do not need contain a return statement

• function can use a return statement to finish before the end of its body

def function(...): statement if condition: return statement statement

(9)

# definition

def caution():

print("Be aware, the computer has no brain!!!")

# call

caution()

• a definition and a function call must include (empty) round brackets

Functions without arguments

(10)

Formal arguments

import math

def area(radius): # the name radius is self-explaining

return math.pi * radius * radius

def area(x): # what is the meaning of x? (radius, diameter...)

return math.pi * x * x

• a head of the function presents the formal arguments • formal arguments

• inform about the number and meaning of arguments • they should have self-explaining names

(11)

Actual arguments

• = arguments used within a function call

• in general the actual arguments are Python expressions:

a = area(5) # a constant

a = area(x) # a variable

a = area(3 * x + 5) # an arithmetic expression

a = area(x > 3) # a logical expr., evaluates to 1(True) or 0(False)

(12)

Global and local variables

• each variable has its lifetime, which defines where in the program is the variable accessible and available

• variables:

1. global

• defined outside any function

• accessible anywhere in the program

2. local

• defined inside a function

• exist (and are accessible) only in the function where they was defined • deleted when the function finishes

(13)

Global and local variables

# global variable

glob = "global variable" def function():

# local variable

loc = "local variable"

# both variables are available in the function

print(glob) print(loc)

# function call (prints both variables)

function()

# only the global variable is available outside the function

print(glob)

(14)

Change of global variable inside the function

def function():

glob = "new value of glob" print(glob)

glob = "global variable"

function() # prints: new value of glob

print(glob) # prints: global variable

• this way does not work:

a new local variable (with the same name as the global variable) is created and

hides the global variable in the function

def function(): global glob

glob = "new value of glob" print(glob)

glob = "global variable"

function() # prints: new value of glob

print(glob) # prints: new value of glob

(15)

Passing arguments by value

def increase(x): x = x + 1 print("in function:", x) x = 5 print(x) # prints: 5

increase(x) # prints: in function: 6

print(x) # prints: 5

• arguments passed into a function are stored as local variables in the function ⇒ if a variable is passed in this way, its value is copied to the local variable • whatever you do with arguments you do in fact with these local copies

⇒ changes of arguments do not affect passed variables outside the function • this mechanism is called "passing by value "

(16)

Passing arguments by reference

def change(x): x[0] = 555 print("in function:", x) x = [1, 2, 3] print(x) # prints: [1, 2, 3]

change(x) # prints: in function: [555, 2, 3]

print(x) # prints: [555, 2, 3]

• only a reference to the variable is passed to the function

• the reference is stored in a local variable, but both references (original outside the function and the local copy) point to the same variable

• the changes made in the function affect the variable outside the function

This holds for: list, dictionary, set

(17)

Assigning a new value to the passed reference

def change(x): x = [4, 5, 6] print("in function:", x) x = [1, 2, 3] print(x) # prints: [1, 2, 3]

change(x) # prints: in function: [4, 5, 6]

print(x) # prints: [1, 2, 3]

• if you assign a new variable to the passed reference, the change will not appear outside the function (because the reference itself is stored in a local variable)

(18)

Positional arguments

def function(x, y, z): print("argument x:", x) print("argument y:", y) print("argument z:", z) function(3, 5, 1)

• up to now, all arguments we used were positional • positional arguments

• have no default values

• are passed to a function according to their position in the list of arguments • cannot be omitted when the function is called

(otherwise an error occures)

argument x: 3 argument y: 5 argument z: 1

(19)

Positional arguments

def function(a, b, c): print("argument a:", a) print("argument b:", b) print("argument c:", c) function(b = 1, c = 2, a = 3)

• do not need to be passed in a given order, but in such case it is necessary to call them through their names with the assignment operator

argument a: 3 argument b: 1 argument c: 2

(20)

Keyword arguments

def function(x = 1, y = 2, z = 3): print("argument x:", x) print("argument y:", y) print("argument z:", z) function() function(y = 5, z = 44, x = 0) function(z = 7)

• have default values

• if they are omitted within the function call, their default values are used

• do not need to be passed in a given order (then we call them through their names)

argument x: 1 argument y: 2 argument z: 3 argument x: 0 argument y: 5 argument z: 44 argument x: 1 argument y: 2 argument z: 7

(21)

Mixing positional and keyword arguments

def function(a, b, c = 10, d = 11): print("argument a:", a) print("argument b:", b) print("argument c:", c) print("argument d:", d)

• positional and keyword arguments can be mixed in one function

the rule: positional arguments must be declared before keyword arguments

• within the function call - the arguments are passed in left to right order

function(1, 2) function(1, 2, 3) function(1, 2, d = 3) argument a: 1 argument b: 2 argument c: 10 argument d: 11 argument a: 1 argument b: 2 argument c: 3 argument d: 11 argument a: 1 argument b: 2

(22)

Function with arbitrary number of arguments

def function(*param): i = 0 for p in param: print("argument {}: {}".format(i, p)) i += 1 function(5, 7, "hello")

• useful when we do not know in advance how many arguments will be passed • we use an argument with an asterisk (*) before its name: *argument

• all passed arguments are stored as a tuple

argument 0: 5 argument 1: 7

argument 2: hello

• note that an arbitrary argument must be declared behind the positional arguments: def function(x, y, *z):

(23)

Function itself is an object

def func(x):

print(2 * x)

func(7) # function call

new_ref = func # new reference

del func # deleting original reference

new_ref(4) # using the new reference

• we can assign a function to another variable

(it means we can create a new reference to the function) • we can also delete any reference to the function

output: 14 8

(24)

Why do we write function

1. repeated usage of code in the program

• we do not need copy the same code in several places 2. clear program structure

• the aim is to split an overall task into several smaller tasks

• the program consists of function calls, functions only pass their results from one to another

• properly designed functions make the program well manageable • functions itself should

• be short

• do clearly defined tasks • have an appropriate name

References

Related documents

everyone else who were not members of the First or Second Estates. There was an enormous logistical problem with the way in which the estates were divided for example, the First

4.1 The Select Committee is asked to consider the proposed development of the Customer Service Function, the recommended service delivery option and the investment required8. It

National Conference on Technical Vocational Education, Training and Skills Development: A Roadmap for Empowerment (Dec. 2008): Ministry of Human Resource Development, Department

A consequence of this perspective of woman directors being appointed as part of the symbolic management of the independence of the board is that, when these directors lose

Marie Laure Suites (Self Catering) Self Catering 14 Mr. Richard Naya Mahe Belombre 2516591 [email protected] 61 Metcalfe Villas Self Catering 6 Ms Loulou Metcalfe

The upper section of the drawing (above the spring of tiburio ) is open to various interpretations, due to the difficulty to distinguish between sectioned and/or

Um fato interessante ´e que na base padr˜ao, com excec¸˜ao do classificador 2-NN, o menor resultado foi obtido utilizando o mesmo bag size (70%) e em todos os casos os pior

Further, by showing that v τ is a modular unit over Z we give a new proof of the fact that the singular values of v τ are units at all imaginary quadratic arguments and obtain