11 Random number generator
Random number generator
What is randomness? Randomness means unpredictability. Real randomness exists only in the natural world. Where lightning strikes randomly; If a storm is brewing somewhere, you can be pretty sure there will be lightning, but you can't predict exactly where it will be, so don't stand under a tree. For example, the teacher wanted the students to get up to answer the question, but no one raised his hand to answer the question, at this time the teacher shouted a seat number, the seat number is also random.
MicroPython comes with a random number module that makes it easy to introduce random Numbers into your code. For example, here's an example of how to scroll a random name on the screen:
from microbit import * import random names = ["Mary", "Yolanda", "Damien", "Alia", "Kushal", "Mei Xiu","Zoltan" ] display.scroll(random.choice(names))
Lists (names) contain strings of 7 different names. Using the random. Choice method, the list (names) is taken as an argument and the randomly selected items are returned. This item (the name chosen at random) will be a parameter to display.scroll. The effect is that you can see the randomly selected names on the led display panel
Random Numbers are very useful.They're very common in games, like dice.MicroPython provides some useful random number methods.Let's make a simple die. Sample code
from microbit import * import random display.show(str(random.randint(1, 6)))
Each time the board executes this function, it displays a number between 1 and 6. Random. Randint () returns an integer (including 6) between the two parameters 1 and 6. Note that since the show function requires a character to display, we use the STR function here to convert the numeric value to a character (for example, we converted 6 to "6" through STR (6)).
If you want a number between 0 and N, use the random. Randrange () function. If you give it a parameter, it returns a random integer, but not the value of the parameter N (unlike random.Random. Random (), this function will only return floating point Numbers between 0.0 and 1.0. So how to generate larger floating point Numbers
from microbit import * import random answer = random.randrange(100) + random.random() display.scroll(str(answer))