Newer
Older
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Notebook 1 - Programming with Python recap\n",
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
"\n",
"Although this course assumes that you have basic knowledge of Python, in this notebook will be a quick recap of the fundamentals of computer programming which will be needed for the rest of the course. The notebook will cover:\n",
"- [Types](#types)\n",
"- [Arithmetic operations](#arith)\n",
"- [Boolean logic](#boolean)\n",
"- [Printing](#print)\n",
"- [High level data structures](#hi-data)\n",
"- [If-Else](#if)\n",
"- [Loops](#loops)\n",
"- [Functions](#func)\n",
"- [Exercises](#exercise)\n",
"\n",
"You are intended to skim over this notebook and do the exercises at the end. Afterwards you can proceed to the next notebook.\n",
"\n",
"Estimated duration: 30 min\n",
"\n",
"You can use this notebook as a reference for the duration of the course."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Types <a name=\"types\"></a>\n",
"| Type | Declaration | Example | Usage |\n",
"|----|----|----|----|\n",
"| Integer | int | `x = 124` | Numbers without decimal point |\n",
"| Float | float | `x = 124.56` | Numbers with decimcal point |\n",
"| String | str | `x = \"Hello world\"` | Used for text |\n",
"| Boolean | bool | `x = True` or `x = False` | Used for conditional statements |\n",
"| NoneType | None | `x = None` | Whenever you want an empty variable |\n",
"\n",
"You can convert from one type to another:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x = 10 # This is an integer\n",
"y = \"20\" # This is a string\n",
"x + int(y)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can find the type of a variable using the `type()` function:"
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
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"var = 13.4\n",
"type(var)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Arithmetical operators <a name=\"arith\"></a>\n",
"\n",
"Python supports a range of different arithmetical operators:\n",
"\n",
"| Symbol | Task Performed | Example | Result\n",
"|----|---|---|---|\n",
"| + | Addition | 4 + 3 | 7 |\n",
"| - | Subtraction | 4 - 3 | 1 |\n",
"| / | Division | 7 / 2 | 3.5 |\n",
"| % | Mod | 7 % 2 | 1 |\n",
"| * | Multiplication | 4 * 3 | 12 |\n",
"| // | Floor division | 7 // 2 | 3 |\n",
"| ** | Power of | 7 ** 2 | 49 |"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"16 ** 2 / 4"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Boolean logic <a name=\"boolean\"></a>\n",
"| Operator | Output | \n",
"|----|---|\n",
"| x == y | True if x and y have the same value |\n",
"| x != y | True if x and y don't have the same value |\n",
"| x < y | True if x is less than y |\n",
"| x > y | True if x is more than y |\n",
"| x <= y | True if x is less than or equal to y |\n",
"| x >= y | True if x is more than or equal to y |\n",
"\n",
"Make note that these operators return Boolean values (ie. `True` or `False`). Naturally, if the operations don't return `True`, they will return `False`. Let's try some of them out:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x = 5 # assign 5 to the variable x\n",
"x == 5 # check if value of x is 5"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x > 7"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"That is nice! How can we extend this to link multiple combinations like that? Luckily, Python offers the usual set of **logical operations**:\n",
"\n",
"| Operation | Result | \n",
"|----|---|\n",
"| x or y | True if at least on is True |\n",
"| x and y | True only if both are True |\n",
"| not x | True only if x is False |\n",
"\n",
"\n",
"\n",
"With this, we can now chain different boolean operations:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# check if x is divisible by both 2 and 3\n",
"x = 42\n",
"( x % 2 == 0 ) and ( x % 3 == 0)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Printing <a name=\"print\"></a>\n",
"Output text to the user of the program"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(\"Python is powerful!\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x = \"Python is powerful\"\n",
"y = \" and versatile!\"\n",
"print(x + y)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"str1 = \"The string has\"\n",
"str2 = 76\n",
"str3 = \"methods!\"\n",
"print(str1, str2, str3)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Furthermore, there is also a way to insert variables inbetween text using placeholders like `%d` which stands for decimal. As seen from the code cell below, this is an extremely compact and easy way to print. "
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
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"num = 12\n",
"print(\"You can also include a number like %d like this.\" %num)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x = \"\"\"To include\n",
"multiple lines\n",
"you have to do this\"\"\"\n",
"y =\"or you can also\\ninclude the special\\ncharacter `\\\\n` between lines\"\n",
"print(x)\n",
"print(y)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# High level data structures <a name=\"hi-data\"></a>\n",
"## Lists <a name=\"lists\"></a>\n",
"Probably the most commonly used data structure in Python. Lists simply group multiple variables together."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fruits = [\"apple\", \"orange\", \"tomato\", \"banana\"] # a list of strings\n",
"print(type(fruits))\n",
"print(fruits)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can access each individual item within the list by **indexing** it.\n",
"\n",
"Recall that indices **start from 0**.\n",
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
"\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(fruits[0])\n",
"print(fruits[2])\n",
"print(fruits[-1])\n",
"print(len(fruits))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can modify existing lists as:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fruits.append(\"lime\") # add new item to list\n",
"print(fruits)\n",
"fruits.append(\"orange\")\n",
"print(fruits)\n",
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
"fruits.remove(\"orange\") # remove orange from list\n",
"print(fruits)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"That seems useful! Can we do the same with integers? Python actually offers various functions for generating numerical lists. The most useful out of which is:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"nums = list(range(10))\n",
"print(nums)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can also get only a part of a list you have already created. This is called **slicing** and can be done in various different ways:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(nums[0:3])\n",
"print(nums[4:])\n",
"print(nums[-1])\n",
"print(nums[::-1])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# If Else <a name=\"if\"></a>\n",
"The statement after `if` must evaluate to a Boolean value (`True` or `False`), if it is `True` then we execute the code between the `if` and `else` statements and skip the code after the else statement. If the Boolean expression after `if` evaluates to `False` then we skip the code between `if` and `else` and execute only the code after `else`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x = True\n",
"if x:\n",
" print(\"Executing if\")\n",
"else:\n",
" print(\"Executing else\")\n",
"print(\"Prints regardless of the outcome of the if-else block\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Try changing the value of x to `False`.\n",
"\n",
"if-else statements can also be extended with `elif` which as implied combines both else + if = elif. This is useful if you want to have multiple conditions for example:\n",
"\n",
"Let us illustrate this in an elaborate example. Imagine you have purchased a stock and are looking to make a profit out of it."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"purchasePrice = float(input(\"Price at which you have purchased bitcoins: \"))\n",
"currentPrice = float(input(\"Current price of the bitcoins: \"))\n",
"\n",
"if currentPrice < purchasePrice*0.9:\n",
" print(\"Not a good idea to sell your bitcoins now.\")\n",
" print(\"You will lose\", purchasePrice - currentPrice, \"£ per bitcoin.\")\n",
"elif currentPrice > purchasePrice*1.2:\n",
" print(\"You will make\", currentPrice - purchasePrice, \"£ per bitcoin.\")\n",
"else:\n",
" print(\"Not worth selling right now.\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Loops <a name=\"loops\"></a>\n",
"\n",
"## for\n",
"Generally useful whenever you want to iterate over a list (or other data structure) of items and apply the same operation to all items within it. In general, `for` loops look like this and have indentation just like if-else statements:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fruitList = [\"apple\", \"orange\", \"tomate\", \"banana\"]\n",
"for fruit in fruitList:\n",
" print(\"The fruit\", fruit, \"has index\", fruitList.index(fruit))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
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
"for num in numbers:\n",
" squared = num ** 2\n",
" print(num, \"squared is\", squared)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## while\n",
"Another useful loop which is a bit less controllable. It executes over and over until its condition becomes false. For example, we can make a loop that executes 5 times and then stops."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"n = 0\n",
"while n < 5:\n",
" print(\"Executing while loop\")\n",
" n = n + 1\n",
"\n",
"print(\"Finished while loop\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## break\n",
"Not a loop but extremely useful within loops! As implied `break` literally breaks the loop and forces the program to go out of it. We can redo our `while` loop example using `break`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"n = 0\n",
"while True: # execute indefinitely\n",
" print(\"Executing while loop\")\n",
" \n",
" if n == 5: # stop loop if n is 5\n",
" break\n",
" \n",
" n = n + 1\n",
"\n",
"print(\"Finished while loop\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Functions <a name=\"func\"></a>\n",
"Also referred to as methods, functions are effectively small programs that take in arguments(ie. inputs) and return values(outputs).\n",
"\n",
"Functions are an incredibly useful concept since they allow us to package functionality in a convenient and easy to read manner and reproduce the same result without having to write it again and again. A quick example:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def printNum(num):\n",
" print(\"My favourite number is\", num)\n",
" \n",
"printNum(7)\n",
"printNum(14)\n",
"printNum(2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Rule of thumb - if you are planning on using very similar code more than once, it may be wortwhile writing it as a reusable function. \n",
"\n",
"Some examples:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def roundNum(num):\n",
" remainder = num % 1\n",
" if remainder < 0.5:\n",
" return num - remainder\n",
" else:\n",
" return num + (1 - remainder)\n",
"\n",
"# Will it work?\n",
"x = roundNum(3.4)\n",
"print (x)\n",
"\n",
"y = roundNum(7.7)\n",
"print(y)\n",
"\n",
"z = roundNum(9.2)\n",
"print(z)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The number of arguments is by no means limited to 1. Actually it is infinite! A function can have any number of arguments using `*args` but bear in mind that this also can make it less controllable. With this knowledge we can make a function that simply adds up all of its inputs."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def sum(*args):\n",
" result = 0\n",
" for num in args:\n",
" result = result + num\n",
" return result\n",
" \n",
"print(sum(5, 6, 7, 8, 9))\n",
"print(sum(1, 2, 5, 10, 20, 34))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Exercise <a name=\"exercise\"></a>\n",
"\n",
"## 1. Fibonacci\n",
"Create a function `fibonacci()` which takes an integer `num` as an input and returns a list of the first `num` fibonacci numbers.\n",
"\n",
"Eg.\n",
"\n",
"Input: `8`\n",
"\n",
"Output: `[1, 1, 2, 3, 5, 8, 13, 21]`\n",
"\n",
"*Hint: You might want to recall [fibonacci numbers](https://en.wikipedia.org/wiki/Fibonacci_number)*"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def fibonacci(num):\n",
" # [ WRITE YOUR CODE HERE ]\n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Check your answer by running the code cell below."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"################ Checking code ########################\n",
"# Please don't edit this code\n",
"newList = fibonacci(10)\n",
"if newList == [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]:\n",
" print(\"Success!\")\n",
"else:\n",
" print(\"Error! Your function returned\")\n",
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2. Guessing game\n",
"Ask the user to input a number within [0, 100] and then have the program guess it. After each guess, the user must input whether it was too high, too low or the correct number. In the end, the program must always guess the users number and it must print out the number of guesses it needed.\n",
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
"\n",
"_Note: You can use `random.randint(0,100)` to generate the random number but don't forget to also import the package via `import random as random`_\n",
"\n",
"_Note2: You can use `input()` to ask the user for a number_"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"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",