An Introduction to python - ekprwolf/teaching/courses/Python201… · In python functions are...

Preview:

Citation preview

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

INSTITUTE OF EXPERIMENTAL PARTICLE PHYSICS (IEKP) – PHYSICS FACULTY

An Introduction to python

Lecture 05: Functions

Roger Wolf06. June 2019

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

INSTITUTE OF EXPERIMENTAL PARTICLE PHYSICS (IEKP) – PHYSICS FACULTY

Part 11:

The python function

1/25

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Function definition2/25

● In python functions are defined as shown in the example below:

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

2/25

● In python functions are defined as shown in the example below:

Defines a function.

Function definition

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

2/25

● In python functions are defined as shown in the example below:

Defines a function.

Function name.

Function definition

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

2/25

● In python functions are defined as shown in the example below:

Defines a function.

Function name.

Function arguments.

Function definition

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

3/25

● In python functions are defined as shown in the example below:

Interface & implementation

Function interface to outside world/user.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

3/25

● In python functions are defined as shown in the example below:

Interface & implementation

Implementation of the function.

Function interface to outside world/user.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

3/25

● In python functions are defined as shown in the example below:

Interface & implementation

Implementation of the function.

Function interface to outside world/user.

Implementation of function ends here.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

3/25

● In python functions are defined as shown in the example below:

● The function opens its own range of validity (=statement block). I.e. everything indented after the function definition is part of the function.

Interface & implementation

Implementation of the function.

Function interface to outside world/user.

Implementation of function ends here.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

3/25

● In python functions are defined as shown in the example below:

● The function opens its own range of validity (=statement block). I.e. everything indented after the function definition is part of the function.

● Again note the importance of indentation in this case.

Interface & implementation

Implementation of the function.

Function interface to outside world/user.

Implementation of function ends here.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Function call4/25

● The following example shows how the function is called inside your script:

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Function call4/25

● The following example shows how the function is called inside your script:

Here the function is called.

● Function arguments are given in braces, separated by comma.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Return value5/25

● A function may have a return value (while it does not have to):

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Return value5/25

max(x,y) has a return value.

● A function may have a return value (while it does not have to):

● The return value is indicated by the key word return.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Return value5/25

max(x,y) has a return value.

● A function may have a return value (while it does not have to):

● The return value is indicated by the key word return.

● The return value is not type bound, i.e. it could be an int, float, string, tuple, list, … depending on the context (→ see the example above).

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Return value5/25

max(x,y) has a return value.

● A function may have a return value (while it does not have to):

● The return value is indicated by the key word return.

● The return value is not type bound, i.e. it could be an int, float, string, tuple, list, … depending on the context (→ see the example above).

● If there is nothing returned the return value will be None.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Types of function arguments6/25

● The following is a dangerous example of using dynamic typing:

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Types of function arguments6/25

● The following is a dangerous example of using dynamic typing:

The result is 6.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Types of function arguments6/25

● The following is a dangerous example of using dynamic typing:

The result is 6.

The result is aaa.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Types of function arguments6/25

● The following is a dangerous example of using dynamic typing:

The result is 6.

The result is aaa.

● As you see the function does different things depending on the function arguments at runtime. This is possible as long as an operator (here “*”) is defined for all types in use.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Types of function arguments7/25

● The following is a dangerous example of using dynamic typing:

● If you have to be sure about the type of your arguments you can always check it using the function type.

● As you see the function does different things depending on the function arguments at runtime. This is possible as long as an operator (here “*”) is defined for all types in use.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Types of function arguments7/25

● The following is a dangerous example of using dynamic typing:

● If you have to be sure about the type of your arguments you can always check it using the function type.

Checking the type of a variable exploiting the type function.

● As you see the function does different things depending on the function arguments at runtime. This is possible as long as an operator (here “*”) is defined for all types in use.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

8/25

● Tuples (of arbitrary length) can easily be passed to or returned from functions:

Tuples & functions

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

8/25

● Tuples (of arbitrary length) can easily be passed to or returned from functions:

Tuples & functions

Expects two tuples of types (float, float).

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

8/25

● Tuples (of arbitrary length) can easily be passed to or returned from functions:

Tuples & functions

Expects two tuples of types (float, float).

Also returns a tuple of type (float, float).

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

The lambda function10/25

● You can define functions at runtime, which are not bound to a name. These functions are usually used to fulfill simple tasks:

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

The lambda function10/25

● You can define functions at runtime, which are not bound to a name. These functions are usually used to fulfill simple tasks:

This is a normal (named) function.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

The lambda function10/25

● You can define functions at runtime, which are not bound to a name. These functions are usually used to fulfill simple tasks:

This is a normal (named) function.

This is a (nameless) lambda function, g is a pointer to this function.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

The lambda function10/25

● You can define functions at runtime, which are not bound to a name. These functions are usually used to fulfill simple tasks:

This is a normal (named) function.

This is a (nameless) lambda function, g is a pointer to this function.

This is the same lambda function w/o name nor function pointer. The first set of braces defines the function, the second set of braces passes the arguments.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Built-in (common) functions to be applied on sequences11/25

● You can apply several useful operations on all sequences, among those:

● len(seq):

Return the length of seq.

● filter(fn, seq):

Apply a function fn to each element of seq; fn should return a boolean; filter returns an iterator through the elements of seq for which fn is true.

● map(fn, seq):

Apply a function fn to each element of seq; fn gives a return value for each element; map returns an iterator through the elements of seq to which fn has been applied element-wise.

● reduce(fn, seq):

Apply a function to each element of seq; fn gives a rule how to combine two elements of seq; reduce returns a combination of all elements applying fn pair-wise up to the end of the sequence.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

● Task: Create a list of sorted objects that can be divided by three w/o rest class from an arbitrary input list:

12/25

Example for the built-in function filter

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

● Task: Create a list of sorted objects that can be divided by three w/o rest class from an arbitrary input list:

12/25

Example for the built-in function filter

● The function filter is used with a lambda function that returns a boolean.

● The return value of filter is an iterator through the elements in foo, for which the lambda function returns true.

● To turn these into a new list we use list comprehension.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

13/25

Example for the built-in function map

● Task: Create a dictionary from the input, with all string values in lower case:

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

13/25

Example for the built-in function map

● Task: Create a dictionary from the input, with all string values in lower case:

Iterator to the key value pairs in moo.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

13/25

Example for the built-in function map

Iterator to the key value pairs in moo.

Lambda function takes key value pair as input & returns a key value pair w/ string value in lower case.

● Task: Create a dictionary from the input, with all string values in lower case:

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

13/25

Example for the built-in function map

Iterator to the key value pairs in moo.

Lambda function takes key value pair as input & returns a key value pair w/ string value in lower case.Access actual key value

pair from iterator.

● Task: Create a dictionary from the input, with all string values in lower case:

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

13/25

Example for the built-in function map

Iterator to the key value pairs in moo.

Lambda function takes key value pair as input & returns a key value pair w/ string value in lower case.Access actual key value

pair from iterator.

● Note: This is not the most elegant way of doing this…

● Task: Create a dictionary from the input, with all string values in lower case:

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

14/25

Example for the built-in function map

● Note: This is not the most elegant way of doing this…

Thinking python: … doing a very similar thing in one line of code. Can you decipher what is being done here? Can you see the difference in output to what has been discussed before?

● Task: Create a dictionary from the input, with all string values in lower case:

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

● Task: Calculate the magnitude of a vector of any dimension, represented by a tuple.

15/25

Example for the common function reduce

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

● Task: Calculate the magnitude of a vector of any dimension, represented by a tuple.

15/25

Example for the common function reduce

Example for a lambda function w/ two arg’s.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

● Task: Calculate the magnitude of a vector of any dimension, represented by a tuple.

15/25

Example for the common function reduce

Example for a lambda function w/ two arg’s.

● The lambda function gives the rule, how to combine two elements of the sequence, pairwise. In this case the return value of reduce is a single number, to which the sequence has been reduced.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

INSTITUTE OF EXPERIMENTAL PARTICLE PHYSICS (IEKP) – PHYSICS FACULTY

Part 13:

Global vs. local variables

16/25

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Global vs. local variables17/25

● Per default function arguments are passed by value, i.e. a variable that is defined in a global scope can only be changed locally, i.e. inside a function:

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Global vs. local variables17/25

● Per default function arguments are passed by value, i.e. a variable that is defined in a global scope can only be changed locally, i.e. inside a function:

The value of each function argument is copied into x here.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Global vs. local variables17/25

● Per default function arguments are passed by value, i.e. a variable that is defined in a global scope can only be changed locally, i.e. inside a function:

The value of each function argument is copied into x here.

x changes its value to 5 here.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Global vs. local variables17/25

● Per default function arguments are passed by value, i.e. a variable that is defined in a global scope can only be changed locally, i.e. inside a function:

The value of each function argument is copied into x here.

x changes its value to 5 here.

But glob kept its initial value.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Global vs. local variables17/25

● Per default function arguments are passed by value, i.e. a variable that is defined in a global scope can only be changed locally, i.e. inside a function:

The value of each function argument is copied into x here.

x changes its value to 5 here.

But glob kept its initial value.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Global vs. local variables18/25

● Per default function arguments are passed by value, i.e. a variable that is defined in a global scope can only be changed locally, i.e. inside a function:

The value of each function argument is copied into x here.

x changes its value to 5 here.

● Local variables, which are defined in fn, will be freed and are not accessible any more after fn is left.

● Global variables are “shadowed” by local scopes, i.e. glob is not visible inside fn.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Side remark19/25

● Global variables are “shadowed” by local scopes, i.e. glob is not visible inside fn.

● The statement at the bottom does not apply to the scope of if statements, as the following example shows:

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Side remark19/25

● Global variables are “shadowed” by local scopes, i.e. glob is not visible inside fn.

j defined inside statement block of if statement.

● The statement at the bottom does not apply to the scope of if statements, as the following example shows:

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Side remark19/25

● Global variables are “shadowed” by local scopes, i.e. glob is not visible inside fn.

j defined inside statement block of if statement.

● The statement at the bottom does not apply to the scope of if statements, as the following example shows:

But still accessible outside.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Side remark19/25

● Global variables are “shadowed” by local scopes, i.e. glob is not visible inside fn.

j defined inside statement block of if statement.

● The statement at the bottom does not apply to the scope of if statements, as the following example shows:

But still accessible outside.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Side remark19/25

● Global variables are “shadowed” by local scopes, i.e. glob is not visible inside fn.

j defined inside statement block of if statement.

● The statement at the bottom does not apply to the scope of if statements, as the following example shows:

But still accessible outside.

Try the same for i=0.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

References to global variables in functions20/25

● Task: Try to access/modify a global variable inside a function:

Trial-1: – the naive approach –

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

References to global variables in functions20/25

● Task: Try to access/modify a global variable inside a function:

Trial-1: – the naive approach –

Access glob, which is defined in the scope above fn.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

References to global variables in functions20/25

● Task: Try to access/modify a global variable inside a function:

Trial-1: – the naive approach –

Access glob, which is defined in the scope above fn.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

References to global variables in functions21/25

● Task: Try to access/modify a global variable inside a function:

Trial-2: – pass as function argument –

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

References to global variables in functions21/25

● Task: Try to access/modify a global variable inside a function:

Pass as function argument here.

Trial-2: – pass as function argument –

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

References to global variables in functions21/25

● Task: Try to access/modify a global variable inside a function:

Pass as function argument here.

Trial-2: – pass as function argument –

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

References to global variables in functions22/25

● Task: Try to access/modify a global variable inside a function:

Trial-3: – using the global declaration –

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

References to global variables in functions22/25

● Task: Try to access/modify a global variable inside a function:

Make glob known as global variable inside fn using the key word global.

Trial-3: – using the global declaration –

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

References to global variables in functions22/25

● Task: Try to access/modify a global variable inside a function:

Make glob known as global variable inside fn using the key word global.

Trial-3: – using the global declaration –

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

References to global variables in functions22/25

● Task: Try to access/modify a global variable inside a function:

Make glob known as global variable inside fn using the key word global.

Trial-3: – using the global declaration –

● Note: you can declare more than one global variable with one global statement, e.g.: global x,y,z.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

References to global variables in functions23/25

● Task: Try to access/modify a global variable inside a function:

Change glob upon return value of fn.

Trial-4: – and don’t forget the obvious –

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

A word on the global declaration24/25

● If you can copy variables into function arguments and back via return values, what do you need the global declaration for at all?

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

A word on the global declaration24/25

● If you can copy variables into function arguments and back via return values, what do you need the global declaration for at all?

● Imagine glob being not a simple number, but a many GB huge object that cannot be copied around w/o blocking your active memory. In this case you cannot pass glob as argument, but you have to manipulate it itself. In this situation the global statement becomes vital for you.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni-karlsruhe.de/~rwolf/

Summary25/25

● Part 11: The python function.

● Part 12: Lambda functions.

● Part 13: Global vs. local variables.

Recommended