（首页）开始编程之旅 翻译自Lee Harr的Start Programming

# 1. StartProgramming-2-2 随机Random

The random module is one which is used frequently in game code. The most common uses are random.randrange(), random.uniform(), random.choice() and random.shuffle().

random 组件是游戏代码中经常用到的。最常用的是random.randrange()， random.uniform()， random.choice() 和 random.shuffle()。

I will summarize the use of these common functions here, but remember that you can also use the help() function to read more:

```   1 import random
2 from random import choice, shuffle
3 help(random.randrange)
4 help(random.uniform)
5 help(choice)
6 help(shuffle)
```

## 1.1. randrange

randrange() works somewhat like the range() function. It is used to return random integers.

randrange() 工作有点像 range() 函数。它通常用来返回一个随机的整数。

To generate 5 random integers from 1 to 10, try this:

```   1 for loop in range(5):
2     print loop, random.randrange(1, 11)
```

Remember that range(5) is [0, 1, 2, 3, 4]. There are five elements in the list, but starting with 0. randrange() is the same way. It could return the first number, but never the last one. So, randrange(1, 11) will return one of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

## 1.2. shuffle

shuffle() will put the elements of a list in random order.

shuffle() 将会把一个列表中的元素随机排序。

```   1 bears = ['polar', 'grizzly', 'black', 'koala', 'panda']
2 print bears
3 random.shuffle(bears)
4 print bears
5 random.shuffle(bears)
6 print bears
7 random.shuffle(bears)
8 print bears
```

## 1.3. choice

choice() will return a randomly selected element of any list. So random.randrange(1, 11) would be equivalent to random.choice(range(1, 11))

choice() 将会从任何列表中返回一个随机选择的元素。所以random.randrange(1, 11)就相当于random.choice(range(1, 11))

Also, choice() can work on lists of anything, like lists of strings:

```   1 for choice_number in range(5):
2     bear = random.choice(bears)
3     print 'number', choice_number, 'is a', bear, 'bear'
```

Or it can even work on lists of penguins:

```   1 from penguin import Penguin
2
3 # First, make an empty list
4 # and fill it with 10 penguins
5 penguins = []
6 for count in range(1, 11):
7     print 'creating penguin number', count
8     p = Penguin()
9     p.moveTo('random')
10     penguins.append(p)
11
12 # Then make them explode randomly
13 for explosion in range(50):
14     penguin = random.choice(penguins)
15     penguin.blast()
```

## 1.4. uniform

uniform() is for random numbers that are not integers:

uniform() is for random numbers that are not integers:

```   1 for loop in range(5):
2     print random.uniform(0, 10)
3     print random.uniform(-10, 0)
```

Similar to randrange() the result returned could be the first number, but it will never be the second number.

Similar to randrange() the result returned could be the first number, but it will never be the second number.

StartProgramming-2-2 (last edited 2009-12-25 07:14:53 by localhost)