You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 01-introduction.md
+57Lines changed: 57 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -189,6 +189,63 @@ else:
189
189
190
190
:::::::::::::::::::::::::::::::::::::::::::::::
191
191
192
+
::::::::::::::::::::::::::::::::::::::::: callout
193
+
194
+
## Formatting Variables and Objects in Strings
195
+
196
+
Throughout this course, we will be printing the values of variables inside strings to demonstrate what the code does. There are a number of ways to this in Python; in this course we will be using `f-strings` which are the recommended string interpolation syntax from version 3.6 onwards.
197
+
198
+
To use `f-strings` simply start a string literal with `f` or `F`, then embed whatever you want interpolating into the string within curly braces `{}`:
199
+
200
+
```python
201
+
two_int =2
202
+
two_str ="2"
203
+
f_string =f"{two_int} + {two_str} = {2+2}"
204
+
print(f_string)
205
+
```
206
+
```output
207
+
2 + 2 = 4
208
+
```
209
+
210
+
Numerical values can be formatted using `:` inside the curly braces. For example, an integer `i` can be made to have a width `n` using `{i:nd}`, or `{i:0nd}` to pad it out with zeros:
211
+
212
+
```python
213
+
print(f"One with four leading spaces {1:5d}")
214
+
print(f"One with four leading zeros {1:05d}")
215
+
```
216
+
```output
217
+
One with four leading spaces 1
218
+
One with four leading zeros 00001
219
+
```
220
+
221
+
Floating point variables can have their precision specified with a number after a decimal point and an `f`:
222
+
```python
223
+
pi =3.141592653589793
224
+
print(pi)
225
+
print(f"pi to three decimal places is {pi:.3f}")
226
+
```
227
+
```output
228
+
3.141592653589793
229
+
pi to three decimal places is 3.142
230
+
```
231
+
232
+
Or made to use scientific notation with an `e`:
233
+
234
+
```python
235
+
print(1e9)
236
+
print(f"A billion in scientific notation is {1e9:.1e}")
237
+
```
238
+
```output
239
+
1000000000.0
240
+
A billion in scientific notation is 1.0e+09
241
+
```
242
+
243
+
This is only scratching the surface of what you can do with `f-strings`, they are often the most powerful and concise way to format variables inside strings. However, there are occasions when other methods are preferable, and you should be careful using them with Python [before version 3.12](https://realpython.com/python-f-strings/#upgrading-f-strings-python-312-and-beyond).
244
+
245
+
To learn more, see: [Python f-strings](https://realpython.com/python-f-strings/).
We would like to reiterate the [Carpentries](https://carpentries.org/) stance on [Generative AI in coding](https://swcarpentry.github.io/python-novice-inflammation/01-intro.html#generative-ai) which you may have seen when preparing for this course.
To access an element of the dictionary we must use the *key*:
151
148
152
149
```python
153
-
print('The age of alice is :', d['alice'])
150
+
print(f'The age of alice is: {d["alice"]}')
154
151
```
155
152
156
153
```output
@@ -161,8 +158,8 @@ We can also use a variable to index the dictionary:
161
158
162
159
```python
163
160
key ='alice'
164
-
print('The name of the person is used as key:', key)
165
-
print('The value associated to that key is:', d[key])
161
+
print(f'The name of the person is used as key:{key}')
162
+
print(f'The value associated to that key is:{d[key]}')
166
163
```
167
164
168
165
```output
@@ -175,9 +172,9 @@ The value associated to that key is: 35
175
172
Adding an element to a dictionary is done by creating a new key and attaching a value to it.
176
173
177
174
```python
178
-
print('Original dictionary:', d)
175
+
print(f'Original dictionary:{d}')
179
176
d['jane'] =24
180
-
print('New dictionary:', d)
177
+
print(f'New dictionary:{d}')
181
178
```
182
179
183
180
```output
@@ -191,7 +188,7 @@ To add one or more new elements we can also use the `update` method:
191
188
d_extra = {'tom': 54, 'david': 87}
192
189
193
190
d.update(d_extra)
194
-
print('Updated dictionary:', d)
191
+
print(f'Updated dictionary:{d}')
195
192
```
196
193
197
194
```output
@@ -202,7 +199,7 @@ To delete an element, use the `del` method:
202
199
203
200
```python
204
201
del d['tom']
205
-
print('Dictionary with item deleted:', d)
202
+
print(f'Dictionary with item deleted:{d}')
206
203
```
207
204
208
205
```output
@@ -213,8 +210,8 @@ Alternatively, the `pop` function can be used to take an element out of a dictio
213
210
214
211
```python
215
212
david_age = d.pop('david')
216
-
print('Age of David:', david_age)
217
-
print('Dictionary with david popped out:', d)
213
+
print(f'Age of David:{david_age}')
214
+
print(f'Dictionary with david popped out:{d}')
218
215
```
219
216
220
217
```output
@@ -250,9 +247,9 @@ TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
250
247
Keys have to be unique; you cannot have two keys with the same name. If you try to add an item using a key already present in the dictionary you will overwrite the previous value.
Copy file name to clipboardExpand all lines: 03-numpy_essential.md
+19-20Lines changed: 19 additions & 20 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -271,13 +271,12 @@ To identify any signal in the data we can use the standard deviation as an estim
271
271
```python
272
272
stddev_noisy = np.std(noisy)
273
273
mean_noisy = np.mean(noisy)
274
-
print(f'standard deviation is: {stddev_noisy}')
275
-
print(f'mean value is: {mean_noisy}')
274
+
print(f'standard deviation is: {stddev_noisy:.5f}')
275
+
print(f'mean value is: {mean_noisy:.5f}')
276
276
```
277
-
278
277
```output
279
-
standard deviation is: 0.011592652442611553
280
-
mean value is: 0.005047252119578472
278
+
standard deviation is: 0.01159
279
+
mean value is: 0.00505
281
280
```
282
281
283
282
We will create a mask for the data, by selecting all data points below this threshold value (we'll assume here that any signal we might be interested in is positive):
@@ -394,10 +393,10 @@ To improve the visible output we will carry out some simple analysis of the imag
394
393
First we examine the general stats of the data (using built-in methods, except for the median, which has to be called from NumPy directly):
This mask is applied to the data for all built-in functions. But where we have to directly use a NumPy function we have to make sure we use the equivalent function in the mask (`ma`) library:
TypeError: '>' not supported between instances of 'str' and 'int'
72
72
```
@@ -81,11 +81,11 @@ To make things simpler, we will first write the test as a function:
81
81
```python
82
82
defcheck_sign(val):
83
83
if val >0:
84
-
print('Value:', val, 'is positive.')
84
+
print(f'Value:{val}is positive.')
85
85
elif val ==0:
86
-
print('Value:', val, 'is zero.')
86
+
print(f'Value:{val}is zero.')
87
87
else:
88
-
print('Value:', val, 'is negative.')
88
+
print(f'Value:{val}is negative.')
89
89
```
90
90
91
91
Then wrap the function call in an `if` statement:
@@ -121,7 +121,7 @@ try:
121
121
exceptTypeErroras err:
122
122
print('Val is not a number')
123
123
print('But our code does not crash anymore')
124
-
print('The run-time error is:', err)
124
+
print(f'The run-time error is:{err}')
125
125
```
126
126
127
127
As with `if` statements, multiple `except` statements can be used, each with a different error test. These can be followed by an (optional) catch-all bare `except` statement (as we started with) to catch any unexpected errors. Note that only one `try` statement is allowed in the structure.
@@ -134,12 +134,12 @@ try:
134
134
reciprocal =1/val
135
135
exceptTypeErroras err:
136
136
print('Val is not a number')
137
-
print('The run-time error is:', err)
137
+
print(f'The run-time error is:{err}')
138
138
exceptExceptionas err:
139
139
print('Some error other than a TypeError occured')
140
-
print('The run-time error is:', err)
140
+
print(f'The run-time error is:{err}')
141
141
else:
142
-
print('The reciprocal of the value =', reciprocal)
142
+
print(f'The reciprocal of the value ={reciprocal}')
143
143
finally:
144
144
print('release memory')
145
145
```
@@ -214,7 +214,7 @@ To conduct such a test we can use an `assert` statement. This follows the struct
214
214
```python
215
215
val ='a'
216
216
217
-
asserttype(val) isfloatortype(val) isint, "Variable has to be a numerical object"
217
+
asserttype(val) isfloatortype(val) isint, 'Variable has to be a numerical object'
0 commit comments