MicroPython基础
MicroPython 是一个精简版的 Python 3 解释器,专为微控制器和嵌入式系统设计。它让我们可以用 Python 语言控制单片机或者SOC中。
你可以把它理解成“跑在芯片上的 Python”。
1.基础数据类型与运算符
类型 | 示例值 | 描述 |
---|---|---|
int | 10 , -5 , 0xFF | 整数(十进制、十六进制) |
float | 3.14 , -2.5 | 浮点数 |
bool | True , False | 布尔值 |
str | 'hello' , "world" | 字符串 |
bytes | b'abc' , bytes([65,66]) | 字节数据 |
list | [1, 2, 3] | 列表(数组) |
tuple | (1, 2) | 元组 |
dict | {'a': 1, 'b': 2} | 字典(键值对) |
算术运算符
a = 10
b = 3
print(a + b) # 13
print(a - b) # 7
print(a * b) # 30
print(a / b) # 3.333...
print(a // b) # 3(整除)
print(a % b) # 1(取余)
print(a ** b) # 1000(乘方)
关系运算符(比较)
print(a == b) # False
print(a != b) # True
print(a > b) # True
print(a < b) # False
print(a >= b) # True
print(a <= b) # False
逻辑运算符
x = True
y = False
print(x and y) # False
print(x or y) # True
print(not x) # False
赋值运算符
a = 5
a += 2 # a = a + 2
print(a) # 7
a *= 3
print(a) # 21
a //= 4
print(a) # 5
位运算符(适用于底层硬件控制)
x = 0b1010 # 10
y = 0b1100 # 12
print(bin(x & y)) # 0b1000(按位与)
print(bin(x | y)) # 0b1110(按位或)
print(bin(x ^ y)) # 0b0110(按位异或)
print(bin(~x)) # -0b1011(按位取反)
print(bin(x << 1)) # 0b10100(左移)
print(bin(y >> 2)) # 0b11(右移)
成员运算符(常用于字符串、列表、字典等)
letters = ['a', 'b', 'c']
print('a' in letters) # True
print('d' not in letters) # True
text = "hello"
print('e' in text) # True
类型判断
a = 123
print(type(a)) # <class 'int'>
s = "MicroPython"
print(isinstance(s, str)) # True
2.字符串
字符串的定义和基本使用:
s1 = "hello"
s2 = 'world'
s3 = "MicroPython"
print(s1) # 输出: hello
print(s1 + " " + s2) # 拼接: hello world
print(len(s3)) # 长度: 11
字符串索引与切片:
msg = "MicroPython"
print(msg[0]) # M(第一个字符)
print(msg[-1]) # n(最后一个字符)
print(msg[0:5]) # Micro(切片,从索引0到4)
print(msg[5:]) # Python(从索引5到结尾)
print(msg[::-1]) # 反转字符串:nohtyPorcim
字符串格式化:
1.使用 %
:
name = "Alice"
age = 25
print("Name: %s, Age: %d" % (name, age))
2.使用 str.format()
temp = 36.6
print("体温是 {:.1f}℃".format(temp)) # 保留1位小数
常用字符串方法:
text = " hello MicroPython! "
print(text.strip()) # 去除首尾空格
print(text.lower()) # 全小写
print(text.upper()) # 全大写
print(text.replace("Micro", "Mini")) # 替换单词
print(text.find("Python")) # 查找子串位置
print(text.startswith(" h")) # 是否以 " h" 开头
print(text.endswith("! ")) # 是否以 "! " 结尾
字符串拆分和拼接:
data = "temp,humidity,pressure"
parts = data.split(",") # 拆分成列表
print(parts) # ['temp', 'humidity', 'pressure']
joined = "-".join(parts) # 用 - 连接
print(joined) # temp-humidity-pressure
遍历字符串:
msg = "OKK123"
for ch in msg:
print(ch) # 每次输出一个字符