Python background knowledge

Appendix 1 of the video tutorial - python syntax: https://singtown.com/learn/50061/

Benefits of using python

OpenMV can use Python for secondary development. There are several benefits:

  • Easy to get started
  • No need to consider memory application and release
  • There are many MicroPython libraries that can be used directly (not compatible with Python modules on PC)
  • The development team has developed various algorithms and modules for OpenMV to call

Python is a very commonly used language, which is widely used in image processing, machine learning, and network programming. And Python is a very easy-to-use language. If you have programming experience in other languages (such as C, C++, Java), it will be easier to get started.

REPL and serial port

OpenMV's IDE comes with a serial port assistant for connecting to OpenMV, and can also connect to other serial ports, such as Arduino, pyboard, esp8266.

First, disconnect OpenMV from the IDE, otherwise the serial port will conflict!

Open Tools → Open Terminal → New Terminal in OpenMV

Type in the terminal

print("hello OpenMV!")

It will display

hello OpenMV!

Python syntax

Output

Use print() to add a string in brackets to output the specified text to the screen. For example, to output 'hello, world', the code is as follows:

   print('hello, world')
hello, world

The print() function can also accept multiple strings, separated by commas "," and then they can be connected into a string for output:

  print('The quick brown fox', 'jumps over', 'the lazy dog')
The quick brown fox jumps over the lazy dog

print() will print each string in turn, and a space will be output when encountering a comma "," so the output string is pieced together like this:

The quick brown fox jumps over the lazy dog

print() can also print integers or calculation results:

  print(300)
300
  print(100 + 200)
300

Therefore, we can print the result of calculating 100 + 200 more beautifully:

   print('100 + 200 =', 100 + 200)
100 + 200 = 300

Note that for 100 + 200, the Python interpreter automatically calculates the result 300, but '100 + 200 =' is a string rather than a mathematical formula, and Python treats it as a string.

Variables

In Python, the equal sign = is an assignment statement, which can assign any data type to a variable. The same variable can be assigned repeatedly, and it can be a variable of different types, for example:

  a = 123 # a是整数
  print(a)
  a = 'ABC' # a变为字符串
  print(a)

This language in which the variable type itself is not fixed is called a dynamic language, and its counterpart is a static language. Static languages must specify the variable type when defining a variable. If the type does not match when assigning, an error will be reported. For example, Java is a static language, and the assignment statement is as follows (// indicates a comment):

  int a = 123; // a是整数类型变量
  a = "ABC"; // 错误:不能把字符串赋给整型变量

Compared with static languages, dynamic languages are more flexible, that's why.

List

One of Python's built-in data types is the list: list. A list is an ordered collection in which elements can be added and deleted at any time.\ For example, to list the names of all the classmates in the class, you can use a list to represent it:

 classmates = ['Michael', 'Bob', 'Tracy']
 classmates
['Michael', 'Bob', 'Tracy']

The variable classmates is a list. Use the len() function to get the number of list elements:

  len(classmates)
3

Use the index to access the element at each position in the list. Remember that the index starts at 0:

 classmates[0]
'Michael'
 classmates[1]
'Bob'
 classmates[2]
'Tracy'
 classmates[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

When the index is out of range, Python will report an IndexError error, so make sure the index does not cross the boundary. Remember that the index of the last element is len(classmates) - 1.

If you want to get the last element, in addition to calculating the index position, you can also use -1 as the index to get the last element directly:

  classmates[-1]
'Tracy'

By analogy, you can get the second to last and the third to last:

   classmates[-2]
'Bob'
   classmates[-3]
'Michael'
   classmates[-4]
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
  IndexError: list index out of range

Of course, the fourth to last is out of bounds.

A list is a mutable ordered list, so you can append elements to the end of the list:

  classmates.append('Adam')
  classmates
  ['Michael', 'Bob', 'Tracy', 'Adam']

You can also insert elements at a specified position, such as index 1:

  classmates.insert(1, 'Jack')
  classmates
  ['Michael', 'Jack', 'Bob', 'Tracy', 'Adam']

To delete an element at the end of a list, use the pop() method:

  classmates.pop()
  'Adam'
  classmates
  ['Michael', 'Jack', 'Bob', 'Tracy']

To replace an element with another element, you can directly assign the value to the corresponding index position:

   classmates[1] = 'Sarah'
 classmates
  ['Michael', 'Sarah', 'Tracy']

The data types of the elements in a list can also be different, for example:

   L = ['Apple', 123, True]

If a list has no elements, it is an empty list with a length of 0:

 L = []

 len(L)

 0

Tuple

Another ordered list is called a tuple. Tuples are very similar to lists, but once a tuple is initialized, it cannot be modified. For example, it also lists the names of classmates:

  classmates = ('Michael', 'Bob', 'Tracy')

Now, the tuple classmates cannot be changed, and it does not have methods such as append() and insert(). Other methods for getting elements are the same as lists. You can use classmates[0] and classmates[-1] normally, but you cannot assign them to other elements.

What is the significance of immutable tuples? Because tuples are immutable, the code is safer. If possible, use tuples instead of lists.

Tuple trap: When you define a tuple, the elements of the tuple must be determined at the time of definition, for example:

  t = (1, 2)

  t

  (1, 2)

However, to define a tuple with only 1 element, if you define it like this:

   t = (1)

   t

   1

The definition is not a tuple, t is an integer variable, and the value of variable t is 1! This is because the brackets () can represent both tuples and parentheses in mathematical formulas, which creates ambiguity. Therefore, Python stipulates that in this case, the calculation is performed according to the parentheses, and the calculation result is naturally 1.

Therefore, a comma, , must be added when defining a tuple with only 1 element to eliminate ambiguity:

   t = (1,)

   t

  (1,)

Python also adds a comma, , when displaying a tuple with only 1 element, so that you don’t misunderstand it as a bracket in the sense of mathematical calculation.

Conditional judgment

The complete form of the if statement is:

if <条件判断1>:
    <执行1>
elif <条件判断2>:
    <执行2>
elif <条件判断3>:
    <执行3>
else:
    <执行4>

For example:

age = 20
if age >= 6:
    print('teenager')
elif age >= 18:
    print('adult')
else:
    print('kid')

Loop

Python has two types of loops. One is the for...in loop, which iterates each element in the list or tuple in turn. See the example:

names = ['Michael', 'Bob', 'Tracy']
for name in names:
    print(name)

Executing this code will print each element of names in turn:

  Michael
  Bob
  Tracy

So the for x in ... loop substitutes each element into the variable x, and then executes the statements in the indented block.

If you want to calculate the sum of integers from 1 to 100, it is a bit difficult to write from 1 to 100. Fortunately, Python provides a range() function that can generate an integer sequence, which can be converted to a list through the list() function. For example, range(5) generates a sequence of integers less than 5 starting from 0:

  list(range(5))

  [0, 1, 2, 3, 4]

range(101) can generate a sequence of integers from 0 to 100, and the calculation is as follows:

sum = 0
for x in range(101):
    sum = sum + x
print(sum)

The second loop is the while loop. For example, if we want to calculate the sum of all odd numbers within 100, we can use a while loop to implement it:

sum = 0
n = 99
while n > 0:
    sum = sum + n
    n = n - 2
print(sum)

===== Data type conversion =====

Python's built-in common functions also include data type conversion functions, such as the int() function, which can convert other data types to integers:

>>> int('123')
123
>>> int(12.34)
12
>>> float('12.34')
12.34
>>> str(1.23)
'1.23'
>>> str(100)
'100'
>>> bool(1)
True
>>> bool('')
False

===== Function =====

In Python, to define a function, you need to use the def statement, write the function name, parentheses, parameters in the parentheses, and colons in sequence:, then write the function body in the indented block, and return the function with the return statement.

Let's first write a function to calculate x2:

def power(x):
    return x * x

For the power(x) function, the parameter x is a positional parameter.

When we call the power function, we must pass in one and only one parameter x:

power(5)\ 25\ power(15)\ 225

Now, what if we want to calculate x3? We can define another power3 function, but what if we want to calculate x4, x5, etc.? We cannot define infinite functions.

You may have thought that we can modify power(x) to power(x, n) to calculate xn, and do it right away:

def power(x, n):
    s = 1
    while n > 0:
        n = n - 1
        s = s * x
    return s

For this modified power(x, n) function, we can calculate any power of n:

power(5, 2)\ 25\ power(5, 3)\ 125

The modified power(x, n) function has two parameters: x and n. Both parameters are positional parameters. When calling the function, the two values passed in are assigned to the parameters x and n in order of position.

Slicing

Taking part of a list or tuple is a very common operation. For example, a list is as follows:

L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']

Take the first 3 elements and slice them with one line of code:

L[0:3]\ ['Michael', 'Sarah', 'Tracy']

L[0:3] means starting from index 0 and ending at index 3, but not including index 3. That is, indexes 0, 1, and 2 are exactly 3 elements.

If the first index is 0, it can be omitted:

L[:3]\ ['Michael', 'Sarah', 'Tracy']

You can also start from index 1 and take out 2 elements:

L[1:3]\ ['Sarah', 'Tracy']

Tuple is also a kind of list, the only difference is that tuple is immutable. Therefore, tuples can also be operated with slices, but the result of the operation is still a tuple:

(0, 1, 2, 3, 4, 5)[:3]\ (0, 1, 2)

The string 'xxx' can also be regarded as a list, and each element is a character. Therefore, strings can also be operated with slices, but the result of the operation is still a string:

'ABCDEFG'[:3]\ 'ABC'

Object

Python is object-oriented programming, such as an LED light

from pyb import LED

red_led = LED(1)
red_led.on()

LED is a class, red_led is an object, and this object can be operated, such as turning on, turning off, and checking the value.

Module

Module usage

results matching ""

    No results matching ""