***Welcome to ashrafedu.blogspot.com ***This website is maintained by ASHRAF***
***Use tabs for Content***

POSTS

    Generating Random Numbers

    Random numbers are useful for lots of different programming tasks. The following are just a few examples.

    • Random numbers are commonly used in games.

    • Random numbers are useful in simulation programs.

    • Random numbers are useful in statistical programs that must randomly select data for analysis.

    • Random numbers are commonly used in computer security to encrypt sensitive data.

    Python provides several library functions for working with random numbers. These functions are stored in a module named random in the standard library.

    To use functions form random module, import statement is used at the top of your program:

    import random

    This statement causes the interpreter to load the contents of the random module into memory.

    1. randint ( random-number generating function)

    The following statement shows an example of how you might call the randint function.

    number = random.randint (1, 100)

    this function takes two arguments for range to generate random numbers.

    2. The randrange, random, and uniform Functions

    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(10)

    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)

    Both the randint and the randrange functions return an integer number.

    The random function returns a random floating-point number. No arguments are passed to the random function. When a call is made to 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 specifying the range of values to select from.

    Here is an example:

    number = random.uniform(1.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.