|
|||
|
Generating Random Numbers:-
Random numbers are useful for lots of different programming tasks. The following are just a few examples. 1. Random numbers are commonly used in games. For example, computer games that let the player roll dice use random numbers to represent the values of the dice. Programs that show cards being drawn from a shuffled deck use random numbers to represent the face values of the cards. 2. Random numbers are useful in simulation programs. In some simulations, the computer must randomly decide how a person, animal, insect, or other living being will behave. Formulas can be constructed in which a random number is used to determine various actions and events that take place in the program. 3. Random numbers are useful in statistical programs that must randomly select data for analysis. 4. 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 any of these functions you first need to write this import statement at the top of your program: import random This statement causes the interpreter to load the contents of the random module into memory. This makes all of the functions in the random module available to your program. The first random-number generating function that we will discuss is named randint. Because the randint function is in the random module, we will need to use dot notation to refer to it in our program. In dot notation, the function's name is random. randint. On the left side of the dot (period) is the name of the module, and on the right side of the dot is the name of the function. The following statement shows an example of how you might call the randint function. number = random.randint(1, 100) The part of the statement that reads random. randint (1, 100) is a call to the randint function. Notice that two arguments appear inside the parentheses: 1 and 100. These arguments tell the function to give an integer random number in the range of 1 through 100. (The values 1 and 100 are included in the range.) Figure (given below) illustrates this part of the statement. ![]() (A statement that calls the random function.) Notice that the call to the randint function appears on the right side of an = operator. When the function is called, it will generate a random number in the range of 1 through 100 and then return that number. The number that is returned will be assigned to the number variable, as shown in the Figure (specified below). ![]() (The random function returns a Value.) |