LoPy4 random number method (solved)
Hi, just looking for the library/function to generate a random number for three choices.
complains about no module.
I've tried urandom, os.random,
pyb as per this post
What I want here is to simulate some users doing 1 of 3 things, so:
>>> print(uos.urandom(1) %3) 0 >>> print(uos.urandom(1) %3) 0 >>> print(uos.urandom(1) %3) 1 >>> >>> print(uos.urandom(1) %3) 2 >>> print(uos.urandom(1) %3) 2
simplifies my code and will be OK.
Regarding Micropython, I've 'hacked' a bit of other code at times and this is the first time I'm having to find the functions I need, so little things like 'dir(os)' are gems.
robert-hh last edited by
n = os.urandom(1)
also results in a number of 0-255. To get a number of 0-3, just use
n % 4or
n & 0x3. If the range you need is not a power of 2, then start with a larger random number to reduce non-randomness of the result.
What do you measn with pycompython? if you waht to know the methods of a module, import that module and call dir(module_name), e.g.
import uos dir(uos)
P.S.: uos is the 'Micro' version of os, and MicroPython provides os as the alias to uos.
TNX, Looks like what I want..(note no 'u', just 'os')
os.urandom(3) gives results like
>>> os.urandom(3) b'\x99\xcc\xe6'
os.urandom(1) gives me a single byte, and this is how to make it an integer.
>>> print(int.from_bytes(os.urandom(1),"big")) 60
I want something between 0 and 3, so I need to limit the range somehow..
Also, how do I know which Micropython functions are in 'pycompython'?
dan last edited by
@pybuggz have you tried
robert-hh last edited by robert-hh
@pybuggz A search for "random" in the documentation reveals that link: