|
| 1 | +import random |
| 2 | +import os |
| 3 | +import string |
| 4 | +import secrets |
| 5 | + |
| 6 | +# generate random integer between a and b (including a and b) |
| 7 | +randint = random.randint(1, 500) |
| 8 | +print("randint:", randint) |
| 9 | + |
| 10 | +# generate random integer from range |
| 11 | +randrange = random.randrange(0, 500, 5) |
| 12 | +print("randrange:", randrange) |
| 13 | + |
| 14 | +# get a random element from this list |
| 15 | +choice = random.choice(["hello", "hi", "welcome", "bye", "see you"]) |
| 16 | +print("choice:", choice) |
| 17 | + |
| 18 | +# get 5 random elements from 0 to 1000 |
| 19 | +choices = random.choices(range(1000), k=5) |
| 20 | +print("choices:", choices) |
| 21 | + |
| 22 | +# generate a random floating point number from 0.0 <= x <= 1.0 |
| 23 | +randfloat = random.random() |
| 24 | +print("randfloat between 0.0 and 1.0:", randfloat) |
| 25 | + |
| 26 | +# generate a random floating point number such that a <= x <= b |
| 27 | +randfloat = random.uniform(5, 10) |
| 28 | +print("randfloat between 5.0 and 10.0:", randfloat) |
| 29 | + |
| 30 | +l = list(range(10)) |
| 31 | +print("Before shuffle:", l) |
| 32 | +random.shuffle(l) |
| 33 | +print("After shuffle:", l) |
| 34 | + |
| 35 | +# generate a random string |
| 36 | +randstring = ''.join(random.sample(string.ascii_letters, 16)) |
| 37 | +print("Random string with 16 characters:", randstring) |
| 38 | + |
| 39 | +# crypto-safe byte generation |
| 40 | +randbytes_crypto = os.urandom(16) |
| 41 | +print("Random bytes for crypto use using os:", randbytes_crypto) |
| 42 | + |
| 43 | +# or use this |
| 44 | +randbytes_crypto = secrets.token_bytes(16) |
| 45 | +print("Random bytes for crypto use using secrets:", randbytes_crypto) |
| 46 | + |
| 47 | +# crypto-secure string generation |
| 48 | +randstring_crypto = secrets.token_urlsafe(16) |
| 49 | +print("Random strings for crypto use:", randstring_crypto) |
| 50 | + |
| 51 | +# crypto-secure bits generation |
| 52 | +randbits_crypto = secrets.randbits(16) |
| 53 | +print("Random 16-bits for crypto use:", randbits_crypto) |
0 commit comments