Difference between revisions of "11 Random number generator"

From Banana Pi Wiki
Jump to: navigation, search
(random number)
Line 15: Line 15:
  
 
=random number=
 
=random number=
 +
 +
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)).

Revision as of 01:15, 20 February 2019

Random number generator

randomness

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 number

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)).