|
|||
|
The randrange, random and uniform Functions:-
The standard library's random module contains numerous functions for working with random numbers. In addition to the randint function, you might find the randrange, random, and uniform functions useful. (To use any of these functions you need to write import random at the top of your program.) The randrange function takes the same arguments as the range function. The difference is that the randrange function does not return a list of values. Instead, it returns a randomly selected value from a sequence of values. For example, the following statement assigns a random number in the range of 0 through 9 to the number variable: number = random.randrange(l0) The argument, in this case 10, specifies the ending limit of the sequence of values. The function will return a randomly-selected number from the sequence of values 0 up to, but not including, the ending limit. The following statement specifies both a starting value and an ending limit for the sequence: number = random.randrange(5, 10) When this statement executes, a random number in the range of 5 through 9 will be assigned to number. The following statement specifies a starting value, an ending limit, and a step value: number = random.randrange(0, 101, 10) In this statement the randrange function returns a randomly selected value from the following sequence of numbers: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100] Both the randint and the randrange functions return an integer number. The random function returns, however, returns a random floating-point number. You do not pass any arguments to the random function. When you call it, it returns a random floating point number in the range of 0.0 up to 1.0 (but not including 1.0). Here is an example: number = random.random() The uniform function also returns a random floating-point number, but allows you to specify the range of values to select from. Here is an example: number = random.uniform(l.0, 10.0) In this statement the uniform function returns a random floating-point number in the range of 1.0 through 10.0 and assigns it to the number variable. |