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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
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
170
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
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Additional Programming Concepts in Python\n",
"\n",
"In this notebook, you will learn about additional programming concepts in Python. They are not part of the learning objectives of the course, but you may run into them at some point, or wonder what they are, or find them fun and useful if you already have some programming experience. \n",
"\n",
"*(Much of this material we wrote up in an earlier version of the notebooks, but then moved here when we tweaked the course to fit in the time we have available.)*\n",
"\n",
"## Tuples\n",
"\n",
"### What is a tuple?\n",
"\n",
"The first more complicated data structure we will discuss is a `tuple`. A tuple is a collection of values inside curved brackets. Here is the basic syntax for making a tuple: \n",
"\n",
"```\n",
"my_tuple = (a, b, c, ...etc...)\n",
"```\n",
"\n",
"As a concrete example, this will create a tuple of three integers:"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"(5, 6, 7)\n"
]
}
],
"source": [
"tup1 = (5,6,7)\n",
"print(tup1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Like the other data types we've see, we can see the tuples we create using `%whos`:"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Variable Type Data/Info\n",
"-----------------------------\n",
"tup1 tuple n=3\n"
]
}
],
"source": [
"%whos"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Tuples are like lists, but behave a bit differently than python lists. In fact, we've already seen tuples before in the previous notebook when we were looking at `for` loops!\n",
"\n",
"If you are given a tuple, you can check how long it by using the `len()` function built into python:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"len(tup1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that tuples do not have to contain integers, they can contain any type of data:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# A tuple of strings\n",
"str_tup = ('foo', 'bar')\n",
"print(str_tup)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Different than how numpy arrays are typically used, tuples can even be mixed, with each element of a different type:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"mixed_tup = (1, 1.05, 7+3j, 'foo')\n",
"print(mixed_tup)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And you can even have tuples of tuples:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"tup_of_tup = (str_tup, mixed_tup)\n",
"print(tup_of_tup)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Tuples support all the same indexing and slicing as arrays. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Tuples can also contain other tuples! If your tuple contains another tuple, like the example `tup_of_tup`, you can use the square brackets a second time to index into the tuple you extract by the first set of square brackets:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(tup_of_tup)\n",
"print(tup_of_tup[0])\n",
"print(tup_of_tup[0][0])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Looping over tuples without using indices\n",
"\n",
"As mentioned briefly in Notebook 2, python `for` loops can also directly iterate over \"iteratable\" objects. \n",
"\n",
"The `tuple` (along with lists, which we will see in a bit, and numpy arrays, which we will see in the next notebook), is one such iteratable objecte. \n",
"\n",
"For example, to print all of entries of a `tuple` out in order, we can use directly following:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for n in tup1:\n",
" print(n)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"During each subsequent iteartion of the loop, the variable `n` will be assigned to the next item that is stored in the tuple. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Lists\n",
"\n",
201
202
203
204
205
206
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
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
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
363
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
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
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
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
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
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
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
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
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
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
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
"In this section, we will introduce a very commonly used data structure in python: the `list`. \n",
"\n",
"A list is a list of values, like a `tuple`, but that is made using square brackets:\n",
"\n",
"```\n",
"my_list = [a, b, c, ...etc...]\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"l1 = list(range(10))\n",
"l1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Like tuples, you can extract single elements of the list using indexing, and extract portions of the list using slicing:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(l1[0])\n",
"print(l1[0:5])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"OK, so far so good. But if I have `tuple`, why would I ever want a list?\n",
"\n",
"### Lists vs tupples: Tupples are \"immutable\", lists are \"mutable\"\n",
"\n",
"This is a bit of python-speak for saying that you cannot change the values of a tupple, but you can change the values of a list.\n",
"\n",
"What does this mean? It means if I have a list `[5,6,7]` and I want to change the last number in my list to an 8, I can just directly do this:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"l1 = [5,6,7]\n",
"l1[2] = 8"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If I try this with a tuple, I will find that I can't do it!"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"ename": "TypeError",
"evalue": "'tuple' object does not support item assignment",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-3-9c8e47fcf882>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[0mt1\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;33m(\u001b[0m\u001b[1;36m5\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m6\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m7\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0mt1\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m2\u001b[0m\u001b[1;33m]\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m8\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;31mTypeError\u001b[0m: 'tuple' object does not support item assignment"
]
}
],
"source": [
"t1 = (5,6,7)\n",
"t1[2] = 8"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Because of this functionality, **lists are much more powerful as we can change them once we've made them!**\n",
"\n",
"In addition to changing lists by individual indexing, we can also change whole parts of the list using slicing:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"l2 = list(range(10))\n",
"print(l2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Replace three entries by zeros\n",
"l2 = list(range(10))\n",
"l2[4:7] = [0,0,0]\n",
"print(l2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Remove entries from a list by replacing them with an empty list []\n",
"l2 = list(range(10))\n",
"l2[4:7] = [] \n",
"print(l2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Functions for manipulating lists\n",
"\n",
"In fact, our list object itself has functions built in that allow you to change it! Some examples of things we can do:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# This will add an element to the end of the list\n",
"l1.append(10)\n",
"l1"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# This will remove an element from the end of the list\n",
"l1.pop()\n",
"l1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There are many more functions built into lists, some of which you can find here:\n",
"\n",
"https://docs.python.org/3/tutorial/datastructures.html"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### The problem with lists for scientific computing\n",
"\n",
"Lists look an awful lot like numpy arrays: why don't we just use lists? \n",
"\n",
"In scientific computing, it is very common to want to perform numerical operations on <a href=https://en.wikipedia.org/wiki/Row_and_column_vectors>vectors and matrices</a> of numbers. And also, many times in experiments, the data you will take will be represented by a vector of numbers: for example, the position of a particle as a function of time.\n",
"\n",
"A vector is a collection of numbers in a one-dimentional array:\n",
"\n",
"$$\n",
"x = [1, 2, 3, 4, 5]\n",
"$$\n",
"\n",
"In Notebook 3, we already introduced python `list`s. A list is also a vector, right? It certainly looks the same! Why do we need something new? \n",
"\n",
"The reason we need something new is that python `list`s are not designed to work in the same way as we expect vectors to from our mathematics classes. For example, in math:\n",
"\n",
"$$\n",
"2x = [2,4,6,8,10]\n",
"$$\n",
"\n",
"Let's check if this works with lists"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]\n"
]
}
],
"source": [
"l = [1, 2, 3, 4, 5]\n",
"print(2*l)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This certainly does something, but it does not do what we want! It has made the list twice as long by appending two of them together!\n",
"\n",
"Also addition and subtraction doesn't work like we would expect:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(l+l)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Addition makes the list twice as long? And:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"print(l-l)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And subtraction doesn't work at all...clearly, although they look a lot like vectors, in terms of mathematics, lists do not act much like vectors. This is one of the reasons numpy arrays were created."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Dictionaries\n",
"\n",
"Another useful data type in python is a \"dictionary\":\n",
"\n",
"https://docs.python.org/3/tutorial/datastructures.html#dictionaries\n",
"\n",
"At a basic level, a dictionary is a bit like a list that supports non-numeric indices. Dictionaries can be created using the curly brackets in python `{` and `}`. \n",
"\n",
"Here we will create an empty dictionary and start filling it:"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"delft_lunch_rating = {}\n",
"delft_lunch_rating['greek olive'] = 10\n",
"delft_lunch_rating['brandmeester'] = 7\n",
"delft_lunch_rating['aula'] = \"expensive\"\n",
"delft_lunch_rating['citg'] = \"bad\"\n",
"delft_lunch_rating['doner'] = \"good but a bit salty\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This is what our dictionary looks like:"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'greek olive': 10, 'brandmeester': 7, 'aula': 'expensive', 'citg': 'bad', 'doner': 'good but a bit salty'}\n"
]
}
],
"source": [
"print(delft_lunch_rating)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"I can then look up values in my dictionary using the \"keys\":"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"scrolled": true
},
"outputs": [
{
"data": {
"text/plain": [
"'expensive'"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"delft_lunch_rating['aula']"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There are also functions for getting all the keys:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"delft_lunch_rating.keys()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"My dictionaries can also hold lists if I want:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"delft_lunch_rating[\"greek olive\"] = ['good', 10]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Dictionaries are actually a way to implement a basic database in python (I use them in my grading scripts to look up the email addresses and student numbers of a given netid...)\n",
"\n",
"And the Jupyter notebook files actually store a list cells, and each cell consist of a dictionary that contains the text of the cell (and other fun things like metadata). You can see this in action using the <a href=https://nbformat.readthedocs.io/en/latest/api.html>nbformat</a> library, you can actually load a notebook file into your python kernel and poke around it to see what it looks like. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Strings\n",
"\n",
"In notebook 1, we already saw strings as variable types. \n",
"\n",
"It turns out that strings are not just simple (immutable) variables like `int`s and `float`s: `str`s are actually data structures that are indexable (like `tuple`s and `list`s). \n",
"\n",
"Strings are immutable, which means they cannot be changed. But they do have lots of built-in functions that can return a new string (or lots of other things!). \n",
"\n",
"Let's look at an example:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"s1 = \"This is a string\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Indexing a string returns the characters of the string:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(s1[0])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can also slice:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(s1[0:6])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Strings do not allow you to directly change "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Built-in string functions\n",
"\n",
"Strings have a bunch of useful built-in functions: \n",
"\n",
"https://docs.python.org/3/library/stdtypes.html#string-methods\n",
"\n",
"some of which we will look at here:\n",
"\n",
"### Splitting a string\n",
"\n",
"Strings have a built-in function `split()`. By default, it will return a list of \"words\" by using whitespaces as the separator:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"s1.split()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Passing `.` as an argument, `split()` will use that as a separator, which is useful for working with filenames:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"input_file = 'myfile.dat'\n",
"output_file = input_file.split('.')[0]\n",
"output_file += \"_processed.dat\"\n",
"print(output_file)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Replacing parts of strings\n",
"\n",
"The function `replace()` replace substrings in your string for you:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"s2 = \"This is a long sentence. It is a good idea to end it.\"\n",
"print(s2)\n",
"print(s2.replace(\" is\", \" was\"))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that without the space, it will also replace the \"is\" in \"This\":"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(s2)\n",
"print(s2.replace(\"is\", \"was\"))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Testing for the contents of a string\n",
"\n",
"You can check if a substring is found inside a string using the `in` logical operator:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"if \"this\" in \"somewhere in this sentence\":\n",
" print(\"We found a 'this'\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# It is case sensitive:\n",
"if \"this\" in \"This is a sentence\":\n",
" print(\"This will not get printed\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# But you can use the .lower() function of a string to do case insensitive checks\n",
"s3 = \"This is a sentence\"\n",
"if \"this\" in s3.lower():\n",
" print(\"Using .lower(), s3 is converted to all lower-case:\\n\")\n",
" print(\"s3.lower = '%s'\\n\" % s3.lower())\n",
" print(\"And now we do find the substring 'this'\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here, we can also see an example of special characters in strings: a `\\n` in a string specifies a \"new line\":\n",
"\n",
"https://docs.python.org/3/reference/lexical_analysis.html#strings\n",
"\n",
"Note that if you want to print a backslash `\\`, you need to put a double backslash in your string: `\\\\`."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### String formatting\n",
"\n",
"Until now, we have been printing values of our variables using the standard `str()` conversion of numbers to strings:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = 11/300\n",
"print(\"The value of a is\", a)\n",
"\n",
"# The above print() statement is equivalent to:\n",
"\n",
"output = \"The value of a is\"\n",
"output += \" \"\n",
"output += str(a)\n",
"print(output)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"But maybe we don't want so many digits in our text output. Say I want only two digits. How can I do this? \n",
"\n",
"For this, python supports \"string formatting\". My personal preference is to work with traditional \"printf-style\" formatting, inherited from the C programming language:\n",
"\n",
"https://docs.python.org/3/library/stdtypes.html#printf-style-bytes-formatting\n",
"\n",
"It sounds a bit scary at first, but it's actually pretty easy to use. It works by using a special operator `%` that works with strings. \n",
"\n",
"To use it, you include a special text in your string that starts with `%`, followed by a sequence of numbers and letters that you use to tell python how you want the string to be formatted. \n",
"\n",
"Here are some examples:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Floating point format with 4 digits\n",
"print(\"The value of a is %.4f\" % a)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Exponential notation with two digits\n",
"print(\"The value of a is %.2e\" % a)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# A string with the formatting not at the end\n",
"print(\"The value of a is %.2e seconds\" % a)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Some additional matrix creation routines\n",
"\n",
"There are several functions for making matrices which you may find useful someday: \n",
"\n",
"https://docs.scipy.org/doc/numpy/reference/routines.array-creation.html\n",
"\n",
"including this one which I use often:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# The identity matrix\n",
"print(np.eye(10))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"# A band diagonal matrix\n",
"print(np.eye(10,k=-1))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Mutable objects and \"call by reference\"\n",
"\n",
"### The `=` operator\n",
"\n",
"Now that we have introduced some more advanced data types, it is time to go back and revisit one of our first topics: the `=` opeartor.\n",
"\n",
"At the start of the first notebook, we introduced the **assignment operator** `=`, and saw that it could be used to give new values to a variable based on the value of another variable:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = 5\n",
"b = a\n",
"print(b)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"What happens if we change the value of `a` after the statment `b = a`? For example:"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"a = 5\n",
"b = a\n",
"a = 6"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"What value does `b` have? Does it have the value of `5` that `a` had when we performed the assignment operation, or does it have `6` (the new values of `a`)? \n",
"\n",
"The obvious answer would be that `b` should have the answer `5`, right? Let's check it:"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"5\n"
]
}
],
"source": [
"a = 5\n",
"b = a\n",
"a = 6\n",
"print(b)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"OK, that seems to make sense. \n",
"\n",
"Now let's take a look at and examples with lists. We will create a list `a`, using the assignment operator to make a list variable `b = a`, and then change the values in the list `a`."
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"a = [2,1]\n",
"b = a\n",
"a[0] = 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now question: did `a[0] = 1` change the value of of `b`? Let's check:"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 1]\n"
]
}
],
"source": [
"print(b)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Changing the values of `a` also changed list `b` for some reason? **WHY!!!!?????!!! WHAT IS GOING ON?!!?**\n",
"\n",
"### \"Call by value\" and \"Call by reference\"\n",
"\n",
"To understand what is going on here, we have to understand how computer programs store variables and their values. \n",
"\n",
"When I create a variable `a` in a python by giving it a value `5`, for example, python creates a space in your computers memory where it puts the value `5` and then makes a name for that variable `a` in the kernel's list of variables that points to that spot in memory. \n",
"\n",
"For some types of objects in python, specifically \"immutable\" (\"unchangeable\") object types, when you execute the statement `b = a`, python will create a new spot in your computers memory for variable `b`, copy the value `5` into that memory spot, and then makes variable `b` point to this new spot in the kernel's list of variables. \n",
"\n",
"This procedure is called \"call by value\" in programming languages, and is illustrated here: \n",
"\n",
"<img src=\"call_by_value.png\"></img>\n",
"\n",
"For \"mutable\" objects, python uses a different concept: \"call by reference\". In call by reference, `b = a` instead does the following: it make a new variable `b` in the list of variables, and make it point to the spot in memory where variable `a` is stored, illustrated here:\n",
"\n",
"<img src=\"call_by_reference.png\"></img>\n",
"\n",
"It is now obvious why changing the values in `a` will also changes the values in `b`: it is because they point to the same data in your computers memory.\n",
"\n",
"\"Call by reference\" also holds for when you are passing variables to functions:"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[0, 2]\n"
]
}
],
"source": [
"def set_first_entry_to_zero(x):\n",
" x[0] = 0\n",
"\n",
"a = [1,2]\n",
"set_first_entry_to_zero(a)\n",
"print(a)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can see that our function changed the value of the variable mylist! This was not possible with integers for example:"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n"
]
}
],
"source": [
"def set_to_zero(x):\n",
" x = 0\n",
"\n",
"a = 1\n",
"set_to_zero(a)\n",
"print(a)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Why use \"call by reference\" at all? I find it confusing!\n",
"\n",
"You might ask: why python does this? Well, one reason is that it is that lists, and in particular numpy arrays that we will look at next, can sometime become very big, taking up 100 MB of memory or more. If python used \"call by value\" for such big things all the time, it would use up massive amounts of memory! Every function call or assignment statement would accdientally use up another 100 MB of memory! By using \"call by reference\", it can avoid accidentally filling up your computers memory every time you use the `=` operator. \n",
"\n",
"If you really want to have a *copy* of a list (or a numpy array), these objects typically have `copy()` functions built in that return instead a copy of the object, for when you really need one. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = [2,1]\n",
"b = a.copy()\n",
"print(b)\n",
"a[0] = 1\n",
"print(b)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now, `b` is unaffected by your changes to `a` because the name `b` points to a new copy of the array in memory."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Interactive plots with ipywidgets\n",
"\n",
"One of the cool things that is easy to do in Jupter notebooks is to make \"interactive\" plots. \n",
"\n",
"For example, in the projectile example above, I may want to be able to play with the angle and see how this changes my trajectory. For this, there is a very easy to use and convenient library called `ipywidgets`.\n",
"\n",
"The way it works is we make a function that generates our plot that takes the parameter we want to play with as an argument. We then call an `ipywidgets` function called `interact()`, and it will automatically make a \"live update\" plot in your web browser in which you can adjust the parameter an see how the plot changes. \n",
"\n",
"Let's look at an example:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from ipywidgets import interact\n",
"\n",
"v0 = 10 # m/s\n",
"g = 9.8 # m/s^2\n",
"\n",
"# We will allow theta to be adjusted and start it at 45 degrees\n",
"def update_plot(theta=45):\n",
" theta *= np.pi/180 # convert to radians\n",
" y = -g/(2*v0**2*np.cos(theta)**2)*x**2 + x*np.tan(theta)\n",
" plt.plot(x,y)\n",
" plt.ylim(-1,6) # Manually set the ylimits\n",
" plt.xlabel(\"Distance (m)\")\n",
" plt.ylabel(\"Height (m)\")\n",
" plt.axhline(0, ls=\":\", c=\"grey\")\n",
" plt.show()\n",
" \n",
"# Now we call interact, and give it a tuple specifiying the min, max and step for the theta slider\n",
"interact(update_plot, theta=(0,89,2))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It is a bit slow in updating if you wiggle it too much with the mouse, but if you click on the slider and adjust it using the arrow keys on your keyboard, it works pretty well. \n",
"\n",
"If you are fitting a line to your data, this can also be very useful for getting a good initial guess:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def update_plot2(slope=0.5):\n",
" line = t*slope\n",
" plt.plot(t,v, '.')\n",
" plt.plot(t,line, lw=4)\n",
" plt.xlabel(\"Time (s)\")\n",
" plt.ylabel(\"Voltage (V)\")\n",
" plt.show()\n",
"\n",
"interact(update_plot2, slope=(0,10,0.1))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It is also easy to make two sliders:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def update_plot3(slope=0.5, offset=0):\n",
" line = t*slope+offset\n",
" plt.plot(t,v, '.')\n",
" plt.plot(t,line, lw=4)\n",
" plt.xlabel(\"Time (s)\")\n",
" plt.ylabel(\"Voltage (V)\")\n",
" plt.show()\n",
"\n",
"interact(update_plot3, slope=(0,10,0.1), offset=(-4,3,0.2))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Functions\n",
"\n",
"### Keyword and optional arguments\n",
"\n",
"In addition to the \"positional\" arguments we introduced earlier, python also supports another type of argument: the \"keyword\" argument. These are often used for \"optional\" arguments that you don't neccessarily need but may want to give the user the option of using. The syntax is:\n",
"\n",
"```\n",
"def function_name(var1, optional_var2 = default_value)\n",
" ...\n",
"```\n",
"\n",
"The \"default_value\" is the value that the optional argument will have if it is not specified by the user. \n",
"\n",
"In python-speak, these \"optional\" arguement as called \"keyword\" arguments, and the normal arguments we introduced above are called \"positional\" arguments. In python, in both defining and using functions, keyword arguments must always come after all of the positional arguments. \n",
"\n",
"Here, we will show an example where we use an optional parameter to change the way we print the status sentence. "
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The value of the first input variable is 1\n",
"The value of the first input variable is 2.5\n",
"Val is 2.4\n"
]
}
],
"source": [
"def print_status4(x, long=True):\n",
" if long:\n",
" print(\"The value of the first input variable is \", x)\n",
" else:\n",
" print(\"Val is \", x)\n",
"\n",
"print_status4(1)\n",
"print_status4(2.5, long=True)\n",
"print_status4(2.4, long=False)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Because python assigns the value of keyword argument variables in the function by matching the keyword and not their position in the list, if you have multiple keyword arguments, you can also change the order of them when you use the function. \n",
"\n",
"For example, if I define a function:\n",
"\n",
"```\n",
"def myfunction(x, var1=1, var2=4):\n",
" ...\n",
"```\n",
"\n",
"then both of these would do the same thing:\n",
"\n",
"```\n",
"myfunction(1,var1=3, var2=54)\n",
"myfunction(1,var2=54, var2=3)\n",
"```\n",
"\n",
"Finally, one can also use keywords as a way to send values to functions even if the functions are not defined with keyword arguments. This allows you to change to order of variables you send to a function if you want. For example:"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [],
"source": [
"def myfun(x,y):\n",
" print(\"x is\", x)\n",
" print(\"y is\", y) "
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"x is 1\n",
"y is 2\n"
]
}
],
"source": [
"myfun(1,2)"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"x is 2\n",
"y is 1\n"
]
}
],
"source": [
"myfun(2,1)"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"x is 1\n",
"y is 2\n"
]
}
],
"source": [
"myfun(x=1,y=2)"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"x is 1\n",
"y is 2\n"
]
}
],
"source": [
"myfun(y=2,x=1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Python Error Messages with functions\n",
"\n",
"In the first notebook, we learned some of the basics of how to understand python errors.\n",
"\n",
"Sometimes, though, if you are using functions from a library, the error messages can get very long, and trickier to understand. \n",
"\n",
"Here, we will look at how to dissect an example of a more complicated error you can get from a function in a library and how to figure out where the useful information is."
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"scrolled": false
},
"outputs": [
{
"ename": "ValueError",
"evalue": "x and y must have same first dimension, but have shapes (2,) and (3,)",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-11-19f47447b05c>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mmatplotlib\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mpyplot\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0mplt\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0mplt\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mplot\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m2\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;33m[\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m2\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m3\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;32mC:\\Programs\\Anaconda3\\lib\\site-packages\\matplotlib\\pyplot.py\u001b[0m in \u001b[0;36mplot\u001b[1;34m(*args, **kwargs)\u001b[0m\n\u001b[0;32m 3356\u001b[0m mplDeprecation)\n\u001b[0;32m 3357\u001b[0m \u001b[1;32mtry\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m-> 3358\u001b[1;33m \u001b[0mret\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0max\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mplot\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m*\u001b[0m\u001b[0margs\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;33m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 3359\u001b[0m \u001b[1;32mfinally\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 3360\u001b[0m \u001b[0max\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m_hold\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mwashold\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
"\u001b[1;32mC:\\Programs\\Anaconda3\\lib\\site-packages\\matplotlib\\__init__.py\u001b[0m in \u001b[0;36minner\u001b[1;34m(ax, *args, **kwargs)\u001b[0m\n\u001b[0;32m 1853\u001b[0m \u001b[1;34m\"the Matplotlib list!)\"\u001b[0m \u001b[1;33m%\u001b[0m \u001b[1;33m(\u001b[0m\u001b[0mlabel_namer\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mfunc\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m__name__\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 1854\u001b[0m RuntimeWarning, stacklevel=2)\n\u001b[1;32m-> 1855\u001b[1;33m \u001b[1;32mreturn\u001b[0m \u001b[0mfunc\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0max\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;33m*\u001b[0m\u001b[0margs\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;33m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 1856\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 1857\u001b[0m inner.__doc__ = _add_data_doc(inner.__doc__,\n",
"\u001b[1;32mC:\\Programs\\Anaconda3\\lib\\site-packages\\matplotlib\\axes\\_axes.py\u001b[0m in \u001b[0;36mplot\u001b[1;34m(self, *args, **kwargs)\u001b[0m\n\u001b[0;32m 1525\u001b[0m \u001b[0mkwargs\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mcbook\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mnormalize_kwargs\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0m_alias_map\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 1526\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m-> 1527\u001b[1;33m \u001b[1;32mfor\u001b[0m \u001b[0mline\u001b[0m \u001b[1;32min\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m_get_lines\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m*\u001b[0m\u001b[0margs\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;33m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 1528\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0madd_line\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mline\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 1529\u001b[0m \u001b[0mlines\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mappend\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mline\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
"\u001b[1;32mC:\\Programs\\Anaconda3\\lib\\site-packages\\matplotlib\\axes\\_base.py\u001b[0m in \u001b[0;36m_grab_next_args\u001b[1;34m(self, *args, **kwargs)\u001b[0m\n\u001b[0;32m 404\u001b[0m \u001b[0mthis\u001b[0m \u001b[1;33m+=\u001b[0m \u001b[0margs\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 405\u001b[0m \u001b[0margs\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0margs\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 406\u001b[1;33m \u001b[1;32mfor\u001b[0m \u001b[0mseg\u001b[0m \u001b[1;32min\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m_plot_args\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mthis\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mkwargs\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 407\u001b[0m \u001b[1;32myield\u001b[0m \u001b[0mseg\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 408\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n",
"\u001b[1;32mC:\\Programs\\Anaconda3\\lib\\site-packages\\matplotlib\\axes\\_base.py\u001b[0m in \u001b[0;36m_plot_args\u001b[1;34m(self, tup, kwargs)\u001b[0m\n\u001b[0;32m 381\u001b[0m \u001b[0mx\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0my\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mindex_of\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mtup\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;33m-\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 382\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 383\u001b[1;33m \u001b[0mx\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0my\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m_xy_from_xy\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mx\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0my\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 384\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 385\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mcommand\u001b[0m \u001b[1;33m==\u001b[0m \u001b[1;34m'plot'\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
"\u001b[1;32mC:\\Programs\\Anaconda3\\lib\\site-packages\\matplotlib\\axes\\_base.py\u001b[0m in \u001b[0;36m_xy_from_xy\u001b[1;34m(self, x, y)\u001b[0m\n\u001b[0;32m 240\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0mx\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mshape\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m]\u001b[0m \u001b[1;33m!=\u001b[0m \u001b[0my\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mshape\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 241\u001b[0m raise ValueError(\"x and y must have same first dimension, but \"\n\u001b[1;32m--> 242\u001b[1;33m \"have shapes {} and {}\".format(x.shape, y.shape))\n\u001b[0m\u001b[0;32m 243\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0mx\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mndim\u001b[0m \u001b[1;33m>\u001b[0m \u001b[1;36m2\u001b[0m \u001b[1;32mor\u001b[0m \u001b[0my\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mndim\u001b[0m \u001b[1;33m>\u001b[0m \u001b[1;36m2\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 244\u001b[0m raise ValueError(\"x and y can be no greater than 2-D, but have \"\n",
"\u001b[1;31mValueError\u001b[0m: x and y must have same first dimension, but have shapes (2,) and (3,)"
]
}
],
"source": [
"import matplotlib.pyplot as plt\n",
"plt.plot([1,2], [1,2,3])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Wow, that was a really big error message. What do I do with all of this? \n",
"\n",
"The most important information is at the very top and at the very bottom (you can just skip the rest for now...). \n",
"\n",
"At the top, it shows us the part of our code that triggered the error:\n",
"\n",
"<img src=\"big_error_1.png\"></img>\n",
"\n",
"The error type is a `ValueError`, which according to the documentation, indicates \"an argument that has the right type but an inappropriate value\". \n",
"\n",
"In the middle there is then a whole bunch of stuff we won't easily understand. What is all of this? This is showing us what is happening inside all the functions of the matplotlib library...probably unless you are a bit of an expert, you will not really understand all of this. \n",
"\n",
"We can learn more, though, by looking at the last line:\n",
"\n",
"<img src=\"big_error_2.png\"></img>\n",
"\n",
"What are `x` and `y`? They are the variable names in the library function in matplotlib where we ended up, so probably also maybe not immediately obvious what they are. But we can see more about the problem: it is complaining that two of the variables do not have the same shape. \n",
"\n",
"If we look up at the line in our code that triggered the error, we can see that we have supplied two arguments that have a different number of elements: `plt.plot([1,2], [1,2,3])`\n",
"\n",
"It would seem that both the first and second variables of the `plot` function should have the same number of elements. Indeed, if we try:\n",
"\n",
"`plt.plot([1,2,3], [1,2,3,])`\n",
"\n",
"then the error goes away:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.plot([1,2,3], [1,2,3,])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Learning objectives list\n",
"\n",
"Not crucial since this notebook is optional, but maybe useful to have.\n",
"\n",
"**Learning objectives for this notebook:**\n",
"\n",
"* Student is able to create and index tuples and lists by hand and using the `range()` operator\n",
"* Student is able to loop over tuples and lists without indexing\n",
"* Student is able to extract subsets of lists and tuples using slicing\n",
"* Student is able to change individual entries of a list using indexing and the assignment operator\n",
"* Student is able to use built-in functions of lists \n",
"* Student is able to use indexing to extract substrings from a string\n",
"* Student is able to use built-in string functions\n",
"* Student is able to split a string into a list of strings using the `.split()` function\n",
"* Student is able to search in strings using the `in` operator\n",
"* Student is able to use formating and the `%` opereator to control how variables are translated into strings\n",
"* Student is able to predict how variables behave differently for \"mutable\" and \"non-mutable\" objects (call-by-value vs. call-by-reference)\n",
"* Student is able to use the `ipywidgets` `interact()` function to explore functions using sliders\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
"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",
"version": "3.7.4"
},
"toc": {
"base_numbering": "1",
"nav_menu": {},
"number_sections": true,
"sideBar": true,
"skip_h1_title": true,
"title_cell": "Table of Contents",
"title_sidebar": "Contents",
"toc_cell": false,
"toc_position": {
"height": "calc(100% - 180px)",
"left": "10px",
"top": "150px",
"width": "303.797px"
},
"toc_section_display": true,
"toc_window_display": true
},
"widgets": {
"application/vnd.jupyter.widget-state+json": {
"state": {},
"version_major": 2,
"version_minor": 0
}
}
},
"nbformat": 4,
"nbformat_minor": 2
}