Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We have seen in that functions basically *do what you expect*, and in\n",
"particular the variables *inside* the function are seperate from those\n",
"in the program. This is true for the basic build-in types (, , and ),\n",
"but you have to be *very careful* when you pass s into functions.\n",
"\n",
"Consider what happend in the following code where the function sets a\n",
"given with random numbers.\n",
"\n",
"def set_random_list(lst): \"\"\" Function to set a list full of random\n",
"numbers. \"\"\" for i in range(0,len(lst)): lst\\[i\\] = random.random()\n",
"\n",
"def main(): xdata = \\[0.0\\]\\*100 set_random_list(xdata)\n",
"\n",
"main()\n",
"\n",
"Now consider what happens,\n",
"\n",
"- in the program we create a list of 100 s, all set to zero,\n",
"\n",
"- then this is passed to the function the is sent to the function,\n",
"\n",
"- inside the function the data *held* in the is the same as the data\n",
" in the , so if you change the values of the elements of the list\n",
" inside then they *will* change in .\n",
"\n",
"- in , after the call to the *elements* of the list will be set to\n",
" random numbers.\n",
"\n",
"This operation of functions *is* typically what you want to happen, but\n",
"you have to be very careful that you really intend to modify the\n",
"contents of a list inside the function.\n",
"\n",
"The way that numbers operate need a bit of through on how they work, if\n",
"you have a function as below that a ,\n",
"\n",
"def complex_value_compare( a , b): if a.real \\> b.real and a.imag \\>\n",
"b.imag: return a + b else: return a - b\n",
"\n",
"then this will work exactly as you expect and you can *read* the real\n",
"and imaginary parts of the arguments with the and syntax. *BUT* beacuse\n",
"of the way the number is passed you are not able to write to the real\n",
"and imaginary parts by this route, this means that althought a complex\n",
"number looks like a of two numbers, it cannot be changed inside a\n",
"function.\n",
"\n",
"webonly\n",
"\n",
"The There is a variant on the list called a which holds multiple\n",
"elements just like a , is indexed by the same syntax for read *but*\n",
"cannot be wrtten to, so its values are *fixed*. This is not frequently\n",
"used in normal *user* programs, but is used inside complex libraries to\n",
"implement constants.\n",
"\n",
"You have now completed sufficient to attempt which is the last\n",
"checkpoint of the course."
]
}
],
"nbformat": 4,
"nbformat_minor": 5,
"metadata": {}
}