MicroPython语法条件判断和循环 - 1.2.4

2020-02-208669
AI 快速预览详细 收起
本文介绍了MicroPython中的条件判断和循环语句。首先讲解了if语句,通过示例展示了如何使用if-elif-else结构进行多条件判断。接着介绍了while语句,用于在满足条件时循环执行代码。然后讲解了for语句,用于按序列顺序迭代执行代码。此外,还介绍了range()函数、break语句、continue语句和pass语句的用法。通过这些基本语法,读者可以掌握在MicroPython中实现逻辑控制的方法。

1.2.4.1 if语句

if语句用来判断当某个条件成立(非0或为True)时,执行下一个语句。常与else一起使用,表示除if判断条件之外的其他情况。

示例:

>>> num = 130
>>> if num%2 == 0:
...   print(num, "is a even number")
... else:
...   print(num, "is a odd number")
... 
130 is a even number

** 注意:

可以有多个elif,else是可选的。elif是“else if”的缩写,对于避免过多的缩进非常有用,else与它最近的前一个if或elif匹配。
示例:

>>> x = 32
>>> if x < 0:
...   print("Negative changed to zero")
... elif x == 0:
...   print("Zero")
... elif x == 1:
...   print("Single")
... else:
...   print("More")
... 
More

注意:
由于MicroPython严格的缩进格式,为避免出错,最好用空格键进行缩进。

示例:

>>> x = 32
>>> if x > 0:
...   print("x > 0")
... print("hello")
... else:
...   print("x <= 0")
... 
Traceback (most recent call last):
  File "<stdin>", line 3
SyntaxError: invalid syntax

1.2.4.2 while语句

while语句用于循环执行程序,即在某条件下,循环执行某段程序。

示例:

>>> i = 5
>>> while i > 0:
...   print(i)
...   i = i-1
... 
5
4
3
2
1

1.2.4.3 for语句

for语句用于循环执行程序,即在某条件下,循环执行某段程序。 for语句按序列中的项目(一个列表或一个字符串)顺序迭代。

示例:

>>> words = ['www', 'DFRobot', 'com', 'cn']
>>> for w in words:
...   print(w, len(w))
... 
www 3
DFRobot 7
com 3
cn 2

如果需要在for循环内修改迭代的顺序或条件,可以在for循环中增加条件判断。

示例:

>>> words = ['www', 'DFRobot', 'com', 'cn']
>>> for w in words:
...   if len(w) < 7:
...     print(w)
...     
...     
... 
www
com
cn

range()函数

如果你需要遍历一系列的数字,可以使用内置函数range()。

示例:

>>> for i in range(4):
...     print(i)
...     
...     
... 
0
1
2
3

1.2.4.4 break语句

break语句用于退出for或while循环。

示例:

>>> for x in range(2, 10):
...   if x == 5:
...     break
...   print(x)
... 
2
3
4

1.2.4.5 continue语句

continue语句用于退出for或while语句的当前循环,进入下一次循环。

示例:

>>> for x in range(2, 10): 
...   if x == 5:
...     continue
...   print(x)
... 
2
3
4
6
7
8
9

1.2.4.6 pass语句

pass语句表示空语句,不做任何事情,一般用作占位语句,用来保持程序结构的完整性。

示例:

>>> for letter in 'hello':
...   if letter == 'l':
...     pass
...     print("This is pass")
...   print("Current letter:", letter)
... 
Current letter: h
Current letter: e
This is pass
Current letter: l
This is pass
Current letter: l
Current letter: o

创作许可协议

本项目采用 None(不开放任何权利,保留所有权利) 进行许可。

评论(1)
DFrJ5KYVQaH
DFrJ5KYVQaH
继续学习
- 没有更多了 -