CHAPTER 10 (Web design conference) BATTERIES INCLUDED 229 random number
CHAPTER 10 BATTERIES INCLUDED 229 random number in the range from 1 to 10 (inclusive), you would use randrange(1,11) (or, alternatively, randrange(10)+1), and if you want a random odd positive integer lower than 20, you would use randrange(1,20,2). The function random.choice chooses (uniformly) a random element from a given sequence. The function random.shuffleshuffles the elements of a (mutable) sequence randomly, such that every possible ordering is equally likely. The function random.sample chooses (uniformly) a given number of elements from a given sequence, making sure that they re all different. Note For the statistically inclined, there are other functions similar to uniformthat return random numbers sampled according to various other distributions, such as betavariate, exponential, Gaussian, and several others. Examples Generating a random date in a given range. In the following examples, I use several of the functions from the time module described previously. First, let s get the real numbers representing the limits of the time interval (the year 2005). You do that by expressing the date as a time tuple (using -1 for day of the week, day of the year, and daylight savings, making Python calculate that for itself) and calling mktime on these tuples: from random import * from time import * date1 = (2005, 1, 1, 0, 0, 0, -1, -1, -1) time1 = mktime(date1) date2 = (2006, 1, 1, 0, 0, 0, -1, -1, -1) time2 = mktime(date2) Then you generate a random number uniformly in this range (the upper limit excluded): >>> random_time = uniform(time1, time2) Then, you simply convert this number back to a legible date: >>> print asctime(localtime(random_time)) Mon Jun 24 21:35:19 2005 Creating an electronic die-throwing machine. For this example, let s ask the user how many dice to throw, and how many sides each one should have. The die-throwing mechanism is implemented with randrange and a for loop: from random import randrange num = input(’How many dice? ‘) sides = input(’How many sides per die? ‘) sum = 0 for i in range(num): sum += randrange(sides) + 1 print ‘The result is’, sum
From our experience, we can recommend PHP Web Hosting services, if you need affordable webhost to host and run your web application.