logo

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

BackNext

20 thoughts on “Random numbers


  1. Dimas Bagus Aditya
    - January 31, 2018

    Hello Frank,
    I can’t run everything in this tutorial. why?

    Traceback (most recent call last):
    File "random.py", line 13, in
    from random import *
    File "/home/insight/Desktop/python/pyspot/random.py", line 16, in
    shuffle(items)
    NameError: name 'shuffle' is not defined

    1. Frank
      - February 8, 2018

      You named your program “random.py”, give it a different name because Python is trying to import from the module random.

  2. Tim Osborn
    - June 3, 2017

    Quick thanks for the great comments thread – it elevated a my super basic reference search to a whole ‘nother level – kudos!

Leave a Reply

Login disabled