Опубликован: 12.07.2013 | Доступ: свободный | Студентов: 985 / 36 | Длительность: 37:41:00
Лекция 9:

Hangman

Multi-line Strings

Ordinarily when you write strings in your source code, the string has to be on one line. However, if you use three single-quotes instead of one single-quote to begin and end the string, the string can be on several lines:

>>> fizz = '''Dear Alice,
I will return home at the end of the month. I will see you then.
Your friend,
Bob'''
>>> print fizz
Dear Alice,
I will return home at the end of the month. I will
see you then.
Your friend,
Bob
>>>

If we didn't have multi-line strings, we would have to use the \n escape character to represent the new lines. But that can make the string hard to read in the source code, like in this example:

>>> fizz = 'Dear Alice,\nI will return home at the
end of the month. I will see you then.\nYour
friend,\nBob'
>>> print fizz
Dear Alice,
I will return home at the end of the month. I will
see you then.
Your friend,
Bob
>>>

Multi-line strings do not have to keep the same indentation to remain in the same block. Within the multi-line string, Python ignores the indentation rules it normally has for where blocks end.

def writeLetter():
  # inside the def-block 
  print '''Dear Alice,
How are you? Write back to me soon.

Sincerely,
  Bob''' # end of the multi-line string and print 
statement
  print 'P.S. I miss you.' # still inside the 
def-block

writeLetter() # This is the first line outside the 
def-block.

Constant Variables

You may have noticed that HANGMANPICS's name is in all capitals. This is the programming convention for constant variables. Constants are variables whose values do not change throughout the program. Although we can change HANGMANPICS just like any other variable, the all-caps reminds the programmer to not write code that does so.

Constant variables are helpful for providing descriptions for values that have a special meaning. Since the multi-string value never changes, there is no reason we couldn't copy this multi-line string each time we needed that value. The HANGMANPICS variable never varies. But it is much shorter to type HANGMANPICS than it is to type that large multi-line string.

Also, there are cases where typing the value by itself may not be obvious. If we set a variable eggs = 72, we may forget why we were setting that variable to the integer 72. But if we define a constant variable DOZEN = 12, then we could set eggs = DOZEN * 6 and by just looking at the code know that the eggs variable was set to six dozen.

Like all conventions, we don't have to use constant variables, or even put the names of constant variables in all capitals. But doing it this way makes it easier for other programmers to understand how these variables are used. (It even can help you if you are looking at code you wrote a long time ago.)

Lists

I will now tell you about a new data type called a list. A list value can contain several other values in it. Try typing this into the shell: ['apples', 'oranges', 'HELLO WORLD']. This is a list value that contains three string values. Just like any other value, you can store this list in a variable. Try typing spam = ['apples', 'oranges', 'HELLO WORLD'], and then type spam to view the contents of spam.

>>> spam = ['apples', 'oranges', 'HELLO WORLD'] 
>>> spam
 ['apples', 'oranges', 'HELLO WORLD'] 
>>>

Lists are a good way to store several different values into one variable. The individual values inside of a list are also called items. Try typing: animals = ['aardvark', 'anteater', 'antelope', 'albert'] to store various strings into the variable animals. The square brackets can also be used to get an item from a list. Try typing animals[0], or animals[1], or animals[2], or animals[3] into the shell to see what they evaluate to.

>>> animals = ['aardvark', 'anteater', 'antelope',
'albert']
>>> animals[0]
'aardvark'
>>> animals[1]
'anteater'
>>> animals[2]
'antelope'
>>> animals[3]
'albert'
>>>

The number between the square brackets is the index. In Python, the first index is the number 0 instead of the number 1. So the first item in the list is at index 0, the second item is at index 1, the third item is at index 2, and so on. Lists are very good when we have to store lots and lots of values, but we don't want variables for each one. Otherwise we would have something like this:

>>> animals1 = 'aardvark' 
>>> animals2 = 'anteater' 
>>> animals3 = 'antelope' 
>>> animals4 = 'albert' 
>>>

This makes working with all the strings as a group very hard, especially if you have hundreds or thousands (or even millions) of different strings that you want stored in a list. Using the square brackets, you can treat items in the list just like any other value. Try typing animals[0] + animals[2] into the shell:

>>> animals[0] + animals[2]
'aardvarkantelope'
>>>

Because animals[0] evaluates to the string 'aardvark' and animals[2] evaluates to the string 'antelope', then the expression animals[0] + animals [2] is the same as 'aardvark' + 'antelope'. This string concatenation evaluates to 'aardvarkantelope'.

What happens if we enter an index that is larger than the list's largest index? Try typing animals[4] or animals[99] into the shell:

>>> animals = ['aardvark', 'anteater', 'antelope',
'albert']
>>> animals[4]
Traceback (most recent call last):
File "", line 1, in
animals[4]
IndexError: list index out of range
>>> animals[99]
Traceback (most recent call last):
File "", line 1, in
animals[99]
IndexError: list index out of range
>>>

If you try accessing an index that is too large, you will get an index error.

Changing the Values of List Items with Index Assignment

You can also use the square brackets to change the value of an item in a list. Try typing animals[1] = 'ANTEATER', then type animals to view the list.

>>> animals = ['aardvark', 'anteater', 'antelope',
'albert']
>>> animals[1] = 'ANTEATER'
>>> animals
['aardvark', 'ANTEATER', 'antelope', 'albert']
>>>

The second item in the animals list has been overwritten with a new string.

List Concatenation

You can join lists together into one list with the + operator, just like you can join strings.

When joining lists, this is known as list concatenation. Try typing [1, 2, 3, 4] + ['apples', 'oranges'] + ['Alice', 'Bob'] into the shell:

>>> [1, 2, 3, 4] + ['apples', 'oranges'] +
['Alice', 'Bob']
[1, 2, 3, 4, 'apples', 'oranges', 'Alice', 'Bob']
>>>

Notice that lists do not have to store values of the same data types. The example above has a list with both integers and strings in it.

The in Operator

The in operator makes it easy to see if a value is inside a list or not. Expressions that use the in operator return a boolean value: True if the value is in the list and False if the value is not in the list. Try typing 'antelope' in animals into the shell:

>>> animals = ['aardvark', 'anteater', 'antelope',
'albert']
>>> 'antelope' in animals
True
>>>

The expression 'antelope' in animals returns True because the string 'antelope' can be found in the list, animals. (It is located at index 2.)

But if we type the expression 'ant' in animals, this will return False because the string 'ant' does not exist in the list. We can try the expression 'ant' in ['beetle', 'wasp', 'ant'], and see that it will return True.

>>> animals = ['aardvark', 'anteater', 'antelope',
'albert']
>>> 'antelope' in animals
True
>>> 'ant' in animals
False
>>> 'ant' in ['beetle', 'wasp', 'ant']
True
>>>

The in operator also works for strings as well as lists. You can check if one string exists in another the same way you can check if a value exists in a list. Try typing 'hello' in 'Alice said hello to Bob.' into the shell. This expression will evaluate to True.

>>> 'hello' in 'Alice said hello to Bob.'
True
>>>

Removing Items from Lists with del Statements

You can remove items from a list with a del statement. ("del" is short for "delete.") Try creating a list of numbers by typing: spam = [2, 4, 6, 8, 10] and then del spam[1]. Type spam to view the list's contents:

>>> spam = [2, 4, 6, 8, 10]
>>> del spam[1]
>>> spam
[2, 6, 8, 10]
>>>

Notice that when you deleted the item at index 1, the item that used to be at index 2 became the new index 1. The item that used to be at index 3 moved to be the new index 2. Everything above the item that we deleted moved down one index. We can type del spam[1] again and again to keep deleting items from the list:

>>> spam = [2, 4, 6, 8, 10]
>>> del spam[1]
>>> spam
[2, 6, 8, 10]
>>> del spam[1]
>>> spam
[2, 8, 10]
>>> del spam[1]
>>> spam
[2, 10]
>>>

Just remember that del is a statement, not a function or an operator. It does not evaluate to any return value.