logo


Tag: randint

Random numbers

Using the random module, we can generate pseudo-random numbers. The function random() generates a random number between zero and one [0, 0.1 .. 1].  Numbers generated with this module are not truly random but they are enough random for most purposes.

Related Course:
Complete Python Bootcamp: Go from zero to hero in Python 3

Random number between 0 and 1.
We can generate a (pseudo) random floating point number with this small code:

from random import *

print(random()) # Generate a pseudo-random number between 0 and 1.

Generate a random number between 1 and 100
To generate a whole number (integer) between one and one hundred use:

from random import *

print(randint(1, 100)) # Pick a random number between 1 and 100.

This will printa random integer. If you want to store it in a variable you can use:

from random import *

x = randint(1, 100) # Pick a random number between 1 and 100.
print(x)

Random number between 1 and 10
To generate a random floating point number between 1 and 10 you can use the uniform() function

from random import *

print(uniform(1, 10))

Picking a random item from a list

Fun with lists
We can shuffle a list with this code:

from random import *

items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
shuffle(items)
print(items)

To pick a random number from a list:

from random import *

items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

x = sample(items, 1) # Pick a random item from the list
print(x[0])

y = sample(items, 4) # Pick 4 random items from the list
print(y)

We can do the same thing with a list of strings:

from random import *

items = ['Alissa','Alice','Marco','Melissa','Sandra','Steve']

x = sample(items, 1) # Pick a random item from the list
print(x[0])

y = sample(items, 4) # Pick 4 random items from the list
print(y)

Download Python Exercises