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

# 1. StartProgramming-1-7 列表Lists

In the loops in previous examples, we used code like this:

`for x in 1, 2, 3, 4:`

The series of numbers 1, 2, 3, 4 is a called a sequence, and loops can iterate over the members of any sequence.

What this code means is: "set x = 1 and do the following things, then set x = 2, and do these things again", etc, until the end of the sequence.

A sequence like this will often be written either in square brackets [1, 2, 3, 4] (called a list) or in parentheses (1, 2, 3, 4) (a tuple).

The difference between these is a bit subtle.

A list can be changed after it is constructed (we say that it is mutable), whereas a tuple cannot be changed (immutable).

The differences will become more clear later, but I will use the word "list" for now to keep things simpler.

## 1.1. 创建Create

It is very common to give the list a name instead of typing the list itself in to a loop statement. When creating a list like this, brackets are required.

You can make an empty list:

`empty_list = []`

or if you know exactly what needs to be in the list, just go ahead and fill it up:

`sides = ['side one', 'side two', 'side three', 'side four']`

Sometimes, especially if the elements in the list are long, it looks better to break it up in to multiple lines. As long as you are inside the brackets, that is fine:

```   1 verbose_sides = [
2   'The side known as "side one"',
3   'This one is side two',
4   'Another side, called "side three"',
5   'The final side, or side four'
6 ]
```

## 1.2. 改变Mutate

Lists are mutable, but what exactly does that mean?

Lists are objects with special methods built in to make it easy to add, remove, sort, and find things that are in the list.

For instance, if you did not know beforehand what words you wanted to print around the square, you could add them to the list as you found out:

```   1 from pygsear.Widget import Dialog_LineInput
2 sides = []
3 for side in 'first', 'second', 'third', 'fourth':
4     message = 'Enter the name of the %s side' % side
5     namegetter = Dialog_LineInput(message=message)
6     name = namegetter.modal()
7     sides.append(name)
```

## 1.3. 循环Iterate

In this case, the members in the list sides are not numbers, but text (called strings), so we could not use them in math formulas, but we could use them like this:

```   1 for word in sides:
2     write(word)
3     forward(180)
4     right(90)
```

Or, more generally:

```   1 def messageSquare(messages=['one', 'two', 'three', 'four']):
2     for word in messages:
3         write(word)
4         forward(180)
5         right(90)
```

The function messageSquare() takes one parameter, and if called without a value it will use the default argument ['one', 'two', 'three', 'four'].

In other words, a call to:

`messageSquare()`

is the same as if you called it:

`messageSquare(['one', 'two', 'three', 'four'])`

You can also call it with a totally different list:

`messageSquare(['penguins', 'like', 'to eat', 'herring'])`

or with a list created before:

`messageSquare(sides)`

## 1.4. 排列Range

The function messageSquare() has a problem similar to the problem with the function at the end of the last page. If you pass in a sequence which is longer or shorter than 4 elements, it is probably not going to do what you want.

Try it now. If the sequence is less than 4 elements, it will not make a complete square. If the sequence is more than 4 elements, it will write over the words on previous sides.

```   1 reset()
2 messageSquare(['one', 'side', 'short'])
3 reset()
4 messageSquare(['one', 'side', 'too', 'many', 'here'])
```

To get around this problem, we need to figure out what angle to turn from the number of sides we want the shape to have.

Using the built-in function range() we can make a very general function to draw polygons:

```   1 def poly(sides, length):
2     angle = 360.0 / sides
3     for side in range(sides):
4         forward(length)
5         right(angle)
```

The function range() takes a number, and returns a list with that many elements.

That means: if sides=5 then range(sides) is the same as range(5) and it returns [0, 1, 2, 3, 4]

So the function call poly(5, 10) will draw a five-sided figure with sides of length 10.

Now we can make almost any sort of regular polygon by giving poly() the number of sides and the length of each side:

```   1 poly(5, 20)
2 poly(6, 30)
3 poly(100, 3)
```

The last one will probably be indistinguishable from a circle. In fact, if pete did not have a built in circle() method, that would be a good way to simulate a circle.

StartProgramming-1-7 (last edited 2009-12-25 07:13:54 by localhost)