-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathintroducing_python.Rmd
459 lines (343 loc) · 7.27 KB
/
introducing_python.Rmd
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
---
jupyter:
jupytext:
notebook_metadata_filter: all,-language_info
split_at_heading: true
text_representation:
extension: .Rmd
format_name: rmarkdown
format_version: '1.2'
jupytext_version: 1.13.7
kernelspec:
display_name: Python 3
language: python
name: python3
orphan: true
---
# Introduction to Python
## Variables
Variables are named values.
```{python}
a = 4
```
Read this as:
> "a" gets the value 4.
```{python}
b = 6
```
> "b" gets the value 6.
```{python}
a + b
```
You can also *update* variables, as in:
```{python}
a = a + 2
a
```
So far we've seen numbers as values, but we can also have bits of text called *strings*. Strings are bits of text between quotes.
```{python}
a = "Python"
c = "MATLAB"
z = " > "
```
You have seen adding numbers. We can also add strings. This as the effect of sticking them together — *concatenating* the strings:
```{python}
a + z + c
```
Strings can have apostrophes (`'`) or inverted commas (`"`) at either end, Python accepts either.
```{python}
first = 'a string'
second = "b string"
first + second
```
You can even use triple apostrophes or inverted commas at either end; this is useful for when you want to put a new line inside your string:
```{python}
many_line_string = """
This string
has
several
lines
"""
print(many_line_string)
```
Length of a string:
```{python}
len(first)
```
Strings and numbers are different:
```{python tags=c("raises-exception")}
number = "9"
number + 6
```
We can convert between numbers and strings:
```{python}
int(number) + 6
str(9)
```
However ...
```{python tags=c("raises-exception")}
number = "nine"
int(number)
```
## Lists
```{python}
an_empty_list = []
list_with_two_items = [1, 2]
items_can_be_diverse = [1, "Obama", 4.55]
```
```{python}
example_list = []
example_list.append("experiment1")
example_list
```
```{python}
example_list[0]
```
The length of a list (or any object that can have a length):
```{python}
len(example_list)
```
```{python}
example_list.append("failed_experiment")
print(example_list)
example_list.append("failed_experiment")
print(example_list)
```
```{python}
example_list.pop()
```
```{python}
example_list
```
```{python}
del example_list[0]
example_list
```
`range` in returns a “range object”. It’s like a list, but isn’t quite a
list.
```{python}
range(10)
```
You can make it into a list by using the `list` constructor. A constructor
is like a function, but it creates a new object, in this case a new object of
type `list`.
```{python}
list(range(10))
```
You can also set the start element for `range`:
```{python}
list(range(2, 7))
```
Use `in` to ask if a element is a collection of things, such as a range, or
a list:
```{python}
5 in range(2, 7)
5 in [2, 5, 7]
```
```{python}
9 in range(2, 7)
```
## Sets
Sets are unordered, and unique.
“Unordered” means the order is arbitrary, and Python reserves the right to
return the elements in any order it likes:
```{python}
our_work = set(["metacognition", "mindwandering", "perception"])
print(our_work)
```
If you want to get a version of the set that is ordered, use `sorted`, which
returns a sorted list:
```{python}
sorted(our_work)
```
You can't index a set, because the indices 0, or 1, or 2 don’t correspond to
any particular element (because the set is unordered):
```{python tags=c("raises-exception")}
our_work[0]
```
Add to a set with the `add` method:
```{python}
our_work.add("consciousness")
print(our_work)
```
```{python}
our_work.add("consciousness")
print(our_work)
our_work.add("consciousness")
print(our_work)
```
You can subtract sets:
```{python}
competing_labs_work = set(["motor control", "decision making", "memory", "consciousness"])
what_we_should_focus_on = our_work - competing_labs_work
print(what_we_should_focus_on)
```
```{python}
what_we_should_avoid = our_work.intersection(competing_labs_work)
print(what_we_should_avoid)
```
Sets have lengths as well:
```{python}
len(what_we_should_focus_on)
```
## Working with strings
We have already seen strings. Here is another example.
```{python}
example = "mary had a little lamb"
print(example)
```
String slicing:
```{python}
example[0]
```
```{python}
example[0:4]
```
You can split strings with any character. This breaks up the string,
returning a list of strings broken at the separator character:
```{python}
example.split(" ")
```
```{python}
example.split(" ")[4]
```
You can split with any character:
```{python}
another_example = 'one:two:three'
another_example.split(":")
```
You can also `strip` a string. That returns a new string with spaces, tabs
and end of line characters removed from the beginning and end:
```{python}
my_string = ' a string\n'
my_string
my_string.strip()
```
Adding strings:
```{python}
example + " or two"
```
Putting strings into other strings:
```{python}
subject_id = "sub1"
print(f"Subject {subject_id} is excellent")
```
```{python}
age = 29
print(f"Subject {subject_id} is {age} years old")
```
You can do more complex formatting of numbers and strings using formatting
options after a `:` in the placeholder for the string. See:
[https://docs.python.org/3.5/library/string.html#format-examples](https://docs.python.org/3.5/library/string.html#format-examples).
```{python}
print("Subject {:02d} is here".format(4))
```
## For loop
```{python}
for i in range(10):
print(i)
```
Indentation is crucial!
```{python tags=c("raises-exception")}
for i in range(10):
print(i)
```
Watch out for mistakes:
```{python}
for i in range(10):
j = i + 1
print(j)
```
## Ifs and breaks
```{python}
a = 2
b = 5
c = a + b
if c < 6:
print("yes")
```
```{python}
if c < 6:
print("yes")
else:
print("no")
```
```{python}
if c < 6:
print("yes")
elif c > 6:
print("no")
else:
print("kind of")
```
```{python}
if True:
print("true, true!")
```
```{python}
if False:
print("never!")
```
```{python}
for i in range(10):
if i == 6:
break
print(i)
```
```{python}
for i in range(10):
if i == 6:
continue
print(i)
```
## Logic
You can use logical operators like `and`, `or` and `not`:
```{python}
strange_election = True
uncomfortable_choices = True
satisfying_experience = False
strange_election and uncomfortable_choices
strange_election and satisfying_experience
strange_election and not satisfying_experience
```
We often use these in `if` statements:
```{python}
if strange_election and not satisfying_experience:
print('Watching a lot of news')
```
## Files
Use [pathlib](pathlib.Rmd) to write text and read text from files.
Write lines to a text file:
```{python}
from pathlib import Path
path = Path("important_notes.txt")
type(path)
```
```{python}
my_text = """captains log 672828: I had a banana for breakfast.
captains log 672829: I should watch less TV.
"""
print(my_text)
```
```{python}
path.write_text(my_text)
```
Read lines from a text file:
```{python}
text_again = path.read_text()
print(text_again)
```
Split the lines from a text into a list, where there is one element per line,
and each element is a string:
```{python}
# The splitlines method of a string.
lines = text_again.splitlines()
len(lines)
print(lines[0])
print(lines[1])
```
We may want to delete the file when we've finished with it. Again the `Path` object does the job:
```{python}
# Delete the file.
path.unlink()
```