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
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"run_control": {
"frozen": true
}
},
"source": [
"\n",
"\n",
"# Converting numbers\n",
"\n",
"**Learning goals:**\n",
"\n",
"* Converting between datatypes by using standard functions like int() and float()\n",
"\n",
"* To understand the definition of integers and floating point numbers\n",
"\n",
"**Starting Out with Python:**\n",
"\n",
"* Chapter. 2.6\n",
"\n",
"* Chapter. 2.8"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"heading_collapsed": true,
"run_control": {
"frozen": true
}
},
"source": [
"## Tutorial part 1: Converting between datatypes"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"hidden": true,
"run_control": {
"frozen": true
}
},
"source": [
"We can have different types of data, like text strings (e.g. `\"Python\"`), integers (e.g. `42`), floats (e.g. `9.80`) and Booleans (`True`, `False`). We are often in a situation where we have data as one datatype, but we now need the same data as a different type. That means that the data needs to be converted. Some common convertion functionsa:\n",
"\n",
"**`int()`** - Converts to integer\n",
"- `int('423')` gives 423 (meaning that the string is converted into a number). Only works if the string contains whole numbers.\n",
"- `int(5.69)` gir 5 (the decimal part of floats gets removed)\n",
"\n",
"**`float()`** - Converts to float\n",
"- `float('5.69')` gives 5.69 (text string is converted to a number)\n",
"- `float('5')` gives 5.0, meaning that float() works on text string containg either floats or ingegers (does not work on strings that are not numbers)\n",
"- `float(5)` gives 5.0\n",
"\n",
"**`str()`** - Converts to string\n",
"- `str(42)` gives '42'\n",
"- `str(5.69)` gives '5.69'\n",
"The code below fails to run because we have not converted. Try to run it."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"hidden": true
},
"outputs": [],
"source": [
"age = input(\"How old are you?\")\n",
"aage_mother = input(\"How old is your mother?\")\n",
"sum_age = age + age_mother\n",
"print(\"Congratulations! You are\", sum_age, \"years!\")\n",
"answer = input(\"How does it feel to be \", sum_age, \"? \")"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"hidden": true,
"run_control": {
"frozen": true
}
},
"source": [
"An example of running:\n",
" \n",
" \n",
"```python\n",
"How old are you? 13\n",
"How old is your mother? 37\n",
"Congratulations! You are 1337 years!\n",
"Traceback (most recent call last):\n",
" File \"/Users/guttorm/Documents/tut2.py\", line 5, in <module>\n",
" answer = input(\"How does it feel to be \", sum_age, \"? \")\n",
"TypeError: input expected at most 1 arguments, got 3\n",
">>>\n",
"```\n",
"\n",
"The first error shows up in the line \"Congratulations...\" The sum should be 50 years. However, the numbers are still stored as text strings. For strings `+` puts the two strings next to each other, it does not do numerical addition. Meaning that we get `'13' + '37'` to be `'1337'` rather than `13 + 37` to be `50`. We need to convert from text to numbers before doing the addition.\n",
"\n",
"The next error comes in the input statement. In `print()` we are allowed to list many arguments, both text and numbers, separated by commas. In an `input()` statement however, only one argument is allowed. This argument needs to be a text string. This is why we get the error: \"input expected at most 1 arguments, got 3\". To be able to ask our question, while still providing only one argument to the input function (\"How does it feel to be 50?\" if the sum is 50) - we need to add the parts together to one text string rather than separating the parts with a comma. `input(\"How does it feel to be\" + sum_age + \"? \")` will not work if sum_age is a number, we can't add text and numbers. Two texts can be added however. If we convert `sum_age` to tekst it is going to work. Fixed code is shown below:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"hidden": true
},
"outputs": [],
"source": [
"age = int(input(\"How old are you?\"))\n",
"age_mother = int(input(\"How old is your mother?\"))\n",
"sum_age = age + age_mother\n",
"print(\"Congratulations! You are\", sum_age, \"years!\")\n",
"answer = input(\"How does it feel to be \" + str(sum_age) + \"? \")"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"hidden": true,
"run_control": {
"frozen": true
}
},
"source": [
"To summarize: we use `int()` in line 1 and 2, this gives us integers in the variables `age` and `age_mother` so we can calculate with them. We then use `str()` in line 5 so we can put this together with another string and use it for a new `input()`. This example shows both a situation where we have text and need it to be a number, and a situation where we have a number that we need to be a text. If the user inputs a decimal number for the age (e.g. `13.5`) the code above will not work. In that case, we need to use `float()` instead of `int()`."
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"run_control": {
"frozen": true
}
},
"source": [
"## a)"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"run_control": {
"frozen": true
}
},
"source": [
"Ask the user to input 3 floating point numbers. Convert the strings to floats using `float()`, then use `int()` and convert them to integers. Ask the user to input an integer and use `float()` to convert it into a decimal number."
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"run_control": {
"frozen": true
}
},
"source": [
"Example of correctly running program:\n",
"\n",
"\n",
"```python\n",
"Input a decimal number: 4.232443\n",
"Input another decimal number: 3.24324\n",
"Input your last decimal number: 1.22342454\n",
"Converted to integers gives: 4 3 1\n",
"Input an integer: 13\n",
"Converting to a floating point number gives: 13.0\n",
"```\n",
"\n",
"***Write your code in the block below:***"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"ExecuteTime": {
"end_time": "2019-07-01T11:24:13.550825Z",
"start_time": "2019-07-01T11:24:13.542723Z"
}
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"heading_collapsed": true,
"run_control": {
"frozen": true
}
},
"source": [
"#### Hint"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"hidden": true,
"run_control": {
"frozen": true
}
},
"source": [
"Each time the user is asked for something, the `input()` function is used. Remember to have the function in an `int()` statement if you are asking for an integer, and in a `float()` statement if it is a decimal number. A text string containing floats, e.g. `\"4.325\"`, can't be converted directly to an integer. Meaning that `int(\"4.325\")` wil throw an error. feilmelding. If you want to convert an input of this type to an integer, you need to first convert the string to a float, then convert from a float to an int."
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"run_control": {
"frozen": true
}
},
"source": [
"## b)"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"run_control": {
"frozen": true
}
},
"source": [
"Write a program that asks the user for name, age and how old the user was when he or she started programming. An example of running such a program is shown below, *Martin, 21*, *19* amd *Yes* at the end of lines 1, 2, 3 og 5 are user inputs, while the rest is printed by the machne. Make the program so that it adapts to the data that it is given. (Look at the tutorial above if you get stuck)\n",
"\n",
"Example of program running:\n",
" \n",
"```\n",
"Write your name: Martin\n",
"Hi, Martin, how old are you? 21\n",
"How old where you when you started programming? 19\n",
"You have been programming for 2 years.\n",
"Did you find those 2 years to be rewarding? Yes\n",
"Thank you for your answer Martin!\n",
"```\n",
"\n",
"***Write your code in the block below.***"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"heading_collapsed": true,
"run_control": {
"frozen": true
}
},
"source": [
"## Tutorial part 2: int() vs. round()"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"hidden": true,
"run_control": {
"frozen": true
}
},
"source": [
"We often have floats when what we need is integers, e.g. when we want to use Python-functions that require integers as arguments, or when we want to use a number as an index for a string or a list (we will get back to this later in the course). Floats can be converted to integers with functions like `int()` or `round()`. The block below shows some of the differences between these functions."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"hidden": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"int() cuts off the decimals, no matter how large they are:\n",
"int(2.25) is 2\n",
"int(2.5) is 2\n",
"int(2.99) is 2\n",
"round() rounds to the closest integer e.g.\n",
"round(2.25) is 2\n",
"round(2.51) is 3\n",
"Hva hvis tallet er midt mellom to heltall?\n",
"round(2.5) is 2\n",
"round(3.5) is 4\n",
"round() bruker en IEEE standard som velger partallet for midt-imellom-situasjoner.\n",
"Mens int() alltid gir heltall kan round() brukes for antall desimaler:\n",
"round(2.5488, 1) gives 2.5\n",
"round(2.5488, 3) gives 2.549\n",
"Med negativt antall desimaler kan vi få round() til å runde større enn heltall:\n",
"round(12345.67, -3) gives 12000.0\n"
]
}
],
"source": [
"print(\"int() cuts off the decimals, no matter how large they are:\")\n",
"print(\"int(2.25) is\", int(2.25))\n",
"print(\"int(2.5) is\", int(2.5))\n",
"print(\"int(2.99) is\", int(2.99))\n",
"print(\"round() rounds to the closest integer e.g.\")\n",
"print(\"round(2.25) is\", round(2.25))\n",
"print(\"round(2.51) is\", round(2.51))\n",
"print(\"What if the number is right between two integers?\")\n",
"print(\"round(2.5) is\", round(2.5))\n",
"print(\"round(3.5) is\", round(3.5))\n",
"print(\"round() uses IEEE standard to choose in these situations.\")\n",
"print(\"Mens int() always gives an integers, round() can be used to give a certain number of decimals:\")\n",
"print(\"round(2.5488, 1) gives\", round(2.5488, 1))\n",
"print(\"round(2.5488, 3) gives\", round(2.5488, 3))\n",
"print(\"With a negative amount of decimals, we can use round() for courser rounding than the nearest integer:\")\n",
"print(\"round(12345.67, -3) gives\", round(12345.67, -3))"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"hidden": true,
"run_control": {
"frozen": true
}
},
"source": [
"As you saw in the example above, 2.5 is rounded to 2 while 3.5 is rounded to 4. This probably looks a bit strange compared to the type of rounding we often do in dayly life shopping where we always round up if we are exactly between two integers (meaning that 2.5 should have been rounded to 3). This type of rounding leads to a problem however, we get a systematic error if we have large amounts of data that is rounded. Think about for instance finding the average of temperature measurements over long periods of time. If we round up every time a temperature right in between, the average for the period will always be a bit too high. If we instead round to the side with an even number in these cases, we will round down about half the time, and up the other half. This helps us avoid systematic errors. For daily shopping however, a systematic error from rounding up is to the sellers advantage."
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"run_control": {
"frozen": true
}
},
"source": [
"## c)"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"run_control": {
"frozen": true
}
},
"source": [
"Ask the user for a floating point number with at least 5 digits both before and after the decimal point. Store the number in a variable, then convert it in the ways indicated in the example run below. In the end, convert the number you got from `int()` back to a float.\n",
"\n",
"Example run:\n",
" \n",
"```python\n",
"Input a floating point number containing at least 5 digits both before and after .\n",
"What is your number? 123456.724353\n",
"Converted to a whole number using int(): 123456\n",
"Rounded to the closest whole number: 123457\n",
"Rounded to two decimals: 123456.72\n",
"Rounded to four decimals: 123456.7244\n",
"Rounded to the closest thousand: 123000\n",
"Integer from int() converted back into a float: 123456.0\n",
"```\n",
"\n",
"***Write your code in the block below.***"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"editable": false,
"run_control": {
"frozen": true
}
},
"source": [
"## d)"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": false,
"run_control": {
"frozen": true
}
},
"source": [
"Get a floating point number from the user, then ask how many decimals the user wants, then use `round()` with the required number.\n",
"\n",
"Example run:\n",
" \n",
"```python\n",
"Write a floating point number: 3.14159263\n",
"How many decimals do you want? 2\n",
"The number you gave was 3.14159263, with 2 decimals this becomes 3.14\n",
"```\n",
"***Write your code in the block below.***"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"celltoolbar": "Edit 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.6"
},
"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
}