# LoPy4 random number method (solved)

• Hi, just looking for the library/function to generate a random number for three choices.

like
import random

I've tried urandom, os.random,
pyb as per this post
https://forum.micropython.org/viewtopic.php?t=2727

TIA Dave

• @robert-hh Thanks

What I want here is to simulate some users doing 1 of 3 things, so:

``````>>> print(uos.urandom(1)[0] %3)
0
>>> print(uos.urandom(1)[0] %3)
0
>>> print(uos.urandom(1)[0] %3)
1
>>>
>>> print(uos.urandom(1)[0] %3)
2
>>> print(uos.urandom(1)[0] %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.

Dave

• ``````n = os.urandom(1)[0]
``````

also results in a number of 0-255. To get a number of 0-3, just use `n % 4` or `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.

• @dan
TNX, Looks like what I want..(note no 'u', just 'os')

os.urandom(3) gives results like

``````>>> os.urandom(3)
b'\x99\xcc\xe6'
``````

OK
os.urandom(1) gives me a single byte, and this is how to make it an integer.
I've tried:

``````>>> 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'?

regards
Dave

• @pybuggz A search for "random" in the documentation reveals that link:
https://docs.pycom.io/firmwareapi/micropython/ucrypto#methods