Skip to content

Commit 7b1d750

Browse files
Essentials created
1 parent 010af8b commit 7b1d750

File tree

1 file changed

+267
-0
lines changed
  • content/micropython/03.micropython/01.basics/04. essentials

1 file changed

+267
-0
lines changed
Lines changed: 267 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,267 @@
1+
---
2+
title: 'Essentials'
3+
description: 'A guide to digital inputs and outputs using MicroPython.'
4+
author: 'Pedro Lima'
5+
tags: [MicroPython, Basics, Essentials]
6+
---
7+
8+
To make the most of all the tools available in your "Python" belt (thankfully, pythons are non-venomous!), understanding MicroPython's fundamental concepts is essential. This guide focuses on the language basics, covering variable types, lists, tuples, functions, and exception handling to help you build efficient and powerful programs.
9+
10+
## Variables and Data Types
11+
12+
Variables in MicroPython don’t need explicit type declarations. The type is inferred based on the assigned value.
13+
14+
### Example:
15+
16+
```python
17+
# Different data types
18+
integer_var = 42 # Integer
19+
float_var = 3.14 # Float
20+
string_var = "Hello!" # String
21+
boolean_var = True # Boolean
22+
23+
# Print variable types
24+
print(type(integer_var)) # Output: <class 'int'>
25+
print(type(float_var)) # Output: <class 'float'>
26+
print(type(string_var)) # Output: <class 'str'>
27+
print(type(boolean_var)) # Output: <class 'bool'>
28+
```
29+
30+
31+
32+
## Lists
33+
34+
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+
36+
### Creating Lists:
37+
38+
```python
39+
my_list = [1, 2, 3, "Four", True]
40+
print(my_list) # Output: [1, 2, 3, 'Four', True]
41+
```
42+
43+
### Accessing Elements:
44+
45+
Lists are zero-indexed, meaning the first element is at index `0`.
46+
47+
```python
48+
print(my_list[0]) # Output: 1
49+
print(my_list[3]) # Output: Four
50+
```
51+
52+
### Modifying Lists:
53+
54+
```python
55+
my_list[1] = 20
56+
print(my_list) # Output: [1, 20, 3, 'Four', True]
57+
```
58+
59+
### Common List Methods:
60+
61+
```python
62+
my_list.append("New Item") # Add an item
63+
print(my_list) # Output: [1, 20, 3, 'Four', True, 'New Item']
64+
65+
my_list.pop(2) # Remove item at index 2
66+
print(my_list) # Output: [1, 20, 'Four', True, 'New Item']
67+
```
68+
69+
70+
71+
## Tuples
72+
73+
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+
75+
### Creating Tuples:
76+
77+
```python
78+
my_tuple = (1, 2, 3, "Four", True)
79+
print(my_tuple) # Output: (1, 2, 3, 'Four', True)
80+
```
81+
82+
### Accessing Elements:
83+
84+
Like lists, tuples are zero-indexed.
85+
86+
```python
87+
print(my_tuple[0]) # Output: 1
88+
print(my_tuple[3]) # Output: Four
89+
```
90+
91+
### Why Use Tuples?
92+
93+
- **Efficiency**: Tuples consume less memory than lists.
94+
- **Safety**: Their immutability prevents accidental changes to the data.
95+
96+
### Common Tuple Methods:
97+
98+
Tuples are limited compared to lists but have a few useful methods:
99+
100+
```python
101+
my_tuple = (1, 2, 3, 2, 4)
102+
103+
print(my_tuple.count(2)) # Output: 2 (number of times 2 appears)
104+
print(my_tuple.index(3)) # Output: 2 (index of the first occurrence of 3)
105+
```
106+
107+
108+
109+
## Functions
110+
111+
Functions allow you to encapsulate reusable blocks of code, making your programs more modular and readable.
112+
113+
### Defining Functions:
114+
115+
```python
116+
def greet(name):
117+
print(f"Hello, {name}!")
118+
```
119+
120+
### Calling Functions:
121+
122+
```python
123+
greet("Karl") # Output: Hello, Karl!
124+
greet("Alex") # Output: Hello, Alex!
125+
```
126+
127+
### Functions with Default Arguments:
128+
129+
```python
130+
def greet(name="World"):
131+
print(f"Hello, {name}!")
132+
133+
greet() # Output: Hello, World!
134+
greet("Karl") # Output: Hello, Karl!
135+
```
136+
137+
### Returning Values:
138+
139+
```python
140+
def square(number):
141+
return number * number
142+
143+
result = square(4)
144+
print(result) # Output: 16
145+
```
146+
147+
## Objects
148+
149+
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:
150+
151+
- **Class**: A blueprint or template for creating objects. It defines the structure (attributes) and behavior (methods) that the objects will have. Think of a class as the recipe for making objects.
152+
- **Attributes**: Variables that store data specific to an object. These are the properties or characteristics of the object, like a dog’s name or breed.
153+
- **Methods**: Functions defined inside a class that operate on the object’s attributes or perform specific actions. These represent the behavior of the object, like a dog barking.
154+
155+
Here’s how these concepts come together:
156+
157+
### Defining a Class
158+
159+
Use the `class` keyword to define a class. Inside the class, we can define attributes and methods.
160+
161+
```python
162+
class Dog:
163+
# Constructor method to initialize attributes
164+
def __init__(self, name, breed):
165+
self.name = name # Attribute: name
166+
self.breed = breed # Attribute: breed
167+
168+
# Method: A behavior of the dog
169+
def bark(self):
170+
print(f"{self.name} says: Woof!")
171+
```
172+
173+
### Creating an Object
174+
175+
An object is an instance of the class. It represents a specific entity created from the class blueprint.
176+
177+
```python
178+
# Create an object of the Dog class
179+
my_dog = Dog("Denver", "Golden Retriever")
180+
181+
# Access attributes
182+
print(my_dog.name) # Output: Denver
183+
print(my_dog.breed) # Output: Golden Retriever
184+
185+
# Call a method
186+
my_dog.bark() # Output: Buddy says: Woof!
187+
```
188+
189+
In this example:
190+
1. The `Dog` class is the blueprint.
191+
2. `name` and `breed` are attributes (properties of the dog).
192+
3. `bark()` is a method (a behavior of the dog).
193+
194+
195+
## Exception Handling
196+
197+
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+
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.
200+
201+
### Basic Structure:
202+
203+
Exceptions follow a simple structure using `try`, `except`, and optionally `finally` blocks:
204+
205+
```python
206+
try:
207+
# Code that might raise an exception
208+
risky_operation()
209+
except ExceptionType:
210+
# Code to handle the exception
211+
finally:
212+
# Code that runs no matter what (optional)
213+
```
214+
215+
### Common Exceptions:
216+
217+
- **`ZeroDivisionError`**: Raised when dividing by zero.
218+
- **`ValueError`**: Raised when a function receives an invalid argument.
219+
- **`TypeError`**: Raised when an operation is applied to an unsupported type.
220+
221+
#### Example: Handling a ZeroDivisionError
222+
223+
```python
224+
try:
225+
result = 10 / 0
226+
except ZeroDivisionError:
227+
print("Cannot divide by zero!") # Output: Cannot divide by zero!
228+
```
229+
230+
### Using `else` and `finally`:
231+
232+
```python
233+
try:
234+
result = 10 / 2
235+
except ZeroDivisionError:
236+
print("Cannot divide by zero!")
237+
else:
238+
print(f"Result: {result}") # Output: Result: 5.0
239+
finally:
240+
print("Cleanup completed.") # Always executes
241+
```
242+
243+
### Raising Custom Exceptions:
244+
245+
```python
246+
def check_positive(number):
247+
if number < 0:
248+
raise ValueError("Number must be positive!")
249+
250+
try:
251+
check_positive(-5)
252+
except ValueError as e:
253+
print(e) # Output: Number must be positive!
254+
```
255+
256+
257+
258+
## Summary
259+
260+
MicroPython provides a solid foundation for programming microcontrollers with ease. In this guide, we covered:
261+
262+
- Variables and data types
263+
- Lists and tuples
264+
- Defining and calling functions
265+
- Exception handling for graceful error recovery
266+
267+
With these fundamentals, you’re ready to build powerful and efficient applications. Dive into our additional tutorials for more advanced topics!

0 commit comments

Comments
 (0)