Made Easy Apps at Texas Instruments Calculus Made Easy Review from Collegeboard.com Made Easy Apps at Mathforum Secured by Paypal

Python Random Number Generator


I will show you how to quickly generate Random Numbers using Python's Random Number Generator.
1) Here is an easy example that generate a random number between 0 and 1 (copy and paste code.):

import random

print(random.random())

Note: you will always have to first import "random", which is Python's Random Number Library.
Then, random.random() generates a random number between 0 and 1 (Example 0.6297148070155475) and the print command displays it to the user. See belows program execution.

Python Random Number Generator


2) To generate a random integer between say 1 and 100 (including 1 and 100):

import random

print(random.randint(1, 100))

Here, random.randint() generates a random integer between 1 and 100 (Example: 83) and the print command displays again it to the user.


3) To generate a list of 5 random integers between 1 and 100 (copy and paste code again.):

import random

for _ in range(5):
	value = randint(0, 100)
	print(value)

Here, the for loop runs 5 times generates a random integer between 1 and 100 each time stored in variable called 'value' (Example: 73,12,94,44,63) and the print command displays them again to the user.


4) To generate a list of 5 random items from a given list do this (copy and paste code again.):

import random

mylist = ["apple", "banana", "cherry"]

print(random.choices(mylist,  k = 5))

Here, random.choices() randomly selects a fruit 10 times. (Example: cherry, banana, banana, apple, banana) and the print command displays them again to the user.


5) To shuffle a list of given items do this (copy and paste code again.):

import random

mylist = ["apple", "banana", "cherry"]
random.shuffle(mylist)

print(mylist)

Here, random.shuffle() shuffles the given fruits. (Example: {cherry, banana, apple} ) and the print command displays them again to the user.


6) To change the output of the random functions you would change the seed, for example use random.seed(10) or random.seed(82) before calling a random function.
Different seeds result in different random outputs for a truly random look;-)
Otherwise random numbers generated by computers are actually pseudo-random.

Try it for yourself.




Or try the W3 School Python Compiler: Python Random Number Generator .

OTHER RANDOM NUMBER GENERATORS


Create a List of Random Number
Password Generator (scroll down to see Password)


Online Calculators with Steps (Free)