BeginnerToAdvanced.ipynb 36.7 KB
Newer Older
Simon Clarke's avatar
Simon Clarke committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introducing Python\n",
    "\n",
    "### What Is Python?\n",
    "\n",
    "* Interpreted high-level object-oriented dynamically-typed scripting language.\n",
    "* As a result, run time errors are usually encountered.\n",
    "\n",
    "### Why Python?\n",
    "\n",
16
    "* Python is the most popular language due to the fact that it’s easier to code and understand.\n",
Simon Clarke's avatar
Simon Clarke committed
17
18
    "* Python is an object-oriented programming language and can be used to write functional code too.\n",
    "* It is a suitable language that bridges the gaps between business and developers.\n",
19
20
    "* It takes less time to bring a Python program to market compared to other languages such as C#/Java.\n",
    "* There are a large number of python machine learning and analytical packages.\n",
Simon Clarke's avatar
Simon Clarke committed
21
    "* A large number of communities and books are available to support Python developers.\n",
22
    "* Nearly all types of applications, can be implemented in Python.\n",
Simon Clarke's avatar
Simon Clarke committed
23
24
25
26
27
28
29
30
31
32
33
34
35
36
    "* There is no need to declare variable types. Thus it is quicker to implement a Python application.\n",
    "\n",
    "### Why Not Python?\n",
    "\n",
    "* Python is slower than C++, C#, Java. This is due to the lack of Just In Time optimisers in Python.\n",
    "* Python syntactical white-space constraint makes it slightly difficult to implement for new coders.\n",
    "* Python does not offer advanced statistical features as R does.\n",
    "* Python is not suitable for low-level systems and hardware interaction."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
37
    "## Variables\n",
Simon Clarke's avatar
Simon Clarke committed
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
    "\n",
    "* Variables store information that can be used and/or changed in your program. This information can be an integer, text, collection, etc.\n",
    "* Variables are used to hold user inputs, local states of your program, etc.\n",
    "* Variables have a name so that they can be referenced in the code.\n",
    "* The fundamental concept to understand is that everything is an object in Python.\n",
    "\n",
    "__Python supports numbers, strings, sets, lists, tuples, and dictionaries. These are the standard data types. Each will be explained in detail.__\n",
    "\n",
    "### Declare and Assign Value to a Variable\n",
    "\n",
    "Assignment sets a value to a variable.\n",
    "\n",
    "To assign variable a value, use the equals sign (=)"
   ]
  },
  {
   "cell_type": "code",
55
56
57
58
59
60
61
62
63
64
65
   "execution_count": 294,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello You 2\n"
     ]
    }
   ],
Simon Clarke's avatar
Simon Clarke committed
66
67
68
69
   "source": [
    "myFirstVariable = 1\n",
    "mySecondVariable = 2\n",
    "myFirstVariable = \"Hello You\"\n",
70
    "print(myFirstVariable,mySecondVariable) # print arguments to standard output or screen"
Simon Clarke's avatar
Simon Clarke committed
71
72
73
74
75
76
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
77
78
    "Note that comments can be included in code by inserting a #. Everything after this on the line is ignored.\n",
    "\n",
79
    "Assigning a value is known as __binding__ in Python. In the example above, we have assigned the value of 2 to mySecondVariable.\n",
Simon Clarke's avatar
Simon Clarke committed
80
    "\n",
81
    "Note how we assigned an integer value of 1 and then a string value of “Hello You” to the same myFirstVariable variable. This is possible due to the fact that the data types are dynamically typed in python. This is why Python is known as a dynamically typed programming language.\n",
Simon Clarke's avatar
Simon Clarke committed
82
83
84
85
86
87
    "\n",
    "If you want to assign the same value to more than one variables then you can use the chained assignment:"
   ]
  },
  {
   "cell_type": "code",
88
   "execution_count": 295,
Simon Clarke's avatar
Simon Clarke committed
89
90
91
92
93
94
95
96
97
98
99
100
   "metadata": {},
   "outputs": [],
   "source": [
    "myFirstVariable = mySecondVariable = 1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Numeric\n",
    "\n",
101
    "Integers and floats (floating point numbers) are supported."
Simon Clarke's avatar
Simon Clarke committed
102
103
104
105
   ]
  },
  {
   "cell_type": "code",
106
107
108
109
110
111
112
113
114
115
116
117
   "execution_count": 296,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "1.2\n"
     ]
    }
   ],
Simon Clarke's avatar
Simon Clarke committed
118
   "source": [
119
120
121
122
    "value1 = 1 # integer\n",
    "value2 = 1.2 # float with a floating point\n",
    "print(value1)\n",
    "print(value2)"
Simon Clarke's avatar
Simon Clarke committed
123
124
125
126
127
128
129
130
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Strings\n",
    "\n",
131
132
    "* Textual information. Not limited to letters.\n",
    "* A string is an list of characters.\n",
Simon Clarke's avatar
Simon Clarke committed
133
134
135
136
137
    "* A string value is enclosed in quotation marks: single, double or triple quotes."
   ]
  },
  {
   "cell_type": "code",
138
   "execution_count": 297,
Simon Clarke's avatar
Simon Clarke committed
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
   "metadata": {},
   "outputs": [],
   "source": [
    "name = 'simon'\n",
    "name = \"simon\"\n",
    "name = \"\"\"simon\"\"\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* Strings are immutable. Once they are created, they cannot be changed, e.g.,"
   ]
  },
  {
   "cell_type": "code",
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
   "execution_count": 344,
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "'str' object does not support item assignment",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-344-35db51373c14>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m      1\u001b[0m \u001b[0ma\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m'me'\u001b[0m \u001b[0;31m# Updating it will fail:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0ma\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m'y'\u001b[0m \u001b[0;31m# Will throw a Type Error\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;31mTypeError\u001b[0m: 'str' object does not support item assignment"
     ]
    }
   ],
Simon Clarke's avatar
Simon Clarke committed
171
172
173
174
175
176
177
178
179
   "source": [
    "a = 'me' # Updating it will fail: \n",
    "a[1]='y' # Will throw a Type Error"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
180
    "* When string variables are assigned a new value then Python creates a new object to store the value. Therefore a reference/pointer to an object is created. This pointer is then assigned to the variable and as a result, the variable can be used.\n",
Simon Clarke's avatar
Simon Clarke committed
181
    "\n",
182
    "We can also assign one variable to another variable. All it does is that a new pointer is created which points to the same object:\n"
Simon Clarke's avatar
Simon Clarke committed
183
184
185
186
   ]
  },
  {
   "cell_type": "code",
187
   "execution_count": null,
Simon Clarke's avatar
Simon Clarke committed
188
   "metadata": {},
189
   "outputs": [],
Simon Clarke's avatar
Simon Clarke committed
190
   "source": [
191
192
193
194
    "a = 'alpha' \n",
    "b = a \n",
    "a = 'beta'\n",
    "print(a,b)"
Simon Clarke's avatar
Simon Clarke committed
195
196
197
198
199
200
201
202
203
204
205
206
207
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Finding Variable Type\n",
    "\n",
    "If you want to find type of a variable, you can implement:\n"
   ]
  },
  {
   "cell_type": "code",
208
   "execution_count": null,
Simon Clarke's avatar
Simon Clarke committed
209
   "metadata": {},
210
   "outputs": [],
Simon Clarke's avatar
Simon Clarke committed
211
212
213
214
215
216
217
218
219
220
   "source": [
    "type('simon') # Returns <type 'str'>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Operations\n",
    "\n",
221
    "* Allow us to perform computation on variables\n",
Simon Clarke's avatar
Simon Clarke committed
222
223
224
225
    "\n",
    "### Numeric Operations\n",
    "\n",
    "* Python supports basic *, /, +, -\n",
226
    "* Python also supports floor division // (division rounded __down__ to the next integer)"
Simon Clarke's avatar
Simon Clarke committed
227
228
229
230
   ]
  },
  {
   "cell_type": "code",
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
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(1//3)  #returns 0\n",
    "print(1/3) #returns 0.333 "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note: the return type of division is always float as shown below:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = 10/5\n",
    "print(type(a)) # prints float"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Additionally, python supports exponentiation via `**` operator:"
   ]
  },
  {
   "cell_type": "code",
265
266
267
268
269
270
271
272
273
274
275
   "execution_count": 345,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "8\n"
     ]
    }
   ],
Simon Clarke's avatar
Simon Clarke committed
276
   "source": [
277
    "print(2**3)"
Simon Clarke's avatar
Simon Clarke committed
278
279
280
281
282
283
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
284
    "Python also supports Modulus (remainder) operator:"
Simon Clarke's avatar
Simon Clarke committed
285
286
287
288
   ]
  },
  {
   "cell_type": "code",
289
290
291
292
293
294
295
296
297
298
299
   "execution_count": 346,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n"
     ]
    }
   ],
Simon Clarke's avatar
Simon Clarke committed
300
   "source": [
301
    "print(7%2) # (7/2-7//2)*2 = 1"
Simon Clarke's avatar
Simon Clarke committed
302
303
304
305
306
307
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
308
    "There is also a divmod built-in function. It returns the floor division and modulus:"
Simon Clarke's avatar
Simon Clarke committed
309
310
311
312
   ]
  },
  {
   "cell_type": "code",
313
314
315
316
317
318
319
320
321
322
323
   "execution_count": 347,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(3, 1)\n"
     ]
    }
   ],
Simon Clarke's avatar
Simon Clarke committed
324
   "source": [
325
    "print(divmod(10,3)) #it will print 3 and 1 as 3*3 = 9 +1 = 10"
Simon Clarke's avatar
Simon Clarke committed
326
327
328
329
330
331
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
332
    "The common operators also support augmented expressions. For example, `a+1` can be written as"
Simon Clarke's avatar
Simon Clarke committed
333
334
335
336
   ]
  },
  {
   "cell_type": "code",
337
338
339
340
341
342
343
344
345
346
347
   "execution_count": 348,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3\n"
     ]
    }
   ],
Simon Clarke's avatar
Simon Clarke committed
348
   "source": [
349
350
351
    "a = 2\n",
    "a += 1 # shorthand for a = a+1\n",
    "print(a)"
Simon Clarke's avatar
Simon Clarke committed
352
353
354
355
356
357
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
358
359
360
361
362
363
364
    "## Methods\n",
    "\n",
    "We have already seen examples of functions such as `print()`, `type()` and `divmod`.\n",
    "\n",
    "Each class or type of variable has a set of functions that are built in to their implementation. These are called *methods* and are invoked by first calling the variable and then following that with a period and then the function name. \n",
    "\n",
    "For example, there are number of methods for changing the case of strings:"
Simon Clarke's avatar
Simon Clarke committed
365
366
367
368
   ]
  },
  {
   "cell_type": "code",
369
370
371
372
373
374
375
376
377
378
379
380
381
   "execution_count": 349,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello world!\n",
      "HELLO WORLD!\n",
      "hEllO wORLd!\n"
     ]
    }
   ],
Simon Clarke's avatar
Simon Clarke committed
382
   "source": [
383
384
385
386
    "myString = \"HeLLo WorlD!\"\n",
    "print(myString.lower()) # convert string to lower case\n",
    "print(myString.upper()) # convert string to upper case\n",
    "print(myString.swapcase()) # swap the case of all the letters"
Simon Clarke's avatar
Simon Clarke committed
387
388
389
390
391
392
393
394
395
396
397
398
399
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### String Operations\n",
    "\n",
    "#### Concatenate Strings:"
   ]
  },
  {
   "cell_type": "code",
400
401
402
403
404
405
406
407
408
409
410
   "execution_count": 350,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "AB\n"
     ]
    }
   ],
Simon Clarke's avatar
Simon Clarke committed
411
412
413
414
415
416
417
418
   "source": [
    "print('A' + 'B')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
419
    "Remember a string is an immutable data type, therefore, concatenating strings creates a new string object.\n",
Simon Clarke's avatar
Simon Clarke committed
420
421
422
423
424
425
426
427
    "\n",
    "#### Repeat String:\n",
    "\n",
    "‘A’*3 will repeat A three times:"
   ]
  },
  {
   "cell_type": "code",
428
429
430
431
432
433
434
435
436
437
438
   "execution_count": 351,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "AAA\n"
     ]
    }
   ],
Simon Clarke's avatar
Simon Clarke committed
439
440
441
442
443
444
445
446
   "source": [
    "print('A'*3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
447
448
449
450
451
452
    "#### Slicing:\n",
    "\n",
    "Each element in a string or list gets two indexes:\n",
    "* From left to right, the index starts at 0 and increments by 1\n",
    "* From right to left, the index starts at -1 and decrements by 1\n",
    "* Therefore,  `y[0]` and `y[-len(y)]` both will return the same value:"
Simon Clarke's avatar
Simon Clarke committed
453
454
455
   ]
  },
  {
456
   "cell_type": "markdown",
Simon Clarke's avatar
Simon Clarke committed
457
458
   "metadata": {},
   "source": [
459
460
461
    "y = 'abc'\n",
    "print(y[0])\n",
    "print(y[-len(y)])"
Simon Clarke's avatar
Simon Clarke committed
462
463
464
465
466
467
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
468
469
470
471
472
    "We can access a substring of a string (or a list) using:\n",
    "\n",
    "`string[start:end:step]`\n",
    "\n",
    "This returns the characters in the string starting at `start` and up to, but not including, `end`, in steps of `step`. Each of the arguments, and the last semi-colon, are optional. The default values are `start=0`, `end=len(string)` and `step=1`."
Simon Clarke's avatar
Simon Clarke committed
473
474
475
476
   ]
  },
  {
   "cell_type": "code",
477
478
479
480
481
482
483
484
485
486
487
488
489
   "execution_count": 352,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Ac\n",
      "bc\n",
      "Ab\n"
     ]
    }
   ],
Simon Clarke's avatar
Simon Clarke committed
490
   "source": [
491
492
493
494
    "y = 'Abc'\n",
    "print(y[0::2])\n",
    "print(y[1:])\n",
    "print(y[:2])"
Simon Clarke's avatar
Simon Clarke committed
495
496
497
498
499
500
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
501
    "#### Reversing\n",
Simon Clarke's avatar
Simon Clarke committed
502
    "\n",
503
    "Using this slicing with negative steps we can reverse a string:"
Simon Clarke's avatar
Simon Clarke committed
504
505
506
507
   ]
  },
  {
   "cell_type": "code",
508
509
510
511
512
513
514
515
516
517
518
   "execution_count": 353,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cba\n"
     ]
    }
   ],
Simon Clarke's avatar
Simon Clarke committed
519
   "source": [
520
521
    "x = 'abc'\n",
    "print(x[::-1])"
Simon Clarke's avatar
Simon Clarke committed
522
523
524
525
526
527
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
528
    "#### Negative Index\n",
Simon Clarke's avatar
Simon Clarke committed
529
    "\n",
530
    "If you want to start from the last character then use negative index."
Simon Clarke's avatar
Simon Clarke committed
531
532
533
534
   ]
  },
  {
   "cell_type": "code",
535
536
537
538
539
540
541
542
543
544
545
   "execution_count": 354,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cb\n"
     ]
    }
   ],
Simon Clarke's avatar
Simon Clarke committed
546
547
   "source": [
    "y = 'abc'\n",
548
    "print(y[-1:0:-1]) # will return cb, same as print(y[-1:-3:-1])"
Simon Clarke's avatar
Simon Clarke committed
549
550
551
552
553
554
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
555
556
557
558
559
    "#### Finding Index\n",
    "\n",
    "To find the occurence of a character in a string we can use the find method. The second and third arguments, which are optional, tell where to start and end the search. \n",
    "\n",
    "Remember indices start at 0."
Simon Clarke's avatar
Simon Clarke committed
560
561
562
563
   ]
  },
  {
   "cell_type": "code",
564
565
566
567
568
569
570
571
572
573
574
575
   "execution_count": 355,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n",
      "9\n"
     ]
    }
   ],
Simon Clarke's avatar
Simon Clarke committed
576
   "source": [
577
578
    "name = \"rumpelstiltskin\"\n",
    "print(name.find('m')) \n",
579
    "print(name.find('l',7,10)) # finds index of l, starting at name[7] and ending at name[10]"
Simon Clarke's avatar
Simon Clarke committed
580
581
582
583
584
585
586
587
588
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "    \n",
    "#### Casting\n",
    "\n",
589
590
591
592
593
    "To __cast__ (convert between types cast) we can use the functions:\n",
    "\n",
    "* `str(x)`: convert to string\n",
    "* `int(x)`: convert to integer\n",
    "* `float(x)`: convert to floats\n",
Simon Clarke's avatar
Simon Clarke committed
594
595
596
597
598
599
600
601
    "    \n",
    "### Set Operations\n",
    "\n",
    "* A set is an unordered data collection without any duplicates. We can define a set variable as:"
   ]
  },
  {
   "cell_type": "code",
602
603
604
605
606
607
608
609
610
611
612
   "execution_count": 356,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{1, 2, 3, 5, 8, 9, -1}\n"
     ]
    }
   ],
Simon Clarke's avatar
Simon Clarke committed
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
   "source": [
    "set = {9,1,-1,5,2,8,3, 8}\n",
    "print(set)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note duplicates are removed.\n",
    "\n",
    "Set has `a item in set`, `len(set)` and `for item in set` operations. However it does not support indexing and \n",
    "slicing like lists.\n",
    "\n",
    "Some of the most important set operations are:\n",
    "* `set.add(item)` — adds item to the set\n",
    "* `set.remove(item)` — removes item from the set and raises error if it is not present\n",
    "* `set.discard(item)` — removes item from the set if it is present\n",
    "* `set.pop()` — returns any item from the set, raises KeyError if the set is empty\n",
632
    "* `set.clear()` - clears the set\n",
Simon Clarke's avatar
Simon Clarke committed
633
634
635
636
637
638
639
640
    "\n",
    "#### Intersect Sets\n",
    "\n",
    "To get what’s common in two sets"
   ]
  },
  {
   "cell_type": "code",
641
642
643
644
645
646
647
648
649
650
651
   "execution_count": 357,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "intersection of a and b is {3}\n"
     ]
    }
   ],
Simon Clarke's avatar
Simon Clarke committed
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
   "source": [
    "a = {1,2,3}\n",
    "b = {3,4,5}\n",
    "print('intersection of a and b is',a.intersection(b))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Difference In Sets\n",
    "\n",
    "To retrieve the difference between two sets:"
   ]
  },
  {
   "cell_type": "code",
669
670
671
672
673
674
675
676
677
678
679
   "execution_count": 358,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "difference of a and b is {1, 2}\n"
     ]
    }
   ],
Simon Clarke's avatar
Simon Clarke committed
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
   "source": [
    "a = {1,2,3}\n",
    "b = {3,4,5}\n",
    "print('difference of a and b is',a.difference(b))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Union Of Collections\n",
    "\n",
    "To get a distinct combined set of two sets"
   ]
  },
  {
   "cell_type": "code",
697
698
699
700
701
702
703
704
705
706
707
   "execution_count": 359,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "union of a and b is {1, 2, 3, 4, 5}\n"
     ]
    }
   ],
Simon Clarke's avatar
Simon Clarke committed
708
709
710
711
712
713
   "source": [
    "a = {1,2,3}\n",
    "b = {3,4,5}\n",
    "print('union of a and b is',a.union(b))"
   ]
  },
714
715
716
717
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
718
    "## Comments and Line Continuation\n",
719
720
721
722
723
724
    "\n",
    "### Single Line Comments"
   ]
  },
  {
   "cell_type": "code",
725
   "execution_count": 360,
726
727
728
729
730
731
732
733
734
735
736
737
   "metadata": {},
   "outputs": [],
   "source": [
    "# this is a single line comment"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Multiple Line Comments\n",
    "\n",
738
    "For long comments we can use (note \\n represents carriage return):"
739
740
741
742
   ]
  },
  {
   "cell_type": "code",
743
744
745
746
747
748
749
750
751
752
753
754
755
756
   "execution_count": 361,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'this is a multi\\nline\\ncomment'"
      ]
     },
     "execution_count": 361,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
757
   "source": [
758
    "'''this is a multi\n",
759
    "line\n",
760
    "comment'''"
761
762
763
764
765
766
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
767
    "### Line Contintuation\n",
768
    "\n",
769
770
771
772
773
    "Long expressions can be continued over multiple lines by enclosing them in parentheses:"
   ]
  },
  {
   "cell_type": "code",
774
775
776
777
778
779
780
781
782
783
784
   "execution_count": 362,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-197.0\n"
     ]
    }
   ],
785
786
787
788
   "source": [
    "a = (25*10+6/2 # can add comment that expression continues on next line\n",
    "    -450)\n",
    "print(a)"
789
790
791
792
793
794
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
795
    "or using a backslash: "
796
797
798
799
   ]
  },
  {
   "cell_type": "code",
800
801
802
803
804
805
806
807
808
809
810
   "execution_count": 363,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-197.0\n"
     ]
    }
   ],
811
   "source": [
812
    "# no characters can appear after the backslash\n",
813
814
815
    "a = 25*10+6/2 \\\n",
    "    -450\n",
    "print(a)"
816
817
818
819
820
821
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
822
823
824
825
826
827
828
829
830
831
    "## Boolean Expressions\n",
    "\n",
    "Expressions can perform Boolean operations such as:\n",
    "* Equality: `==`\n",
    "* Not Equal: `!=`\n",
    "* Greater Than: `>`\n",
    "* Less Than: `<`\n",
    "* Greater Than Or Equal: `>=`\n",
    "* Less Than Or Equal: `<=`\n",
    "\n",
832
    "We can compare numbers and assign Boolean variables:"
833
834
835
836
   ]
  },
  {
   "cell_type": "code",
837
838
839
840
841
842
843
844
845
846
847
848
849
   "execution_count": 364,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n",
      "True\n",
      "c =  False\n"
     ]
    }
   ],
850
   "source": [
851
852
853
    "a = 1\n",
    "b = 2\n",
    "print(a==b) # test whether a is equal to b\n",
854
855
856
    "print(a<=b) # test whether a is less than or equal to b\n",
    "c = a>b     # c is a Boolean variable\n",
    "print('c = ',c)"
857
858
859
860
861
862
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
863
    "and other objects, such as sets:"
864
865
866
867
   ]
  },
  {
   "cell_type": "code",
868
869
870
871
872
873
874
875
876
877
878
   "execution_count": 365,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
879
   "source": [
880
881
882
    "set1 = {1,2,3}\n",
    "set2 = {1,2,3,4}\n",
    "print(set1<=set2) # true if every element of set1 is in set2 and set2 is larger than set1"
883
884
885
886
887
888
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
889
    "## Functions\n",
890
    "\n",
891
892
893
894
895
896
897
898
899
    "* Functions are sequence of statements that you can execute in your code. If you see repetition in your code then create a reusable function and use it in your program.\n",
    "* Functions can also reference other functions.\n",
    "* Functions eliminate repetition in your code. They make it easier to debug and find issues.\n",
    "* Finally, functions enable code to be understandable and easier to manage.\n",
    "* In short, functions allow us to split a large application into smaller chunks.\n",
    "\n",
    "### Define New Function\n",
    "\n",
    "The first line of the function begins with `def` and defines the function name and arguments. The following lines, to the end of the function, are uniformly indented.\n"
900
901
902
903
   ]
  },
  {
   "cell_type": "code",
904
   "execution_count": 366,
905
906
907
   "metadata": {},
   "outputs": [],
   "source": [
908
909
    "def my_new_function():\n",
    "    print('this is my new function')"
910
911
912
913
914
915
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
916
    "### Calling Function\n"
917
918
919
920
   ]
  },
  {
   "cell_type": "code",
921
922
923
924
925
926
927
928
929
930
931
   "execution_count": 367,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "this is my new function\n"
     ]
    }
   ],
932
   "source": [
933
    "my_new_function()"
934
935
936
937
938
939
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
940
    "To find the length of a string we can call the len(x) function:"
941
942
943
944
   ]
  },
  {
   "cell_type": "code",
945
946
947
948
949
950
951
952
953
954
955
956
957
958
   "execution_count": 368,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5"
      ]
     },
     "execution_count": 368,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
959
   "source": [
960
    "len('hello')"
961
962
963
964
965
966
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
967
    "#### Arguments\n",
968
    "\n",
969
970
971
972
973
974
    "* Arguments can be added to a function to make it generic.\n",
    "* You can pass in variables to a method:"
   ]
  },
  {
   "cell_type": "code",
975
   "execution_count": 369,
976
977
978
979
980
981
982
983
984
985
986
   "metadata": {},
   "outputs": [],
   "source": [
    "def my_new_function(my_value):\n",
    "    print('this is my new function with ' + my_value)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
987
    "Information about the function can be included in a `docstring` starting on the first line after the function declaration and enclosed in triple quotes (single or double)."
988
989
990
991
   ]
  },
  {
   "cell_type": "code",
992
   "execution_count": 370,
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
   "metadata": {},
   "outputs": [],
   "source": [
    "def my_new_function(my_value):\n",
    "    '''This function takes the input argument, concatenates it with a fixed string and\n",
    "    prints the output.'''\n",
    "    print('this is my new function with ' + my_value)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then using `help()` will give you the arguments and information about the function."
1007
1008
1009
1010
   ]
  },
  {
   "cell_type": "code",
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
   "execution_count": 371,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on function my_new_function in module __main__:\n",
      "\n",
      "my_new_function(my_value)\n",
      "    This function takes the input argument, concatenates it with a fixed string and\n",
      "    prints the output.\n",
      "\n"
     ]
    }
   ],
1027
   "source": [
1028
1029
1030
1031
1032
1033
1034
    "help(my_new_function)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
1035
    "If we want to know about the `len()` function:"
1036
1037
1038
1039
   ]
  },
  {
   "cell_type": "code",
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
   "execution_count": 372,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on built-in function len in module builtins:\n",
      "\n",
      "len(obj, /)\n",
      "    Return the number of items in a container.\n",
      "\n"
     ]
    }
   ],
1055
1056
   "source": [
    "help(len)"
1057
1058
1059
1060
1061
1062
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
1063
    "#### Return\n",
1064
1065
1066
1067
1068
1069
    "\n",
    "* Functions can return values such as:"
   ]
  },
  {
   "cell_type": "code",
1070
   "execution_count": 373,
1071
1072
1073
1074
   "metadata": {},
   "outputs": [],
   "source": [
    "def my_function(input):\n",
1075
    "    return input + 2"
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* If a function is required to return multiple values then it’s suitable to return a tuple (comma separated values). I will explain tuples later on:"
   ]
  },
  {
   "cell_type": "code",
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
   "execution_count": 374,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "7 8\n"
     ]
    }
   ],
1098
   "source": [
1099
1100
1101
1102
1103
    "def my_function(input):\n",
    "    return input + 2, input+3\n",
    "\n",
    "resultA,resultB = my_function(5)\n",
    "print(resultA,resultB)"
1104
1105
1106
1107
1108
1109
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
1110
    "### Lambda Function\n",
1111
1112
    "\n",
    "* Single expression anonymous function.\n",
1113
    "* It is an inline function.\n",
1114
    "* Lambda functions can be passed as arguments to other functions.\n",
1115
1116
1117
    "\n",
    "#### Syntax:\n",
    "`variable = lambda arguments: expression`\n"
1118
1119
1120
1121
   ]
  },
  {
   "cell_type": "code",
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
   "execution_count": 375,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 375,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
1136
1137
1138
1139
1140
   "source": [
    "my_lambda = lambda x,y,z : x - 100 + y - z\n",
    "my_lambda(100, 100, 100) # returns 0"
   ]
  },
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Collections\n",
    "\n",
    "### Lists\n",
    "* Lists are data structures that can hold a sequence of values of any data types. They are mutable (update-able).\n",
    "* Lists are indexed by integers.\n",
    "* To create a list, use square brackets:"
   ]
  },
  {
   "cell_type": "code",
1155
   "execution_count": 376,
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
   "metadata": {},
   "outputs": [],
   "source": [
    "my_list = ['A', 'B']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To add/update/delete an item, use index:"
   ]
  },
  {
   "cell_type": "code",
1171
   "execution_count": 377,
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
   "metadata": {},
   "outputs": [],
   "source": [
    "my_list.append('C') #adds at the end\n",
    "my_list[1] = 'D' #update\n",
    "my_list.pop(1) # removes\n",
    "# or\n",
    "del my_list[1:2] # removes\n",
    "another_list = ['X','Y','Z']\n",
    "my_list.extend(another_list) # adds second list at end"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* Addition, repetition and slices can be applied to lists (just like strings).\n",
    "* List also supports sorting:"
   ]
  },
  {
   "cell_type": "code",
1194
   "execution_count": 378,
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
   "metadata": {},
   "outputs": [],
   "source": [
    "my_list.sort() #this is inplace sort"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Tuples\n",
    "\n",
    "* Tuples are like lists in the sense that they can store a sequence of objects. The objects, again, can be of any type.\n",
    "* Tuples are faster than lists.\n",
    "* These collections are indexed by integers.\n",
    "* Tuples are immutable (non-update-able)"
   ]
  },
  {
   "cell_type": "code",
1215
   "execution_count": 379,
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
   "metadata": {},
   "outputs": [],
   "source": [
    "my_tuple = tuple()\n",
    "# or\n",
    "my_tuple = 'f','m'\n",
    "# or\n",
    "my_tuple = ('f', 'm')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note: If a tuple contains a list of items then we can modify the list. Also if you assign a value to an object and you store the object in a list and then change the object then the object within the list will get updated.\n",
1231
    "\n",
1232
    "### Dictionaries\n",
1233
    "\n",
1234
1235
1236
1237
1238
1239
    "* Dictionary is one of the most important data structure in the programming world. It stores key/value pair objects.\n",
    "* It has many benefits e.g. optimised data retrieval functionality."
   ]
  },
  {
   "cell_type": "code",
1240
   "execution_count": 380,
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
   "metadata": {},
   "outputs": [],
   "source": [
    "my_dictionary = dict()\n",
    "my_dictionary['my_key'] = 1\n",
    "my_dictionary['another_key'] = 2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can also create a dictionary as:"
   ]
  },
  {
   "cell_type": "code",
1258
   "execution_count": 381,
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
   "metadata": {},
   "outputs": [],
   "source": [
    "my_dictionary = {'my_key':1, 'another_key':2}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Print dictionary contents"
   ]
  },
  {
   "cell_type": "code",
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
   "execution_count": 382,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "my_key 1\n",
      "another_key 2\n"
     ]
    }
   ],
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
   "source": [
    "for key in my_dictionary:\n",
    "  print(key, my_dictionary[key])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* Values of a dictionary can be of any type including strings, numerical, boolean, lists or even dictionaries."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A few of the important functions for dictionaries are:\n",
    "* `get(key, default)`: returns value for key else returns default\n",
    "* `pop(key, default)`: returns value for key and deletes the item with key else returns default\n",
    "* `popitem()`: removes random item from the dictionary\n",
    "* `dictionary1.update(dictionary2)`: merges two dictionaries\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Conditions\n",
    "\n",
1315
    "To write a process based on tests of the values of variables, we can use the if then else construct:"
1316
1317
1318
1319
   ]
  },
  {
   "cell_type": "code",
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
   "execution_count": 383,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a is greater than b\n"
     ]
    }
   ],
1331
1332
1333
1334
1335
1336
1337
1338
   "source": [
    "a = 5\n",
    "b = 4\n",
    "if a == b:\n",
    "    print('a is b')\n",
    "elif a < b:\n",
    "    print('a is less than b')\n",
    "elif a > b:\n",
1339
    "    print('a is greater than b') \n",
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
    "else:\n",
    "    print('a is different') \n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note how colons and indentations are used to express the conditional logic. The indentation has already been seen with functions.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
1355
    "You can also add conditional logic in each part of the if then else construct. This is known as a nested condition."
1356
1357
1358
1359
   ]
  },
  {
   "cell_type": "code",
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
   "execution_count": 384,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "within else of else\n"
     ]
    }
   ],
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
   "source": [
    "a = 5\n",
    "b = 4\n",
    "if a == b:\n",
    "    print('a is b')\n",
    "#let's write conditions within else\n",
    "else:\n",
    "    if a == 2:\n",
    "        print('within if of else')\n",
    "    else:\n",
    "        print('within else of else')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Loops\n",
    "\n",
    "To repeat a process we can use while or for loops. Again these use indentation and colons to define the loop process.\n",
    "\n",
    "### While\n",
    "\n",
    "Here we provide a condition and run the loop until the condition is met:"
   ]
  },
  {
   "cell_type": "code",
1399
   "execution_count": 385,
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
   "metadata": {},
   "outputs": [],
   "source": [
    "input=2\n",
    "while (input < 0):\n",
    "    print(input)\n",
    "    input = input-1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### For\n",
    "\n",
    "To loop for a number of times:"
   ]
  },
  {
   "cell_type": "code",
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
   "execution_count": 386,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n",
      "1\n",
      "2\n",
      "3\n",
      "4\n"
     ]
    }
   ],
1435
   "source": [
1436
    "for i in [0,1,2,3,4]:\n",
1437
1438
1439
1440
1441
1442
1443
    "    print(i)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
1444
1445
1446
1447
1448
1449
    "Or we can use the range function:\n",
    "\n",
    "`range(start, stop, step):`\n",
    "\n",
    "Generates numerical values that commence at `start` (inclusive), finish at `stop` (exclusive) with the steps `step`. As an instance, to generate \n",
    "odd numbers from 1 to 9, do:"
1450
1451
1452
1453
   ]
  },
  {
   "cell_type": "code",
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
   "execution_count": 387,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 3, 5, 7, 9]"
      ]
     },
     "execution_count": 387,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
1468
   "source": [
1469
1470
1471
1472
1473
    "list(range(1,10,2))"
   ]
  },
  {
   "cell_type": "code",
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
   "execution_count": 388,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n",
      "1\n",
      "2\n",
      "3\n",
      "4\n"
     ]
    }
   ],
1489
1490
1491
   "source": [
    "for i in range(0,5):\n",
    "    print(i)"
1492
1493
1494
1495
1496
1497
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
1498
    "We can loop over items or characters of a string"
1499
1500
1501
1502
   ]
  },
  {
   "cell_type": "code",
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
   "execution_count": 389,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "h\n",
      "e\n",
      "l\n",
      "l\n",
      "o\n"
     ]
    }
   ],
1518
   "source": [
1519
1520
    "for letter in 'hello':\n",
    "    print(letter)"
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Combine For with If\n",
    "\n",
    "Let’s do a simple exercise to find if a character is in two words"
   ]
  },
  {
   "cell_type": "code",
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
   "execution_count": 390,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "o\n",
      "n\n",
      "e\n",
      "n\n",
      "a\n",
      "m\n",
      "e\n"
     ]
    }
   ],
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
   "source": [
    "name = 'onename'\n",
    "anothername = 'onenameonename'\n",
    "for character in name:\n",
    "    if character in anothername:\n",
    "        print(character)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Break\n",
    "\n",
    "If you want to end the loop we can use the break construct."
   ]
  },
  {
   "cell_type": "code",
1570
   "execution_count": 391,
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in range(0,10):\n",
    "    if (i==5):\n",
    "        break\n",
    "\n",
    "x = 5\n",
    "while True:\n",
    "    x -= 1\n",
    "    if (x==1):\n",
    "        break"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let’s write Fibonacci for loop:"
   ]
  },
  {
   "cell_type": "code",
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
   "execution_count": 392,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 1\n",
      "1 2\n",
      "1 3\n",
      "2 5\n",
      "3 8\n",
      "5 13\n",
      "8 21\n",
      "Seventh Fibonacci number is 21\n"
     ]
    }
   ],
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
   "source": [
    "def fib(input):\n",
    "    if (input <=1):\n",
    "        return(str(input))\n",
    "    else:\n",
    "        first = 0\n",
    "        second = 1\n",
    "        count = 0\n",
    "        for count in range(input):\n",
    "            result = first + second\n",
    "            print(first,result)\n",
    "            first = second\n",
    "            second = result\n",
    "            count = count+1\n",
    "        return(str(result))\n",
    "\n",
    "#print statement will output the correct fib value\n",
    "print('Seventh Fibonacci number is',fib(7))"
1630
   ]
Simon Clarke's avatar
Simon Clarke committed
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
  }
 ],
 "metadata": {
  "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"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}