Loading... # MicroPython语法·篇一-基础 <!--more--> - ## print 输出 使用`print()`函数可以将数据打印到终端。 `print()`函数可以直接在终端执行,也可以写在Python文件中,通过运行文件来执行。 print()函数中可以有多个字符串,用逗号“,”隔开。 print("Hello World!") Hello World! print("hello", "world!") hello world! print 默认输出换行,如果在末尾加上end=" "则不换行。 例如: print("hello", end=" ") print("world") hello world - ## 注释 单行注释 MicroPython中的单行注释以#开头,后面的文字直到行尾都算注释。 >>> print("hello world") #This is a annotation hello world 多行注释 如果要进行多行的注释,可以使用多个#号, 三个单引号(''')或三个双引号(""")。 ''' This is a multi-line comment. Prints hello world. ''' print("hello world") - ## 缩进 MicroPython使用缩进来区分不同的代码块,不需要使用大括号 {} 。 if True: print ("True") else: print ("False") 缩进的空格数是可变的,但是同一代码块缩进必须一致 if True: print ("Answer") print ("True") else: print ("Answer") print ("False") # 缩进不一致,会导致运行错误 以上程序由于缩进不一致,执行后会出现类似以下错误 *test.py:6:2: unexpected indent print ("False") # 缩进不一致,会导致运行错误 ^ syntax finish. - ## help() 函数 调用 MicroPython的 help() 函数查看一些基本信息。 >>> help(max) #查看max()函数的基本信息 object <function> is of type function >>> >>> help(sys) #查看sys模块的一些信息 object <module 'sys'> is of type module __name__ -- sys path -- ['', '/lib'] argv -- [] version -- 3.4.0 version_info -- (3, 4, 0) implementation -- (name='mi 0> stdout -- <io.FileIO 1> stderr -- <io.FileIO 2> modules -- {'flashbdev': <module 'flashbdev'>} print_exception -- <function> >>> >>> help(sys.path) object ['', '/lib'] is of type list append -- <ert -- <function> pop -- <function> remove -- <function> reverse -- <function> sort -- <function> - ## 常量、变量 - ### 常量 如10、100这样的数值或“hello world!”这样的字符串,就是常量。常量的值不可变,MicroPython提供了一个const关键字,表示其值不可更改。 ``` from micropython import const a = const(33) print(a)表示其值不可更改。 ``` - ### 变量 创建一个变量很简单,只需要起个名,给他赋予一个值,在赋值的时候不需要指定变量的数据类型,因为变量是一个引用,它通过赋值来访问不同数据类型的对象。这点与其他语言中的变量不同,要注意(关于数据类型在下一小节讲)。 ``` Python >>> a = "abcd" #引用a指向一个字符串对象“abcd” >>> print(a) abcd >>> a = 32 #引用a指向一个整型对象 >>> print(a2) 32 >>> a1 = a #a1指向引用a指向的对象 >>> print(a) 32 ``` - ### 变量命名 给变量命名必须遵循以下规则: ◆变量名只能包含数字、字母、下划线 ◆变量名的第一个字符必须是字母或下划线 ◆变量名区分大小写 Last modification:March 26, 2019 © Allow specification reprint Like 0 If you think my article is useful to you, please feel free to appreciate