Skip to content

Commit e08df26

Browse files
Merge pull request #2299 from arduino/karlsoderby/review-essentials
[PXCT-45] MP Essentials
2 parents 239d572 + b619a25 commit e08df26

File tree

1 file changed

+48
-25
lines changed
  • content/micropython/03.micropython/01.basics/04. essentials

1 file changed

+48
-25
lines changed

content/micropython/03.micropython/01.basics/04. essentials/essentials.md

+48-25
Original file line numberDiff line numberDiff line change
@@ -27,20 +27,20 @@ print(type(string_var)) # Output: <class 'str'>
2727
print(type(boolean_var)) # Output: <class 'bool'>
2828
```
2929

30-
31-
3230
## Lists
3331

3432
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.
3533

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 (`,`).
3737

3838
```python
3939
my_list = [1, 2, 3, "Four", True]
4040
print(my_list) # Output: [1, 2, 3, 'Four', True]
4141
```
4242

43-
### Accessing Elements:
43+
### Accessing Elements
4444

4545
Lists are zero-indexed, meaning the first element is at index `0`.
4646

@@ -49,14 +49,16 @@ print(my_list[0]) # Output: 1
4949
print(my_list[3]) # Output: Four
5050
```
5151

52-
### Modifying Lists:
52+
### Modifying Lists
53+
54+
We can modify an element inside a list by assigning it a new value.
5355

5456
```python
5557
my_list[1] = 20
5658
print(my_list) # Output: [1, 20, 3, 'Four', True]
5759
```
5860

59-
### Common List Methods:
61+
### Common List Methods
6062

6163
```python
6264
my_list.append("New Item") # Add an item
@@ -72,7 +74,7 @@ print(my_list) # Output: [1, 20, 'Four', True, 'New Item']
7274

7375
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.
7476

75-
### Creating Tuples:
77+
### Creating Tuples
7678

7779
```python
7880
my_tuple = (1, 2, 3, "Four", True)
@@ -104,37 +106,36 @@ print(my_tuple.count(2)) # Output: 2 (number of times 2 appears)
104106
print(my_tuple.index(3)) # Output: 2 (index of the first occurrence of 3)
105107
```
106108

107-
108-
109109
## Functions
110110

111111
Functions allow you to encapsulate reusable blocks of code, making your programs more modular and readable.
112112

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`.
114114

115115
```python
116116
def greet(name):
117117
print(f"Hello, {name}!")
118118
```
119119

120-
### Calling Functions:
120+
Then, we can call the function, and insert a name.
121121

122122
```python
123123
greet("Karl") # Output: Hello, Karl!
124124
greet("Alex") # Output: Hello, Alex!
125125
```
126126

127-
### Functions with Default Arguments:
127+
The result will be:
128128

129-
```python
130-
def greet(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!
135132
```
136133

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.
138139

139140
```python
140141
def square(number):
@@ -144,6 +145,20 @@ result = square(4)
144145
print(result) # Output: 16
145146
```
146147

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+
def greet(name="World"):
156+
print(f"Hello, {name}!")
157+
158+
greet() # Output: Hello, World!
159+
greet("Karl") # Output: Hello, Karl!
160+
```
161+
147162
## Objects
148163

149164
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:
196211

197212
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.
198213

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.
200215

201-
### Basic Structure:
216+
### Basic Structure
202217

203218
Exceptions follow a simple structure using `try`, `except`, and optionally `finally` blocks:
204219

@@ -212,22 +227,28 @@ finally:
212227
# Code that runs no matter what (optional)
213228
```
214229

215-
### Common Exceptions:
230+
### Common Exceptions
216231

217232
- **`ZeroDivisionError`**: Raised when dividing by zero.
218233
- **`ValueError`**: Raised when a function receives an invalid argument.
219234
- **`TypeError`**: Raised when an operation is applied to an unsupported type.
220235

221236
#### Example: Handling a ZeroDivisionError
222237

238+
In this case, we will set up the script to "fail", by providing it with an impossible task: dividing something by `0`.
239+
223240
```python
224241
try:
225242
result = 10 / 0
226243
except ZeroDivisionError:
227244
print("Cannot divide by zero!") # Output: Cannot divide by zero!
228245
```
229246

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!"`.
231252

232253
```python
233254
try:
@@ -237,10 +258,12 @@ except ZeroDivisionError:
237258
else:
238259
print(f"Result: {result}") # Output: Result: 5.0
239260
finally:
240-
print("Cleanup completed.") # Always executes
261+
print("Completed!") # Always executes
241262
```
242263

243-
### Raising Custom Exceptions:
264+
### Raising Custom Exceptions
265+
266+
We can also implement custom exceptions:
244267

245268
```python
246269
def check_positive(number):

0 commit comments

Comments
 (0)