Vous avez reçu un message "Your GitLab account has been locked ..." ? Pas d'inquiétude : lisez cet article https://docs.gricad-pages.univ-grenoble-alpes.fr/help/unlock/

pres03_functions.ipynb 31.2 KB
Newer Older
paugier's avatar
paugier committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# Python training UGA 2017\n",
    "\n",
    "**A training to acquire strong basis in Python to use it efficiently**\n",
    "\n",
15
    "Pierre Augier (LEGI), Cyrille Bonamy (LEGI), Eric Maldonado (Irstea), Franck Thollard (ISTerre), Christophe Picard (LJK), Loïc Huder (ISTerre)\n",
paugier's avatar
paugier committed
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
    "\n",
    "# Functions\n",
    "\n",
    "A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code \n",
    "reusing."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Simple function definitions and calls\n",
    "\n",
    "Function blocks begin with the keyword `def` followed by the function name and parentheses (`()`).\n",
    "\n",
    "- The code block within every function starts with a colon (:) and is indented.\n",
    "- Any input parameters or arguments should be placed within these parentheses."
   ]
  },
  {
   "cell_type": "code",
41
   "execution_count": 2,
paugier's avatar
paugier committed
42
   "metadata": {},
paugier's avatar
paugier committed
43
44
45
46
47
48
49
50
51
52
53
54
55
56
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello\n",
      "hello\n",
      "I print First call of myprint\n",
      "I print Second call of myprint\n"
     ]
    }
   ],
   "source": [
    "def print_hello():\n",
57
    "    \"hello printer\"\n",
paugier's avatar
paugier committed
58
59
60
    "    print('hello')\n",
    "\n",
    "def myprint(s):\n",
61
    "    \"my hello printer\"\n",
paugier's avatar
paugier committed
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
    "    print('I print', s)\n",
    "    \n",
    "# function calls\n",
    "print_hello()\n",
    "print_hello()\n",
    "myprint('First call of myprint')\n",
    "myprint('Second call of myprint')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "## Simple function definitions and calls\n",
    "\n",
    "- The first statement of a function can be the documentation string of the function, also called \"docstring\".\n",
82
83
84
    "- The statement `return [expression]` exits a function, optionally passing back an expression to the caller. No return statement or a return statement with no arguments is the same as `return None`.\n",
    "\n",
    "(Note: Wikipedia about duck typing: https://fr.wikipedia.org/wiki/Duck_typing)\n"
paugier's avatar
paugier committed
85
86
87
88
   ]
  },
  {
   "cell_type": "code",
89
90
   "execution_count": 8,
   "metadata": {},
Franck Thollard's avatar
Franck Thollard committed
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "test_add (__main__.TestMyStuff0)\n",
      "test max_temp computes correctly ... "
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "result =  5\n",
      "result =  aabb\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "ok\n",
      "\n",
      "----------------------------------------------------------------------\n",
      "Ran 1 test in 0.004s\n",
      "\n",
      "OK\n"
     ]
    }
   ],
paugier's avatar
paugier committed
121
   "source": [
Franck Thollard's avatar
Franck Thollard committed
122
123
    "import unittest\n",
    "\n",
paugier's avatar
paugier committed
124
125
126
127
    "def add(arg0, arg1):\n",
    "    \"\"\"Print and return the sum of the two arguments (duck typing).\"\"\"\n",
    "    result = arg0 + arg1\n",
    "    print('result = ', result)\n",
Franck Thollard's avatar
Franck Thollard committed
128
129
130
131
132
133
134
135
136
137
    "    return result\n",
    "\n",
    "\n",
    "class TestMyStuff(unittest.TestCase):    \n",
    "    def test_add(self):\n",
    "        \"\"\" test max_temp computes correctly\"\"\"\n",
    "        self.assertEqual(8, add(3, 5))\n",
    "        self.assertEqual(\"aabb\", add(\"aa\", \"bb\"))\n",
    "\n",
    "_res = unittest.TextTestRunner(verbosity=2).run(unittest.TestLoader().loadTestsFromTestCase(TestMyStuff0))"
paugier's avatar
paugier committed
138
139
140
141
142
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
paugier's avatar
paugier committed
143
   "metadata": {},
paugier's avatar
paugier committed
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "result =  5\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "5"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "add(2, 3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
paugier's avatar
paugier committed
170
   "metadata": {},
paugier's avatar
paugier committed
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "result =  ab\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'ab'"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "add('a', 'b')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### Do it yourself: simple function definition\n",
    "\n",
    "Write a function that returns the sum of the first argument with twice the second argument."
   ]
  },
Franck Thollard's avatar
Franck Thollard committed
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "test_add_second_twice (__main__.TestMyStuff0)\n",
      "test max_temp computes correctly ... "
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "arg0 + 2*arg1 = 3 + 2*5 = 13\n",
      "arg0 + 2*arg1 = aa + 2*bb = aabbbb\n",
      "arg0 + 2*arg1 = [1, 2] + 2*[3, 4] = [1, 2, 3, 4, 3, 4]\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "ok\n",
      "\n",
      "----------------------------------------------------------------------\n",
      "Ran 1 test in 0.003s\n",
      "\n",
      "OK\n"
     ]
    }
   ],
   "source": [
    "import unittest\n",
    "\n",
    "def add_second_twice(arg0, arg1):\n",
    "    \"\"\"Return the sum of the first argument with twice the second one.\n",
    "        Arguments should be of type that support sum and product by \n",
    "        an integer (e.g. numerical, string, list, ...)\n",
    "        :param arg0: first argument\n",
    "        :param arg1: second argument \n",
    "        :return: arg0 + 2 * arg1\n",
    "    \"\"\"\n",
    "    pass\n",
    "\n",
    "\n",
    "class TestMyStuff0(unittest.TestCase):    \n",
    "    def test_add_second_twice(self):\n",
    "        \"\"\" test max_temp computes correctly\"\"\"\n",
    "        self.assertEqual(13, add_second_twice(3, 5))\n",
    "        self.assertEqual(\"aabbbb\", add_second_twice(\"aa\", \"bb\"))\n",
    "        self.assertListEqual([1, 2, 3, 4, 3, 4], add_second_twice([1, 2], [3, 4])) \n",
    "        \n",
    "_res = unittest.TextTestRunner(verbosity=2).run(unittest.TestLoader().loadTestsFromTestCase(TestMyStuff0))"
   ]
  },
paugier's avatar
paugier committed
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### Do it yourself: simple function definition\n",
    "\n",
    "**A solution:**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "slideshow": {
     "slide_type": "-"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "arg0 + 2*arg1 = 4 + 2*6 = 16\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "16"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
Franck Thollard's avatar
Franck Thollard committed
307
308
309
310
311
312
313
314
    "def add_second_twice(arg0, arg1):\n",
    "    \"\"\"Return the sum of the first argument with twice the second one.\n",
    "        Arguments should be of type that support sum and product by \n",
    "        an integer (e.g. numerical, string, list, ...)\n",
    "        :param arg0: first argument\n",
    "        :param arg1: second argument \n",
    "        :return: arg0 + 2 * arg1\n",
    "    \"\"\"\n",
paugier's avatar
paugier committed
315
    "    result = arg0 + 2*arg1\n",
paugier's avatar
paugier committed
316
    "    print(f'arg0 + 2*arg1 = {arg0} + 2*{arg1} = {result}')\n",
paugier's avatar
paugier committed
317
318
319
320
321
322
323
324
    "    return result\n",
    "\n",
    "myfunc(4, 6)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
paugier's avatar
paugier committed
325
   "metadata": {},
paugier's avatar
paugier committed
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "arg0 + 2*arg1 = a + 2*b = abb\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'abb'"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "myfunc('a', 'b')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## All Python functions return exactly one object but... `None` and `tuple`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
paugier's avatar
paugier committed
363
   "metadata": {},
paugier's avatar
paugier committed
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "NoneType"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(print())"
   ]
  },
  {
   "cell_type": "code",
paugier's avatar
paugier committed
389
   "execution_count": 8,
paugier's avatar
paugier committed
390
   "metadata": {},
paugier's avatar
paugier committed
391
392
393
394
395
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
396
      "(1, 'hello', 3)\n"
paugier's avatar
paugier committed
397
398
399
400
401
402
403
     ]
    }
   ],
   "source": [
    "def return_a_tuple():\n",
    "    return 1, 'hello', 3  # a tuple, same as (1, 'hello', 3)\n",
    "\n",
404
405
406
407
408
409
    "my_tuple = return_a_tuple()\n",
    "print(my_tuple)"
   ]
  },
  {
   "cell_type": "code",
paugier's avatar
paugier committed
410
   "execution_count": 9,
411
412
413
414
415
416
417
418
419
420
421
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello\n"
     ]
    }
   ],
   "source": [
paugier's avatar
paugier committed
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
    "a, b, c = return_a_tuple()\n",
    "print(b)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Function call: namespaces and objects \"passed by references\"\n",
    "\n",
    "For each function call:\n",
    "\n",
    "- a **new namespace** is created (as at the beginning of a module) \n",
    "- the objects are **\"passed by references\"**: new names of the arguments are created in the function namespace and they point towards the objects given as arguments to the function (so it is possible to modify the mutable objects)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "## Function call: objects \"passed by references\"\n",
    "\n",
    "Exercice: use 2 schemes \"namespaces-objects\" to understand these 2 pieces of code. "
   ]
  },
  {
   "cell_type": "code",
paugier's avatar
paugier committed
457
   "execution_count": 10,
paugier's avatar
paugier committed
458
   "metadata": {},
paugier's avatar
paugier committed
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[4] 2\n"
     ]
    }
   ],
   "source": [
    "number = 2\n",
    "mylist = []\n",
    "\n",
    "def my_strange_append_square(l, n):\n",
    "    # new function namespace with names \"l\" and \"n\"\n",
    "    n = n**2\n",
    "    l.append(n)\n",
    "\n",
    "my_strange_append_square(mylist, number)\n",
    "print(mylist, number)"
   ]
  },
  {
   "cell_type": "code",
Franck Thollard's avatar
Franck Thollard committed
483
   "execution_count": 5,
paugier's avatar
paugier committed
484
   "metadata": {},
paugier's avatar
paugier committed
485
486
487
488
489
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
Franck Thollard's avatar
Franck Thollard committed
490
491
      "das f [17, 4]\n",
      "[17] 2\n"
paugier's avatar
paugier committed
492
493
494
495
496
     ]
    }
   ],
   "source": [
    "number = 2\n",
Franck Thollard's avatar
Franck Thollard committed
497
    "mylist = [17]\n",
paugier's avatar
paugier committed
498
499
500
501
    "\n",
    "def my_strange_append_square(mylist, number):\n",
    "    # new function namespace with names \"mylist\" and \"number\"\n",
    "    number = number**2\n",
Franck Thollard's avatar
Franck Thollard committed
502
503
    "    mylist.append( number)\n",
    "    print(\"das f\", mylist)\n",
paugier's avatar
paugier committed
504
    "    \n",
Franck Thollard's avatar
Franck Thollard committed
505
    "my_strange_append_square(mylist[:], number)\n",
paugier's avatar
paugier committed
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
    "print(mylist, number)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "## Global vs Local variables\n",
    "\n",
    "Variables that are defined inside a function body have a local scope (i.e. are defined in the function namespace), and those defined outside have a global scope.\n",
    "\n",
    "This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the module by all functions."
   ]
  },
  {
   "cell_type": "code",
paugier's avatar
paugier committed
526
   "execution_count": 12,
paugier's avatar
paugier committed
527
   "metadata": {},
paugier's avatar
paugier committed
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Inside the function local result:\t 20\n",
      "Outside the function global result:\t 0\n"
     ]
    }
   ],
   "source": [
    "# global variables\n",
    "result = 0\n",
    "multiplicator = 2\n",
    "\n",
    "def multiply(arg0):\n",
    "    # here we create a new name `result` in the function namespace\n",
    "    # `result` is a local variable\n",
    "    # we can use the global variable `multiplicator`\n",
    "    result = multiplicator * arg0\n",
    "    print('Inside the function local result:\\t', result)\n",
    "    return result\n",
    "\n",
    "multiply(10)\n",
    "print('Outside the function global result:\\t', result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- Global variables can be used in a function.\n",
    "- Global variables can not be modified in a function (except with the `global` keyword. Discourage!)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "## Global vs Local variables: `global` keyword\n",
    "\n",
    "There is a keyword `global` to define inside a function a global variable and to modify a global variable in the function. **It is often a bad idea to use it :-)**"
   ]
  },
  {
   "cell_type": "code",
paugier's avatar
paugier committed
578
   "execution_count": 13,
paugier's avatar
paugier committed
579
   "metadata": {},
paugier's avatar
paugier committed
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "global variable locally defined\n",
      "global variable locally defined\n"
     ]
    }
   ],
   "source": [
    "def func():\n",
    "    global me\n",
    "    # Defined locally but declared as global\n",
    "    me = 'global variable locally defined'\n",
    "    print(me)\n",
    "\n",
    "func()\n",
    "# Ask for a global variable\n",
    "print(me)"
   ]
  },
  {
   "cell_type": "code",
paugier's avatar
paugier committed
604
   "execution_count": 14,
paugier's avatar
paugier committed
605
   "metadata": {},
paugier's avatar
paugier committed
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1, 2, 3, 4, "
     ]
    }
   ],
   "source": [
    "delta = 0\n",
    "\n",
    "def add_1_to_delta():\n",
    "    global delta\n",
    "    # global variable modified in a function\n",
    "    delta += 1\n",
    "\n",
    "for i in range(4):\n",
    "    add_1_to_delta()\n",
    "    print(delta, end=', ')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Function Arguments\n",
    "\n",
    "You can call a function by using the following types of formal arguments:\n",
    "\n",
    " - Required arguments\n",
    " - Keyword arguments\n",
    " - Default arguments\n",
    " - Variable-length arguments"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### Required arguments\n",
    "\n",
    "Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition."
   ]
  },
  {
   "cell_type": "code",
Franck Thollard's avatar
Franck Thollard committed
661
   "execution_count": 7,
paugier's avatar
paugier committed
662
   "metadata": {},
paugier's avatar
paugier committed
663
664
665
666
667
668
669
670
671
672
673
674
675
676
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "arg0 + 2*arg1 = 4 + 2*6 = 16\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "16"
      ]
     },
Franck Thollard's avatar
Franck Thollard committed
677
     "execution_count": 7,
paugier's avatar
paugier committed
678
679
680
681
682
683
684
685
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def myfunc(arg0, arg1):\n",
    "    \"Return the sum of the first argument with twice the second one.\"\n",
    "    result = arg0 + 2*arg1\n",
paugier's avatar
paugier committed
686
    "    print(f'arg0 + 2*arg1 = {arg0} + 2*{arg1} = {result}')\n",
paugier's avatar
paugier committed
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
    "    return result\n",
    "\n",
    "myfunc(4, 6)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "-"
    }
   },
   "source": [
    "To call the function `myfunc`, you definitely need to pass two arguments, otherwise it gives a syntax error."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### Keyword arguments\n",
    "\n",
    "Keyword arguments are related to the function calls. When you use keyword arguments in a function call, Python identifies the arguments by the parameter name."
   ]
  },
  {
   "cell_type": "code",
paugier's avatar
paugier committed
718
   "execution_count": 16,
paugier's avatar
paugier committed
719
   "metadata": {},
paugier's avatar
paugier committed
720
721
722
723
724
725
726
727
728
729
730
731
732
733
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "arg0 + 2*arg1 = 2 + 2*3 = 8\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "8"
      ]
     },
paugier's avatar
paugier committed
734
     "execution_count": 16,
paugier's avatar
paugier committed
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "myfunc(arg1=3, arg0=2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### Default arguments\n",
    "\n",
    "A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument."
   ]
  },
  {
   "cell_type": "code",
Franck Thollard's avatar
Franck Thollard committed
758
   "execution_count": 12,
paugier's avatar
paugier committed
759
   "metadata": {},
paugier's avatar
paugier committed
760
761
762
763
764
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
Franck Thollard's avatar
Franck Thollard committed
765
      "arg0 + 2*arg1 = a + 2*n = ann\n"
paugier's avatar
paugier committed
766
767
768
769
     ]
    }
   ],
   "source": [
Franck Thollard's avatar
Franck Thollard committed
770
    "def myfunc1(arg0, arg1=None):\n",
paugier's avatar
paugier committed
771
    "    \"Return the sum of the first argument with twice the second one.\"\n",
Franck Thollard's avatar
Franck Thollard committed
772
773
774
775
776
    "    if arg1 is None:\n",
    "        if type(arg0) == int:\n",
    "            arg1 = 0\n",
    "        else:\n",
    "            arg1 = \"\"\n",
paugier's avatar
paugier committed
777
778
    "    myfunc(arg0, arg1)\n",
    "\n",
Franck Thollard's avatar
Franck Thollard committed
779
    "myfunc1(\"a\", \"n\")"
paugier's avatar
paugier committed
780
781
782
783
   ]
  },
  {
   "cell_type": "code",
paugier's avatar
paugier committed
784
   "execution_count": 18,
paugier's avatar
paugier committed
785
   "metadata": {},
paugier's avatar
paugier committed
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "arg0 + 2*arg1 = 1 + 2*3 = 7\n"
     ]
    }
   ],
   "source": [
    "myfunc1(1, 3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### Default arguments\n",
    "\n",
    "**Warning:** the default arguments are created only once, at the function definition! They are stored in a tuple associated with the function object."
   ]
  },
  {
   "cell_type": "code",
Franck Thollard's avatar
Franck Thollard committed
814
   "execution_count": 15,
paugier's avatar
paugier committed
815
   "metadata": {},
paugier's avatar
paugier committed
816
817
   "outputs": [
    {
Franck Thollard's avatar
Franck Thollard committed
818
819
820
821
822
823
824
825
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1]\n",
      "[1, 1]\n",
      "[1, 1, 1]\n",
      "[1, 1, 1, 1]\n"
     ]
paugier's avatar
paugier committed
826
827
828
829
830
831
832
    }
   ],
   "source": [
    "def do_not_use_mutable_object_for_default_arg(l=[]):\n",
    "    l.append(1)\n",
    "    print(l)\n",
    "\n",
Franck Thollard's avatar
Franck Thollard committed
833
834
835
836
    "do_not_use_mutable_object_for_default_arg()\n",
    "do_not_use_mutable_object_for_default_arg()\n",
    "do_not_use_mutable_object_for_default_arg()\n",
    "do_not_use_mutable_object_for_default_arg()"
paugier's avatar
paugier committed
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Exercice:** what will be the result of 3 calls of this function? Use a namespaces-objects diagram!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### Default arguments\n",
    "\n",
    "**Warning:** the default arguments are created only once, at the function definition! They are stored in a tuple associated with the function object."
   ]
  },
  {
   "cell_type": "code",
paugier's avatar
paugier committed
861
   "execution_count": 20,
paugier's avatar
paugier committed
862
863
864
865
866
867
868
869
870
871
872
873
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def do_not_use_mutable_object_for_default_arg(l=[]):\n",
    "    l.append(1)\n",
    "    print(l)"
   ]
  },
  {
   "cell_type": "code",
paugier's avatar
paugier committed
874
   "execution_count": 21,
paugier's avatar
paugier committed
875
   "metadata": {},
paugier's avatar
paugier committed
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1]\n",
      "[1, 1]\n",
      "[1, 1, 1]\n"
     ]
    }
   ],
   "source": [
    "do_not_use_mutable_object_for_default_arg()\n",
    "do_not_use_mutable_object_for_default_arg()\n",
    "do_not_use_mutable_object_for_default_arg()"
   ]
  },
  {
   "cell_type": "code",
Franck Thollard's avatar
Franck Thollard committed
895
   "execution_count": 16,
paugier's avatar
paugier committed
896
   "metadata": {},
paugier's avatar
paugier committed
897
898
899
900
901
902
903
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1]\n",
      "[1]\n",
Franck Thollard's avatar
Franck Thollard committed
904
905
      "[1]\n",
      "[1, 2, 3, 1]\n"
paugier's avatar
paugier committed
906
     ]
Franck Thollard's avatar
Franck Thollard committed
907
908
909
910
911
912
913
914
915
916
    },
    {
     "data": {
      "text/plain": [
       "[1, 2, 3, 1]"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
paugier's avatar
paugier committed
917
918
919
920
921
922
923
924
925
926
927
    }
   ],
   "source": [
    "def how_to_use_list_as_default_arg(l=None):\n",
    "    if l is None:\n",
    "        l = []\n",
    "    l.append(1)\n",
    "    print(l)\n",
    "\n",
    "how_to_use_list_as_default_arg()\n",
    "how_to_use_list_as_default_arg()\n",
Franck Thollard's avatar
Franck Thollard committed
928
929
930
931
    "how_to_use_list_as_default_arg()\n",
    "l1 = [1,2,3]\n",
    "how_to_use_list_as_default_arg(l1)\n",
    "l1"
paugier's avatar
paugier committed
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### Variable-length arguments\n",
    "\n",
    "You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments.\n",
    "\n",
    "An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable arguments."
   ]
  },
  {
   "cell_type": "code",
paugier's avatar
paugier committed
951
   "execution_count": 23,
paugier's avatar
paugier committed
952
   "metadata": {},
paugier's avatar
paugier committed
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "args = ()\n",
      "totalsum = 0\n",
      "args = (4,)\n",
      "totalsum = 4\n",
      "args = (4, 3, 4, 7)\n",
      "totalsum = 18\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "18"
      ]
     },
paugier's avatar
paugier committed
972
     "execution_count": 23,
paugier's avatar
paugier committed
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def sum_args(*args):\n",
    "    \"\"\"Return the sum of numbers.\"\"\"\n",
    "    totalsum = 0\n",
    "    print('args =', args)\n",
    "    for var in args:\n",
    "        totalsum += var\n",
    "    print('totalsum =', totalsum)\n",
    "    return totalsum\n",
    "\n",
    "sum_args()\n",
    "sum_args(4)\n",
    "sum_args(4, 3, 4, 7)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### Variable-length arguments\n",
    "\n",
    "There is also a (very useful) syntax with two asterisks `**`, which works like this:"
   ]
  },
  {
   "cell_type": "code",
Franck Thollard's avatar
Franck Thollard committed
1007
   "execution_count": 19,
paugier's avatar
paugier committed
1008
   "metadata": {},
paugier's avatar
paugier committed
1009
1010
1011
1012
1013
1014
1015
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "call:\n",
      "\ta = 1\n",
Franck Thollard's avatar
Franck Thollard committed
1016
      "\targs = (3,)\n",
1017
      "\tkwargs = {'toto': 3, 'titi': 3}\n",
paugier's avatar
paugier committed
1018
1019
      "call:\n",
      "\ta = a\n",
Franck Thollard's avatar
Franck Thollard committed
1020
      "\targs = ()\n",
1021
      "\tkwargs = {'bob': 3}\n"
paugier's avatar
paugier committed
1022
1023
1024
1025
     ]
    }
   ],
   "source": [
Franck Thollard's avatar
Franck Thollard committed
1026
    "def func(a, b, *args, **kwargs):\n",
paugier's avatar
paugier committed
1027
    "    print(f'call:\\n\\ta = {a}\\n\\targs = {args}\\n\\tkwargs = {kwargs}')\n",
paugier's avatar
paugier committed
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
    "    \n",
    "func(1, 2, 3, toto=3, titi=3)\n",
    "func('a', 'b', bob=3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "### Do it yourself\n",
    "\n",
    "Write a function that takes as input a list `l` and a number `a` and that multiplies\n",
    "all the elements of the list by the number. If not set, number is defaulted to 2."
   ]
  },
Franck Thollard's avatar
Franck Thollard committed
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "test_mult_list_int_defaut (__main__.TestMyStuff0) ... FAIL\n",
      "test_mult_list_int_with_factor (__main__.TestMyStuff0) ... FAIL\n",
      "test_mult_list_str_with_factor (__main__.TestMyStuff0) ... FAIL\n",
      "\n",
      "======================================================================\n",
      "FAIL: test_mult_list_int_defaut (__main__.TestMyStuff0)\n",
      "----------------------------------------------------------------------\n",
      "Traceback (most recent call last):\n",
      "  File \"<ipython-input-23-4858bef3312c>\", line 14, in test_mult_list_int_defaut\n",
      "    self.assertListEqual(l_target, l)\n",
      "AssertionError: Lists differ: [2, 6, 10] != [1, 3, 5]\n",
      "\n",
      "First differing element 0:\n",
      "2\n",
      "1\n",
      "\n",
      "- [2, 6, 10]\n",
      "+ [1, 3, 5]\n",
      "\n",
      "======================================================================\n",
      "FAIL: test_mult_list_int_with_factor (__main__.TestMyStuff0)\n",
      "----------------------------------------------------------------------\n",
      "Traceback (most recent call last):\n",
      "  File \"<ipython-input-23-4858bef3312c>\", line 8, in test_mult_list_int_with_factor\n",
      "    self.assertListEqual(l_target, l)\n",
      "AssertionError: Lists differ: [2, 6, 10] != [1, 3, 5]\n",
      "\n",
      "First differing element 0:\n",
      "2\n",
      "1\n",
      "\n",
      "- [2, 6, 10]\n",
      "+ [1, 3, 5]\n",
      "\n",
      "======================================================================\n",
      "FAIL: test_mult_list_str_with_factor (__main__.TestMyStuff0)\n",
      "----------------------------------------------------------------------\n",
      "Traceback (most recent call last):\n",
      "  File \"<ipython-input-23-4858bef3312c>\", line 20, in test_mult_list_str_with_factor\n",
      "    self.assertListEqual(l_target, l)\n",
      "AssertionError: Lists differ: ['aa', 'bb', 'cc'] != ['a', 'b', 'c']\n",
      "\n",
      "First differing element 0:\n",
      "'aa'\n",
      "'a'\n",
      "\n",
      "- ['aa', 'bb', 'cc']\n",
      "?    -    -     -\n",
      "\n",
      "+ ['a', 'b', 'c']\n",
      "\n",
      "----------------------------------------------------------------------\n",
      "Ran 3 tests in 0.007s\n",
      "\n",
      "FAILED (failures=3)\n"
     ]
    }
   ],
   "source": [
    "import unittest\n",
    "\n",
    "class TestMyStuff0(unittest.TestCase):    \n",
    "    def test_mult_list_int_with_factor(self):\n",
    "        l = [1, 3, 5]\n",
    "        l_target = [2, 6, 10]\n",
    "        mult_list(l, 2)\n",
    "        self.assertListEqual(l_target, l)\n",
    "        \n",
    "    def test_mult_list_int_defaut(self):\n",
    "        l = [1, 3, 5]\n",
    "        l_target = [2, 6, 10]\n",
    "        mult_list(l, 2)\n",
    "        self.assertListEqual(l_target, l)\n",
    "        \n",
    "    def test_mult_list_str_with_factor(self):\n",
    "        l = [\"a\", \"b\", \"c\"]\n",
    "        l_target = [\"aa\", \"bb\", \"cc\"]\n",
    "        mult_list(l, 2)\n",
    "        self.assertListEqual(l_target, l)\n",
    "\n",
    "def mult_list(my_list, factor):\n",
    "    \"Multiply each element of my_list by factor (default=2)\"\n",
    "    pass\n",
    "\n",
    "\n",
    "_res = unittest.TextTestRunner(verbosity=2).run(unittest.TestLoader().loadTestsFromTestCase(TestMyStuff0))"
   ]
  },
paugier's avatar
paugier committed
1144
1145
1146
1147
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
paugier's avatar
paugier committed
1148
     "slide_type": "fragment"
paugier's avatar
paugier committed
1149
1150
1151
    }
   },
   "source": [
paugier's avatar
paugier committed
1152
    "#### A possible solution:"
paugier's avatar
paugier committed
1153
1154
1155
1156
   ]
  },
  {
   "cell_type": "code",
Franck Thollard's avatar
Franck Thollard committed
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0, 1, 2]\n",
      "[0, 2, 4]\n",
      "[0, 8, 16]\n",
      "['aaaa', 'bbbb']\n"
     ]
    }
   ],
paugier's avatar
paugier committed
1171
1172
1173
   "source": [
    "def func(l, a=2):\n",
    "    for i, val in enumerate(l):\n",
Franck Thollard's avatar
Franck Thollard committed
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
    "        l[i] = a * val\n",
    "        \n",
    "l = list(range(3))\n",
    "print(l)\n",
    "func(l)\n",
    "print(l)\n",
    "func(l, 4)\n",
    "print(l)\n",
    "l = ['a', 'b']\n",
    "func(l, 4)\n",
    "print(l)\n"
paugier's avatar
paugier committed
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## `lambda` keyword and anonymous functions\n",
    "\n",
    "These functions are called anonymous because they are not declared by using the `def` keyword but with the `lambda` keyword so they have not name.\n",
    "\n",
    "- Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.\n",
    "- Lambda form is used in functional programming (but it is usually better to use list comprehension) and for [callbacks in GUI](https://pythonconquerstheuniverse.wordpress.com/2011/08/29/lambda_tutorial/)."
   ]
  },
  {
   "cell_type": "code",
paugier's avatar
paugier committed
1205
   "execution_count": 26,
paugier's avatar
paugier committed
1206
   "metadata": {},
paugier's avatar
paugier committed
1207
1208
1209
1210
1211
1212
1213
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3"
      ]
     },
paugier's avatar
paugier committed
1214
     "execution_count": 26,
paugier's avatar
paugier committed
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "f = lambda x, y: x + y\n",
    "f(1, 2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Example of the builtin function `print`\n",
    "\n",
    "```text\n",
    "In [1]: print?\n",
    "Docstring:\n",
    "print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n",
    "\n",
    "Prints the values to a stream, or to sys.stdout by default.\n",
    "Optional keyword arguments:\n",
    "file:  a file-like object (stream); defaults to the current sys.stdout.\n",
    "sep:   string inserted between values, default a space.\n",
    "end:   string appended after the last value, default a newline.\n",
    "flush: whether to forcibly flush the stream.\n",
    "Type:      builtin_function_or_method\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
paugier's avatar
paugier committed
1251
   "execution_count": 27,
paugier's avatar
paugier committed
1252
   "metadata": {},
paugier's avatar
paugier committed
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello Eric\n"
     ]
    }
   ],
   "source": [
    "print('hello', 'Eric')"
   ]
  },
  {
   "cell_type": "code",
paugier's avatar
paugier committed
1268
   "execution_count": 28,
paugier's avatar
paugier committed
1269
   "metadata": {},
paugier's avatar
paugier committed
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello_Eric.\n"
     ]
    }
   ],
   "source": [
    "print('hello', 'Eric', sep='_', end='')\n",
    "print('.')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
paugier's avatar
paugier committed
1292
    "## Input from Keyboard (builtin function `input`)"
paugier's avatar
paugier committed
1293
1294
1295
1296
   ]
  },
  {
   "cell_type": "code",
paugier's avatar
paugier committed
1297
   "execution_count": 29,
paugier's avatar
paugier committed
1298
1299
1300
1301
1302
1303
   "metadata": {
    "slideshow": {
     "slide_type": "-"
    }
   },
   "outputs": [
paugier's avatar
paugier committed
1304
1305
1306
1307
1308
1309
1310
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "what's your name ? eric\n"
     ]
    },
paugier's avatar
paugier committed
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "your name is  eric\n"
     ]
    }
   ],
   "source": [
    "answer = input(\"what's your name ?\")\n",
    "print(\"your name is \", answer)"
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Slideshow",
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
Franck Thollard's avatar
Franck Thollard committed
1342
   "version": "3.7.3rc1"
paugier's avatar
paugier committed
1343
1344
1345
1346
1347
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}