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
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"run_control": {
"frozen": true
}
},
"source": [
"# Inputs and variables\n",
"\n",
"**Learning goals:**\n",
"\n",
"* Create programs where the user passes text to the program using input()\n",
"\n",
"* Simple use of variables\n",
"\n",
"* Correct naming of variables\n",
"\n",
"**Starting Out with Python:**\n",
"\n",
"* Chapt. 2.2\n",
"\n",
"* Chapt. 2.5-2.6"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"heading_collapsed": true,
"run_control": {
"frozen": true
}
},
"source": [
"## **Tutorial part 1: The function input()**"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"hidden": true,
"run_control": {
"frozen": true
}
},
"source": [
"**Why do we need input?** In a lot of programs, it is important that the user can give input. In a web shop, the user must be able to select products, input the address to which it will be sent, payment options, etc.\n",
"\n",
"There are many ways of giving input, for instance through touch screens, mouse, or using voice. Here you are going to learn the way which is the easiest to program; text input from the keyboard.\n",
"In Python this is done using the function `input()`. Similarly to `print()`, this is a function in the standard library of Python.\n",
"Run the code below, then you will see some important differences between print() and input().\n",
"\n",
"**print() and input()**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"hidden": true
},
"outputs": [],
"source": [
"print(\"print() prints out text to the screen and adds a new line.\")\n",
"input(\"input() awaits user input finished by Enter: \")\n",
"print(\"print() can have\", \"many texts\", \"separated by comma\")\n",
"input(\"input() only allows one text! OK? \")"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"hidden": true,
"run_control": {
"frozen": true
}
},
"source": [
"The one text `input()` can contain, is the so-called **prompt** which explains to the user the expected input.\n",
"The prompt should be precise enough so that the user knows what details are being requested.\n",
"For instance, \"Input the weight in kg: \" is a better prompt than \"Input weight: \", which again is much better than \"Input a number: \" or \"Give input: \".\n",
"Whitespace at the end of the prompt is recommended, otherwise the input cursor of the user will appear in the prompt. In the small example above, we did not use the result from `input()`. However, normally we ask the user for input because it it is needed for something. For a little useful example, assume we want to ask the user about their name - and then use this name in a subsequent print statement, then we get a small dialogue between the user and the program:\n",
"\n",
"```\n",
"Hello, what is your name? Nina \n",
"Nina - that is a nice name. \n",
">>>\n",
"```\n",
"\n",
"Here the program asks the user \"Hello, what is your name?\", the user responds with \"Nina\" and the machine printes out \"Nina - that is a nice name.\"\n",
"This small dialogue can be accomplished with the following line of code:\n",
"\n",
"**Simple dialogue with user:**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"hidden": true
},
"outputs": [],
"source": [
"print(input(\"Hello, what is your name? \"), \"- that is a nice name.\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"hidden": true,
"run_control": {
"frozen": true
}
},
"source": [
"This code works because parentheses are always executed from the inside out. The print statement cannot be run until it knows what to print. Therefore, the input statement is ran first, it returns the name the user input as the result (e.g. Nina). This name is subsequently printed out with the following text \"- that is a nice name.\""
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"run_control": {
"frozen": true
}
},
"source": [
"## a) Simple use of input directly in a print() statement"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"run_control": {
"frozen": true
}
},
"source": [
"Use the tutorial code below (and run it once to see how it works; if you do not understand it, read the tutorial first)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(input(\"Hello, what is your name? \"), \"- that is a nice name.\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"run_control": {
"frozen": true
}
},
"source": [
"Modify the text strings in this line of code such that the dialogue with the user instead becomes as shown below. The program is always going to repeat the name from the user input, Nina is just an example.\n",
"```\n",
"Navn? Nina \n",
"Nina - cool name!\n",
"```\n",
"Add a new, similar line of code which asks the user about their favorite course. Once the program is finished, the dialogue should look as shown below.\n",
"The output of the program should of course depend on the user input, which is their name and favorite course.\n",
"\n",
"```\n",
"Name? Per\n",
"Per - cool name! \n",
"Favorite course? Ex.phil. \n",
"Ex.phil. - interesting!\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"heading_collapsed": true,
"run_control": {
"frozen": true
}
},
"source": [
"## Tutorial part 2: variables - basic information"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"hidden": true,
"run_control": {
"frozen": true
}
},
"source": [
"Why do we need variables? The point of variables is to **remember data on the way** during the execution of a program.\n",
"\n",
"As such, variables are a central concept in programming, not just in Python, but any programming language.\n",
"\n",
"Without variables, we quickly face a series of problems because our program cannot remember anything, for instance that:\n",
"\n",
"* we must ask the user to give details they have already given\n",
"* we must evaluate data we have already evaluated earlier\n",
"\n",
"This wastes time and electricity, and will in many cases make the program completely useless.\n",
"\n",
"In the small example program in tutorial part 1, we did not need to use any variables, because the name we got from the user was only every used once, and this happened immediately after it was input.\n",
"\n",
"```python\n",
"print(input(\"Hello, what is your name? \"), \"- that is a nice name.\") \n",
"```\n",
"\n",
"```\n",
"Hello, what is your name? Nina \n",
"Nina - that is a nice name. \n",
">>>>\n",
"```\n",
"\n",
"Oftentimes, the same data is going to be reused, and after we have done different things in the mean time. In that case, data must be remembered/stored in a variable. Assume we want a litle more advanced dialogue with the user:\n",
"\n",
"```\n",
"Hello, what is your name? Nina \n",
"Nina - that is a nice name.\n",
"Good luck with ITGK, Nina! \n",
">>>>\n",
"```\n",
"\n",
"Here want to use the name which was input in two subsequent print statements. If we try the same trick as before by putting the input statement directly within the print statement, we get the following code:\n",
"\n",
"```python\n",
"print(input(\"Hello, what is your name? \"), \"- that was a nice name.\")\n",
"print(\"Good luck with ITGK,\", input(\"Hello, what is your name? \")) \n",
"```\n",
"\n",
"The execution below, demonstrates the issues with the code; that is the question \"Hello, what is your name?\" occurs twice.\n",
"\n",
"```\n",
"Hello, what is your name? Nina\n",
"Nina - that is a nice name.\n",
"Hello, what is your name? Nina\n",
"Good luck with ITGK, Nina\n",
"```\n",
"\n",
"\n",
"Not a major issue here, but imagine a program where the same data is used, perhaps 100 times or more, in a critical task which needs to completed quickly.\n",
"\n",
"Can we solve this in a better way? YES - with a variable in order to remember the name. The code then becomes"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"hidden": true
},
"outputs": [],
"source": [
"name = input(\"Hello, what is your name?\")\n",
"print(name, \"- that is a nice name.\")\n",
"print(\"Good luck with ITGK,\", navn)"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"hidden": true,
"run_control": {
"frozen": true
}
},
"source": [
"This program can be explained as follows:\n",
"* line 1, to the right of `=` : uses `input()` to ask the user for their name\n",
"* line 1, to the left of `=` : creates a variable named `name`.\n",
"* line 1, the sign `=`. This is the **assignment operator**. This means that the value of the expression on the right, the result of `input()`, is stored in the variable named `name`. If the user writes Nina, the variable `name` will then contain the string `'Nina'`\n",
"* line 2, the variable `name` is used at the start of the print statement. Note that the variable name should **not** be enclosed in quotes. With quotes, it would instead have printed \"name - that is a nice name.\". The word at the end of the sentence \"that is a nice name.\" is not the variable. Here the word 'name' is just a part of the text string.\n",
"* line 3, the variable `name` is used at the end of the print statement. Again, without quotes; it is not the word 'name' we want to print, but the text string which the variable `name` contains (e.g. Nina)\n",
"\n",
"Using the variable which here is called name, you avoid the need to ask the same question twice. We ask only once, at the start of the program, and remember the data the user gives us by storing it in a variable.\n",
"\n",
"Later on in the program, we can use this variable every time we need the name - either, as in this example, only twice, or several times."
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"run_control": {
"frozen": true
}
},
"source": [
"## b) Storing input in a variable"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"run_control": {
"frozen": true
}
},
"source": [
"Run the code below in order to see how it works. As you will notice, it bothers the user by repeating both questions twice.\n",
"\n",
"Improve the code by introducing a variable for name and another for favorite course, so that the user only gets asked each question once.\n",
"\n",
"If you are in doubt as to how you should attack the problem, see similar examples in the tutorial just above."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(\"Hello,\", input(\"Name? \"))\n",
"print(input(\"Favorite course? \"), \"- interesting!\")\n",
"print(\"Have a nice day,\", input(\"Name? \"))\n",
"print(\"- and good luck with\", input(\"Favorite course? \"))"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"run_control": {
"frozen": true
}
},
"source": [
"If you manage to use the variables as intended, the execution of the improved program should look as follows (but also work if the user inputs something other than Ada in the question Name? and something different than ITGK in Favorite course?\n",
"```\n",
"Name? Ada \n",
"Hello, Ada \n",
"Favorite course? ITGK \n",
"ITGK - interesting! \n",
"Have a nice day, Ada \n",
"- and good luck with ITGK\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"heading_collapsed": true,
"run_control": {
"frozen": true
}
},
"source": [
"## Tutorial part 3 - Using variables in calculations"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"hidden": true,
"run_control": {
"frozen": true
}
},
"source": [
"Variables are not only used with regards to `input()`, but all sorts of programs. In mathematical calculations, the result of one calculation is often used in subsequenet new calculations. In this case, the numbers must be stored in variables. The code below shows the same example done in two ways, which is evaluating the area of a circle, and the volume of a cylinder that has this circle as its base. Version 1 is done without variables, while Version 2 uses variables.\n",
"\n",
"**Circle and cylinder**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"hidden": true
},
"outputs": [],
"source": [
"import math\n",
" \n",
"# VERSION 1, without variables\n",
"print(\"Area of the circle:\", math.pi * 5.4**2)\n",
"print(\"Volume of the cylinder:\", math.pi * 5.4**2 * 7.9)\n",
" \n",
"print()\n",
" \n",
"# VERSION 2, with variables\n",
"r = 5.4 # radius of a circle.\n",
"A_circle = math.pi * r**2\n",
"print(\"Area of the circle:\", A_circle)\n",
"h = 7.9 # height of the cylinder where the circle is the base.\n",
"V_syl = A_circle * h\n",
"print(\"Volume of the cylinder:\", V_syl)"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"hidden": true,
"run_control": {
"frozen": true
}
},
"source": [
"If you run the code, you will see that both give the same result. What is the difference?\n",
"\n",
"* Version 2 is significantly longer (6 lines of code, versus 2) because extea lines are used on the variables. Longer code is a possible disadvantage. \n",
"\n",
"**However**:\n",
"* The formulae in Version 2 are easier to understand because there are variables with intuitiv names such as `r`, `h`, `A_circle` rather than just numbers directly.\n",
"* The code in V2 is more flexible in the sense that instead of having to change every occurence of a value, you only change the variable once. If you want to set the radius to 6.2 instead of 5.4, this number must only be changed one place in V2 (at the variable assignment), while multiple places in V1.\n",
"* Version 1 performs **5 operations** of type `*` and `**`, while Version 2 only performs ***3***. This is because Version 2 remembers the area in `A_cirlce` and uses it in the subsequent calculation of the volume. On the other hand, Version 1 must evaluate `math.pi * 5.4**2` twice.\n",
"\n",
"**With fewer multiplications, VERSION 2 will both save electricity and time compared to VERSION 1, i.e. the code does less work and executes faster even though there are more lines of code.**"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"run_control": {
"frozen": true
}
},
"source": [
"## c) Using variables in calculations"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"run_control": {
"frozen": true
}
},
"source": [
"Given below is a program in which we evaluate the circumference and area of a circle using the well known formulae O=2πr and A = πr2. We are not using any variables, aside from the built in constants `math.pi` and `math.tau`(=2π).\n",
"As such when we want to evaluate the area of a cylinder where the circle is the base, we have to repeat several calculations which we have done prior.\n",
"\n",
"The area of the cylinder with height h will be `Circumference_Circ * h + 2 * Area_Circ`, where the first term is the area of the cylinder wall and the final term is the top and bottom cap.\n",
"\n",
"***Task: Modify the code by assigning and using variables for the radius, height, circumference and area of the circle, in order for the program to reuse calculations.***"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"ExecuteTime": {
"end_time": "2019-07-01T10:54:16.358742Z",
"start_time": "2019-07-01T10:54:16.351684Z"
}
},
"outputs": [],
"source": [
"import math\n",
" \n",
"print(\"Have a circle with radius \", 5.4, \"which is the base of a cylinder with height \", 7.9)\n",
"print(\"Circumference of the circle:\", math.tau * 5.4) #tau = 2pi\n",
"print(\"Area of the circle:\", math.pi * 5.4**2)\n",
"print(\"Area of the cylinder:\", math.tau * 5.4 * 7.9 + 2 * math.pi * 5.4 ** 2)"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"run_control": {
"frozen": true
}
},
"source": [
"The result of the execution of the code should remain unchanged, i.e. the output should be as shown below (but if you want to, you can also round the answers to one decimal point).\n",
"\n",
" \n",
"```\n",
"Have a circle with radius 5.4 which is the base of a cylinder with height 7.9\n",
"Circumference of the circle: 33.929200658769766\n",
"Area of the circle: 91.60884177867838\n",
"Area of the cylinder: 451.25836876163794\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"heading_collapsed": true,
"run_control": {
"frozen": true
}
},
"source": [
"## Tutorial part 4: Naming variables"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"hidden": true,
"run_control": {
"frozen": true
}
},
"source": [
"A variable is a name that represents a value which is stored in the memory of the computer. The most common way to create a variable is using an assignment statement:\n",
"\n",
"`variable = expression`\n",
"\n",
"\n",
"In this case, 'variable' is the name of the variable, while 'expression' is the value. A few rules for such assignment statements:\n",
"\n",
"* the variable which is created must always be on the left side of the statement, and the left side should only contain this variable, nothing else.\n",
"* the right side could be anything from a simple value (e.g. a number) or a simple variable, to complex composite expressions that must be evaluated. If the right side contains variables, this must be variables that have been created earlier in the code.\n",
"* the variable name must satisfy the following constraints:\n",
" * words that are reserved in Python, e.g. `if`, `def`, or names of standard functions such as `print`, `min`, `max`, ... should not be used as variable names.\n",
" * variable names must begin with a letter or the character _ (underscore)\n",
" * otherwise they may contain letters, numbers and underlines, i.e. it cannot for instance contain blank space.\n",
"* Python differenciates between lower-case and upper-case letters, i.e. `Area` and `area` would be two different variables.\n",
"\n",
"It is recommended to use variable names which are intuitive to understand, for instance `area` is a better name than `x` for a variable which contains an area. Composite variable names is typically written in camelCase or with an underscore to show where each word ends and the next begins, for instance `startTime`, `pricePerLiter` or `start_time`, `price_per_liter`, because directly concatentating the words would be hard to read.\n",
"\n",
"The code block below demonstrates examples of variable names which do and do not work."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"hidden": true
},
"outputs": [],
"source": [
"# Example of valid variable assignments\n",
"pokemon_name = \"Tyranitar\"\n",
"MaxCP = 3670\n",
"amount = 3\n",
"amount = amount + 1 # right side is evaluated as 3 + 1, as such 4 is the new value of the variable 'amount'\n",
"resists_fighting = False\n",
"level42 = \"to be done\" # numbers are allowed as long as the first character is a letter or _.\n",
" \n",
"# Example of INVALID variable assignments\n",
"1 = amount # the variable must be on the left side\n",
"amount + 1 = amount # and the left side may ONLY contain a variable name, and not larger expressionsog\n",
"10fight = \"fun\" # variables cannot begin with a number, only a letter or _\n",
"amount = 3 # this is OK, but see the next line.\n",
"amount = Amount + 1 # Python differentiates between upper-case and lower-case letters.'Amount' will be\n",
" # a different variable and complains about NameError here because 'Amount' is\n",
" # has not been created prior in the code.\n",
"happy hour = 20 # names cannot contain spaces, should be happy_hour or happyHour\n",
"alkohol% = 4.5 # % (meaning modulo) may not be used in variable names. Same goes for other\n",
" # special characters. Stick to letters and numbers."
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"run_control": {
"frozen": true
}
},
"source": [
"## d) Variable names"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"run_control": {
"frozen": true
}
},
"source": [
"Attempt to run the code below. As you will see, it does not work because of various mistakes in the variable names and assignment statements. Fix the mistakes so that the program runs"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"1name = \"Per\"\n",
"ideal age = 42\n",
"37 = customersAge\n",
"difference = ideal age - customersAge\n",
"print(1name, \"is\", difference, \" years away the ideal age\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"run_control": {
"frozen": true
}
},
"source": [
"## e) Variable program"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"run_control": {
"frozen": true
}
},
"source": [
"Create a program in the code block below which first stores your name in a variable and your age in a different variable, and then print it out with the `print()` function. Here you do not need to use the `input()` function!\n",
"\n",
"Example run:\n",
"```\n",
"My name is Bob Bernt, and I am 46 years old.\n",
"```\n",
"\n",
"***Write your code in the block below.***"
]
},
{
"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",
"version": "3.7.4"
},
"toc": {
"base_numbering": 1,
"nav_menu": {},
"number_sections": false,
"sideBar": true,
"skip_h1_title": false,
"title_cell": "Table of Contents",
"title_sidebar": "Contents",
"toc_cell": false,
"toc_position": {},
"toc_section_display": true,
"toc_window_display": false
}
},
"nbformat": 4,
"nbformat_minor": 2
}