Exercise: Chapter 3 (14-17)

14.

Using words.sort():

>>> words =["banana", "pineapple", "peach", "apple", "orange", "mango", "maron",
 "nuts"]
>>> words
['banana', 'pineapple', 'peach', 'apple', 'orange', 'mango', 'maron', 'nuts']
>>> words.sort()
>>> words
['apple', 'banana', 'mango', 'maron', 'nuts', 'orange', 'peach', 'pineapple']

After sorting, the sequence in the list was sorted permanently.

Using sorted(words):

>>> words =["banana", "pineapple", "peach", "apple", "orange", "mango", "maron",
 "nuts"]
>>> sorted(words)
['apple', 'banana', 'mango', 'maron', 'nuts', 'orange', 'peach', 'pineapple']
>>> words
['banana', 'pineapple', 'peach', 'apple', 'orange', 'mango', 'maron', 'nuts']

This sorting is just temporary.

15.

>>> "3" * 7
'3333333'
>>> 3 * 7
21
>>> int("3") * 7
21
>>> str(3) * 7
'3333333'
>>>

16.

>>> monty
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'monty' is not defined
>>> from test import msg
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name msg
>>> from test import *
>>> monty
'Monty Python'

17.

In general, if using positive values, the display will be aligned to right. For negative, it will be left aligned.

>>> string = 'abc'
>>> print '%6s' % string
   abc
>>> print '%-6s' % string
abc
>>> string = 'abcdefghijk'
>>> print '%6s' % string
abcdefghijk
>>> print '%-6s' % string
abcdefghijk
>>>

There is no difference to display longer than 6.