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
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
{
"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",
"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",