Esp32 micro Python development journey basics ③ - basic syntax of micro Python

Posted by nthomthom on Sat, 04 Dec 2021 07:59:45 +0100

Micro Python basic syntax

Before officially entering the development of esp32 micro python, let's learn some simple syntax.

1. Print output - print content

  • explain

Use the print() function to print data to the terminal

  • case
print('Single chip microcomputer rookie MicroPython')
  • result
  • Attention
    print outputs line breaks by default. If end = 'is added at the end, there will be no line breaks.

2. Good code requires appropriate comments

Normally, good code will give appropriate comments at key points, and good comments can be remembered even after a long time.

  • Single-Line Comments
    A single line comment starts with # and the contents that follow # are comments as long as there is no line break

  • multiline comment
    You can use multiple # signs, three single quotation marks ('') or three double quotation marks ("" ")

print('Single chip microcomputer rookie MicroPython',end='')
# Multiline annotation multiline annotation multiline annotation
# Multiline annotation multiline annotation multiline annotation
# Multiline annotation multiline annotation multiline annotation

print('Single chip microcomputer rookie MicroPython',end='')
"""
  Multiline annotation multiline annotation multiline annotation
  Multiline annotation multiline annotation multiline annotation
  Multiline annotation multiline annotation multiline annotation
"""

print('Single chip microcomputer rookie MicroPython',end='')
'''
  Multiline annotation multiline annotation multiline annotation
  Multiline annotation multiline annotation multiline annotation
  Multiline annotation multiline annotation multiline annotation
'''

3. Constant

Generally, our constants are immutable, including numbers such as 1 and 2 or strings such as "hello". Micro Python provides a const keyword to indicate that its value cannot be changed.

from micropython import const
a = const(66)
print(a)
# Try copying a variable again
a = 66

Test results:

4. Variable

Creating a variable is very simple. You can name it at will and assign a value. When assigning values, you do not need to specify the data type of the variable (similar to c language, int and double). Because a variable is a reference, it accesses objects of different data types through assignment.

Random naming is not really random, but some rules should be followed:

  • Variable names can only contain numbers, letters and underscores
  • The first character of a variable name must be a letter or underscore
  • Variable names are case sensitive
a = "abc" #Reference a points to a string object "abcd"
print(a)

a = 32 #Reference a points to an integer object
print(a)

Test results:

5. Data type

The basic data types in micro Python include Number, String, List, Tuple, Dictionary, etc.

5.1 Number - int, float, bool, complex

Micro Python supports int, float, bool and complex (plural).
When a variable is defined, the Number object is created. The created Number object can be deleted through the del statement.

a = 3
del a
5.1.1 int -- integer

Micro Python can handle integers of any size (including negative integers). The representation of integers is the same as that in mathematics,

1, -1, 0, 10000, ...

The integer is expressed in hexadecimal in micropathon, as follows

0xff00, 0xabcd, ...

5.1.2 float -- floating point type

Floating point numbers are decimals.
You can replace 10 with E, 1.23 × 10 ^ 9 is 1.23e9, or 12.3e8. 0.000012 can be written as 1.2e-5.

a = 1.3e6
print(a)

5.1.3 bool -- Boolean

Boolean values have only True and False values. If it is not True, it is False. Pay attention to case

if True:
    print('true')
else:
    print('false')

5.1.4 complex -- complex number

slightly

5.1.5 digital type conversion

Convert built-in data types:

int(x): converts x to an integer.
float(x): converts x to a floating point number.
complex(x): converts x to a complex number, the real part is x and the imaginary part is 0. > complex (x, y): converts X and y to a complex number, the real part is x and the imaginary part is y. X and y are numeric expressions.

a = 10.2
print(int(a)) # Convert floating point numbers to integers
b = 11
print(float(b)) # Integer to floating point

5.2 String

A string is any text enclosed by "" or "" (such as' abc ',' xyz ').

s = 'MCU rookie 123456'
print(s)
s = "MCU rookie 123456"
print(s) 

  • To access a substring, you can use square brackets to intercept the string
s = 'MCU rookie 123456'
print(s)
s = "MCU rookie 123456"
print(s)
print(s[1])
print(s[1:5])

  • Intercepts a part of a string and splices it with other strings
s = 'MCU rookie 123456'
print(s)
s = "MCU rookie 123456"
print(s)
print(s[1])
print(s[1:5])
print(s[1:5] + '987654')

5.3 List

Square brackets are required to define the list in micropthon. The data items in the list are contained in square brackets, and the data items are separated by commas.

  • Create a list. The data in the list can be any data type, or even a mixture of different types
list = [0,1,2,3,'abcd']
print(list)
print(list[3]) # Print elements with index 3

  • Modify list item
list = [0,1,2,3,'abcd']
print(list)
print(list[3]) # Print elements with index 3
list[3] = 4
print(list[3]) # Print the element with index 3 again

  • Delete elements from the list
    You can use the del or pop() function to delete an element at a specified location in the list.
list = [0,1,2,3,'abcd']
print(list)
print(list[3]) # Print elements with index 3
del list[3] # Delete element with index 3
print(list)

  • Insert element at a location
    Insert the element x at position i with the insert(i, x) function, and the elements at and after the original i position move back in turn. You can also add elements at the end with the append() method.
list = [0,1,2,3,'abcd']
print(list)
list.insert(2,'bef')
print(list)
list.append('end')
print(list)

  • Operation summary
  • cmp(list1, list2): compares the elements of two lists
  • len(list): returns the number of list elements
  • max(list): returns the maximum value of a list element
  • min(list): returns the minimum value of a list element
  • list(seq): convert tuples to lists
  • list.append(obj): adds a new object at the end of the list
  • list.count(obj): counts the number of times an element appears in the list
  • list.extend(seq): append multiple values in another sequence at one time at the end of the list (expand the original list with the new list)
  • list.index(obj): find the index position of the first match of a value from the list
  • list.insert(index, obj): inserts objects into the list
  • list.pop(obj=list[-1]): removes an element in the list (the last element by default) and returns the value of the element
  • list.remove(obj): removes the first match of a value in the list
  • list.reverse(): reverse the elements in the list
  • list.sort([func]): sort the original list

5.4 Tuple tuple

Tuples are very similar to lists, except that tuples are immutable like strings, i.e. tuples cannot be modified. Because tuples are immutable, they are generally used to define a set of values that do not need to be changed in micro python.
In micro python, tuples are defined using parentheses, and items in tuples are also separated by commas.

Note: when defining a tuple with only 1 element, you must follow this element with a comma.

tup=(1,2,3)
print(tup)
tup=(1)
print(tup)
tup=(1,)
print(tup)

5.5 Dictionary

In the dictionary, the name is "key" and the corresponding content is "value". A dictionary is a collection of key/value pairs.
The dictionary defined in micropthon uses curly braces {}, the key / value pairs in the dictionary are separated by commas, and the keys and values are separated by colons.

dic={'key':1,'key2': '123434'}
print(dic)

  • A method of directly assigning a value to a single key to put data into a dictionary
dic={'key':1,'key2': '123434'}
print(dic)
dic['key'] = 'new' #A method of directly assigning a value to a single key to put data into a dictionary
print(dic)

  • A key only corresponds to a value. Put a value into a key multiple times, and the subsequent value will overwrite the previous value
dic={'key':1,'key2': '123434'}
print(dic)
dic['key'] = 'new' #A method of directly assigning a value to a single key to put data into a dictionary
print(dic)
dic['key'] = 'new1' #Put value into a key multiple times
print(dic)

  • Delete key / value pair
dic={'key':1,'key2': '123434'}
print(dic)
dic['key'] = 'new' #A method of directly assigning a value to a single key to put data into a dictionary
print(dic)
dic['key'] = 'new1' #Put value into a key multiple times
print(dic)
dic.pop('key') #Delete key / value pair
print(dic)

Topics: Python