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
Lists are a versatile way to store collections of items in MicroPython. They can hold any combination of data types and are mutable, meaning you can modify them after creation.
35
33
36
-
### Creating Lists:
34
+
### Creating Lists
35
+
36
+
To create a list, we need to define a variable, followed by square brackets `[]`. The content of the list is separated by a comma (`,`).
37
37
38
38
```python
39
39
my_list = [1, 2, 3, "Four", True]
40
40
print(my_list) # Output: [1, 2, 3, 'Four', True]
41
41
```
42
42
43
-
### Accessing Elements:
43
+
### Accessing Elements
44
44
45
45
Lists are zero-indexed, meaning the first element is at index `0`.
46
46
@@ -49,14 +49,16 @@ print(my_list[0]) # Output: 1
49
49
print(my_list[3]) # Output: Four
50
50
```
51
51
52
-
### Modifying Lists:
52
+
### Modifying Lists
53
+
54
+
We can modify an element inside a list by assigning it a new value.
Tuples are similar to lists but **immutable**, meaning their values cannot be changed after they are created. They are useful for representing fixed collections of items.
74
76
75
-
### Creating Tuples:
77
+
### Creating Tuples
76
78
77
79
```python
78
80
my_tuple = (1, 2, 3, "Four", True)
@@ -104,37 +106,36 @@ print(my_tuple.count(2)) # Output: 2 (number of times 2 appears)
104
106
print(my_tuple.index(3)) # Output: 2 (index of the first occurrence of 3)
105
107
```
106
108
107
-
108
-
109
109
## Functions
110
110
111
111
Functions allow you to encapsulate reusable blocks of code, making your programs more modular and readable.
112
112
113
-
### Defining Functions:
113
+
To define a function, we use `def` followed by the name of the function and parameters. In this case, let's define a function named `greet()`, which has the parameter `name`.
114
114
115
115
```python
116
116
defgreet(name):
117
117
print(f"Hello, {name}!")
118
118
```
119
119
120
-
### Calling Functions:
120
+
Then, we can call the function, and insert a name.
121
121
122
122
```python
123
123
greet("Karl") # Output: Hello, Karl!
124
124
greet("Alex") # Output: Hello, Alex!
125
125
```
126
126
127
-
### Functions with Default Arguments:
127
+
The result will be:
128
128
129
-
```python
130
-
defgreet(name="World"):
131
-
print(f"Hello, {name}!")
132
-
133
-
greet() # Output: Hello, World!
134
-
greet("Karl") # Output: Hello, Karl!
129
+
```cmd
130
+
Hello Karl!
131
+
Hello Alex!
135
132
```
136
133
137
-
### Returning Values:
134
+
### Returning Values
135
+
136
+
A function can also accept numbers, and compute them for you. In this case, we want to find out the **square number** of a number (a number multiplied by itself).
137
+
138
+
Inside the function we use `number * number` to get the value, and `return` to return the value to where it is called.
138
139
139
140
```python
140
141
defsquare(number):
@@ -144,6 +145,20 @@ result = square(4)
144
145
print(result) # Output: 16
145
146
```
146
147
148
+
### Default Arguments
149
+
150
+
If you have function with parameters, you can set a **default** value, so that if we call the function without a parameter, we get a default value returned.
151
+
152
+
In this case, we set the default to be `"World"`.
153
+
154
+
```python
155
+
defgreet(name="World"):
156
+
print(f"Hello, {name}!")
157
+
158
+
greet() # Output: Hello, World!
159
+
greet("Karl") # Output: Hello, Karl!
160
+
```
161
+
147
162
## Objects
148
163
149
164
Objects are a cornerstone of Python, and MicroPython fully supports object-oriented programming (OOP). An object is an instance of a **class**, and it can have **properties (attributes)** and **behaviors (methods)**. Let’s break these concepts down:
@@ -196,9 +211,9 @@ In this example:
196
211
197
212
In MicroPython, exceptions are a powerful way to deal with errors gracefully, ensuring your program doesn’t crash unexpectedly. By catching and handling exceptions, you can recover or retry alternative solutions.
198
213
199
-
Are we covering exceptions just because it is good practice? **No.** Albeit they may appear scary, exceptions are all bark and no bite. They use logic we are already familiar with, just in a slightly different format, and once you master them, they make debugging your code a breeze making it a very usefull bark.
214
+
Exceptions use logic we are already familiar with, just in a slightly different format, and contribute to making more foolproof code.
200
215
201
-
### Basic Structure:
216
+
### Basic Structure
202
217
203
218
Exceptions follow a simple structure using `try`, `except`, and optionally `finally` blocks:
204
219
@@ -212,22 +227,28 @@ finally:
212
227
# Code that runs no matter what (optional)
213
228
```
214
229
215
-
### Common Exceptions:
230
+
### Common Exceptions
216
231
217
232
-**`ZeroDivisionError`**: Raised when dividing by zero.
218
233
-**`ValueError`**: Raised when a function receives an invalid argument.
219
234
-**`TypeError`**: Raised when an operation is applied to an unsupported type.
220
235
221
236
#### Example: Handling a ZeroDivisionError
222
237
238
+
In this case, we will set up the script to "fail", by providing it with an impossible task: dividing something by `0`.
239
+
223
240
```python
224
241
try:
225
242
result =10/0
226
243
exceptZeroDivisionError:
227
244
print("Cannot divide by zero!") # Output: Cannot divide by zero!
228
245
```
229
246
230
-
### Using `else` and `finally`:
247
+
### Example: Using `else` and `finally`
248
+
249
+
We can make the decision tree a bit more complex, by using the `else` and `finally` operators.
250
+
251
+
In this case, we first try a division. If successful, we skip the `except` and jump to the `else`, which will print out the value, and `finally` we print out a statement `"Completed!"`.
0 commit comments