3 Random
3 Random
RANDOM
6
RANDRANGE
RANDINT
Random
CHOICE
CHOICES
SHUFFLE
New Randomize Output Assignment
How to use random.randrange(): There are multiple variants of random.randrange() function let see
how to use it with the help of different examples.
The Syntax of random.randrange() function
random.randrange(start, stop[, step])
random.randrange() function takes three parameters. Out of three parameters, two is optional. i.e., start and
step is the optional parameter.
Note: randrange (start, stop, step) doesn’t consider the last item i.e. it is exclusive. For example, randrange
(10,20,1) will return any random number from 10 to 19 (exclusive). it will never select 20.
Start argument is the starting number in a range. i.e., lower limit. By default starts with 0 if not specified.
Stop argument is the last number in a range. Stop argument is the upper limit.
The step is a difference between each number in the sequence. The step is optional parameters. The default
value of step is 1 if not specified.
It will raise a ValueError if you used values other than an integer. i.e., You cannot use float value parameters
in
Randint functions:
The Random module contains some very useful functions randint(start, stop, step)
If we wanted a random integer, we can use the randint function Randint accepts two parameters: a lowest and
a highest number. Generate integers between 1,5. The first value should be less than the second.
import random
print random.randint(0, 5)
This will output either 0,1, 2, 3, 4 or 5. #0 to 5 any
If you want a larger number, you can multiply it.
For example, a random number between 0 and 100:
import random
random.random() * 100
Choice functions: Generate a random value from the sequence sequence. random.choice( ['red', 'black',
'green'] ).The choice function can often be used for choosing a random element from a list.
import random
myList = [2, 109, False, 10, "Lorem", 482, "Ipsum"]
random.choice(myList)
Shuffle functions::The shuffle function, shuffles the elements in list in place, so they are in a random
order.
random.shuffle(list)
Example taken from this post on Stackoverflow
from random import shuffle
Page 4 of 10 EDUCATION FOR EVERYONE
DoyPyEdu PLAY WITH PYTHON
x = [[i] for i in range(10)]
shuffle(x)
Output:
# print x gives [[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]]
# o:f course your results will vary
OUTPUT
**********************************