[Diaoye learns programming] MicroPython manual's built-in module random: random number generation

Insert image description here

MicroPython is a lightweight version of the interpreter designed to run the Python 3 programming language in embedded systems. Compared with regular Python, the MicroPython interpreter is small (only about 100KB) and is compiled into a binary Executable file to run, resulting in higher execution efficiency. It uses a lightweight garbage collection mechanism and removes most of the Python standard library to accommodate resource-constrained microcontrollers.

The main features of MicroPython include:
1. The syntax and functions are compatible with standard Python, making it easy to learn and use. Supports most of Python's core syntax.
2. Directly access and control the hardware, control GPIO, I2C, SPI, etc. like Arduino.
3. A powerful module system that provides functions such as file system, network, and graphical interface.
4. Support cross-compilation to generate efficient native code, which is 10-100 times faster than the interpreter.
5. The amount of code is small, and the memory usage is small, which is suitable for running on MCU and development boards with small memory.
6. Open source license, free to use. The Shell interactive environment provides convenience for development and testing.
7. The built-in I/O driver supports a large number of microcontroller platforms, such as ESP8266, ESP32, STM32, micro:bit, control board and PyBoard, etc. There is an active community.

The application scenarios of MicroPython include:
1. Quickly build prototypes and user interactions for embedded products.
2. Make some small programmable hardware projects.
3. As an educational tool, it helps beginners learn Python and IoT programming.
4. Build smart device firmware to achieve advanced control and cloud connectivity.
5. Various microcontroller applications such as Internet of Things, embedded intelligence, robots, etc.

Pay attention to the following when using MicroPython:
1. The memory and Flash space are limited.
2. The explanation and execution efficiency is not as good as C language.
3. Some library functions are different from the standard version.
4. Optimize the syntax for the platform and correct the differences with standard Python.
5. Use memory resources rationally and avoid frequently allocating large memory blocks.
6. Use native code to improve the performance of speed-critical parts.
7. Use abstraction appropriately to encapsulate underlying hardware operations.

Generally speaking, MicroPython brings Python into the field of microcontrollers, which is an important innovation that not only lowers the programming threshold but also provides good hardware control capabilities. It is very suitable for the development of various types of Internet of Things and intelligent hardware.

Insert image description here
MicroPython's built-in module random is a module for generating random numbers, which can be used to generate random integers or floating point numbers in a certain range or sequence. Its main features are:

1. It can use the random() method to return a random floating point number in the range [0.0, 1.0).
2. It can use the getrandbits(n) method to return an n-bit random integer (0 <= n <= 32).
3. It can use the uniform(a, b) method to return a random floating point number in the range [a, b].
4. It can use the randrange(stop), randrange(start, stop) or randrange(start, stop, step) method to return a random integer specifying the range and step size.
5. It can use the randint(a, b) method to return a random integer in the range [a, b].
6. It can use the choice(sequence) method to randomly select an element from a sequence.
7. It can use the seed(n=None) method to initialize the random number generator. If there is no parameter or the parameter is None, a real random number (if supported) is used as the seed.

Application scenarios of the random module include:

1. It is used for some calculations or simulations related to probability or statistics, such as coin flipping, dice rolling, lottery drawing, etc.
2. It is used to realize some randomized functions or effects, such as password generation, verification code generation, game design, etc.
3. It is used to learn or teach some knowledge or skills related to random numbers, such as pseudo-random numbers, seeds, distribution, etc.

Notes on the random module include:

1. The random module implements a subset of the CPython module1 and only supports 32-bit integers1, so it is not fully compatible with the functions and performance of CPython.
2. The random module uses a pseudo-random number generator (PRNG), which is a deterministic random number generator based on algorithms and seeds1, so its randomness and security cannot be guaranteed. If you need higher quality random numbers, you can use os.urandom() method 2 to generate truly random bytes.
3. The callback function used by the random module is executed in the interrupt context 1. It needs to be as short and fast as possible, and avoid complex or time-consuming operations, so as not to affect system performance and stability.

The following are several practical application cases of MicroPython's built-in module random:

Case 1: Use the random() method to generate 10 random floating point numbers in the range [0.0, 1.0) and print the results

# 导入random模块
import random

# 循环10次
for i in range(10):
    # 调用random()方法,并返回一个[0.0, 1.0)区间内的随机浮点数
    r = random.random()
    # 打印结果
    print(r)

Case 2: Use the choice() method to randomly select an element from a list and print the result

# 导入random模块
import random

# 创建一个列表对象,包含一些元素
l = ['apple', 'banana', 'cherry', 'durian', 'elderberry']

# 调用choice()方法,并从列表中随机选择一个元素
c = random.choice(l)

# 打印结果
print(c)

Case 3: Implement a simple number guessing game using the seed() method and the randint() method

# 导入random模块
import random

# 使用当前时间作为种子初始化随机数生成器
random.seed()

# 生成一个[1, 100]区间内的随机整数作为答案
answer = random.randint(1, 100)

# 设置猜测次数为10
guesses = 10

# 打印欢迎信息和提示信息
print('Welcome to the guess the number game!')
print('I have chosen a number between 1 and 100.')
print('You have 10 chances to guess it.')

# 循环猜测
while guesses > 0:
    # 获取用户的输入,并转换为整数
    guess = int(input('Please enter your guess: '))
    # 如果猜对了,打印恭喜信息并结束游戏
    if guess == answer:
        print('Congratulations! You guessed it!')
        break
    # 如果猜错了,打印提示信息并减少猜测次数
    else:
        # 如果猜大了,打印太大的提示
        if guess > answer:
            print('Too high.')
        # 如果猜小了,打印太小的提示
        else:
            print('Too low.')
        # 减少猜测次数
        guesses -= 1
        # 如果还有剩余次数,打印剩余次数
        if guesses > 0:
            print('You have', guesses, 'chances left.')
# 如果用完了所有次数,打印失败信息和答案
else:
    print('Sorry, you ran out of chances.')
    print('The answer was', answer)

Case 4: Generate random integers:

import random

# 生成一个范围在1到10之间的随机整数
random_int = random.randint(1, 10)
print("Random Integer:", random_int)

In this example, we use the randint() function of the random module to generate a random integer in the range 1 to 10. Then, we print out the generated random integer.

Case 5: Randomly select elements from a list:

import random

# 定义一个列表
fruits = ["apple", "banana", "orange", "mango", "kiwi"]

# 从列表中随机选择一个元素
random_fruit = random.choice(fruits)
print("Random Fruit:", random_fruit)

In this example, we use the random module's choice() function to randomly select an element from a list. We define a fruit list fruits, and then use the choice() function to select a random fruit. Finally, we print out the selected random fruit.

Case 6: Disturbing the order of the list:

import random

# 定义一个列表
cards = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]

# 打乱列表的顺序
random.shuffle(cards)
print("Shuffled Cards:", cards)

In this example, we use the shuffle() function of the random module to shuffle the order of a list. We define a list of playing cards, cards, and then use the shuffle() function to randomly shuffle the order of the cards. Finally, we print out the order of the shuffled cards. These practical application examples demonstrate the capabilities of using MicroPython's built-in module random. By using the random module, you can generate random integers, randomly select elements from lists, and shuffle lists. These functions are useful in scenarios such as games, randomized data, and simulated experiments.

Case 7: Generate random numbers

import random

# 生成一个随机整数
random_int = random.randint(1, 10)
print("随机整数:", random_int)

# 生成一个随机浮点数
random_float = random.uniform(0.0, 1.0)
print("随机浮点数:", random_float)

# 从列表中随机选择一个元素
fruits = ["apple", "banana", "orange", "grape"]
random_fruit = random.choice(fruits)
print("随机水果:", random_fruit)

In this example, we imported the random module and used it to generate random numbers. First, we use the randint() function to generate a random integer within a specified range, and then print the result. Next, we use the uniform() function to generate a random floating point number within the specified range and print the result. Finally, we use the choice() function to randomly select an element from the list and print the result. This example shows how to use the random module to generate random numbers.

Case 8: Random shuffling

import random

# 创建一个有序列表
cards = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]

# 随机洗牌
random.shuffle(cards)

# 打印洗牌后的列表
print("洗牌后的列表:", cards)

In this example, we import the random module and use it to perform a random shuffle operation. We create an ordered list of cards and then use the shuffle() function to shuffle the list. Finally, we print the shuffled list, showing the effect of random shuffling.

Case 9: Generate random password

import random
import string

# 定义密码长度
password_length = 8

# 生成随机密码
password = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(password_length))

# 打印随机密码
print("随机密码:", password)

In this example, we import the random and string modules and use them to generate random passwords. We first define the length password_length of the password, and then use the list comprehension and the join() function to generate a random password of the specified length. In the list comprehension, we use the set of letters and numbers string.ascii_letters + string.digits as the selected character set, and then use the random.choice() function to randomly select characters from the character set, and repeatedly generate passwords of the specified length. Finally, we print the generated random password.

These examples show practical use of the random module in MicroPython. The random module provides functions such as generating random numbers, randomly shuffling cards, and generating random passwords. By using the random module, you can implement various randomization functions in MicroPython.

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_41659040/article/details/132775851