Documents
Resources
Learning Center
Upload
Plans & pricing Sign in
Sign Out

Python によるプログラミング入門

VIEWS: 2 PAGES: 182

									Python
                                                                                                      i




Python                                                                           Ruby
                                                                                   Python
                               Python                                                          Python


1.

2.              OS

3.                                      C++

4.

5.

6.

7.

                      Python                                                                   Python



Python                                                                       www.python.org
                                                                               1
                                                                                       (2008          3
        )     2.5.2                                       Python
                                                                                      Python
                                                                 Mark Lutz


    •       Python         (O’Reilly Japan, 1998)

    •       Python                      (O’Reilly Japan, 1998)



    • Mark Lutz:“Programming Python”,(O’Reilly & Associates,Inc. 1996)

                       2                              Python


    •                 M                                        Python                             (
                                        )



1                                                   http://ar.aichi-u.ac.jp/python/
ii



     Python


      • John E.Grayson: “Python and Tkinter Programming” (Manning, 2000)



      •            Python        GUI          I-                       -
          (                            Com Vol.11, No.1,2000)

      •            Python        GUI          II -                 -
          (                            Com Vol.11, No.2,2000)

      •            Python        GUI          III - Text               -
          (                            Com Vol.12, No.1,2001)




     Amazon       Python




     Python




     2008     3   10
                                                                                                                                                                iii




I       Python                                                                                                                                                  1

1      Python                                                                                                                                                    3
 1.1                  . . . . . . . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .    4
 1.2                  . . . . . . . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .    6
 1.3            . . . . . . . . . . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .    7
 1.4                                . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .    7
 1.5                  . . . . . . . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .    7

2                                                                                                                                                                9
 2.1         . . . .    . . . . . . . . . . . .         .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .    9
 2.2      1 . . . .     . . . . . . . . . . . .         .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .    9
 2.3      2 . . . .     . . . . . . . . . . . .         .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   11
       2.3.1                            . . . .         .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   11
       2.3.2                    . . . . . . . .         .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   12
       2.3.3                  . . . . . . . . .         .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   13
       2.3.4                                ...         .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   13
2.4          . . . .    . . . . . . . . . . . .         .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   14

3                                                                                                                                                               15
 3.1                . . . . . . . . . . . .         .   . . .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   15
 3.2                                  . . .         .   . . .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   16
 3.3                                    . .         .   . . .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   17
 3.4                        . . . . . . . .         .   . . .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   20
 3.5                        . . . . . . . .         .   . . .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   22
 3.6                    . . . . . . . . . .         .   . . .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   23
 3.7      2                    1                          .         .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   25
 3.8   Zeller           . . . . . . . . . .         . . . .         .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   27
 3.9   1752       9   . . . . . . . . . . .         . . . .         .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   28

4                                                                                                                                                               31
 4.1                            . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .                                                             31
 4.2                  . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .                                                             34
       4.2.1                            . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .                                                             35
iv

     4.3                                .    .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   38
     4.4                    . . . . . . .    .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   40
     4.5                  . . . . . . . .    .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   41
            4.5.1                 . . . .    .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   41
            4.5.2                                                            .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   41
     4.6                             . . . . . .     .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   43
     4.7                               . . . . .     .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   44
     4.8                       . . . . . . . . .     .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   47
            4.8.1                          . . .     .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   47
            4.8.2                              .     .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   47
     4.9    Boyce                    . . . . . .     .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   50
            4.9.1                    . . . . . .     .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   50
            4.9.2                              .     .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   50
            4.9.3       4.15             . . . .     .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   51


     II        Python                                                                                                                                                53

     1                                                                                                                                                               55
      1.1                  . . . . . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   55
            1.1.1                . . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   55
            1.1.2                      . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   56
     1.2        . . . . . . . . . . . . .    .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   58
     1.3            (string) . . . . . .     .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   58
            1.3.1                  . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   59
            1.3.2                                            .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   60
            1.3.3                            . .     .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   61
            1.3.4 string                       .     .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   62
            1.3.5                      . .   . .     .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   63
     1.4            (tuple) . . . . . . .    . .     .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   65
            1.4.1                            . .     .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   65
            1.4.2                                            .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   66
     1.5            (list) . . . . . . . .   . . .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   67
            1.5.1                      . .   . . .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   67
            1.5.2                              . .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   69
            1.5.3 2                  . . .   . . .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   70
            1.5.4                    (                       )   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   72
     1.6          (dictionary) . . . . .     . . . .         .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   73
            1.6.1                        .   . . . .         .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   73
            1.6.2                        .   . . . .         .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   73
            1.6.3                    (                       )   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   74
                                                                                                                                                                                  v

       1.6.4                                                                     . . . . . . . . . . . . . . . . . . . . .                                                        75
       1.6.5                                                         . . . . . . . . . . . . . . . . . . . . . . . . . . .                                                        76

2                                                                                                                                                                                 79
 2.1       . . .   .   . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .    80
 2.2           .   .   . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .    82
 2.3           .   .   . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .    83
 2.4           .   .   . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .    84
 2.5                     .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .    85
 2.6   lambda          . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .    87

3                                                                                                                                                                                 89
 3.1                   . . . . .   . .   .   .   .           .   .   .   .
                                                                         .   .   .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .    89
       3.1.1           . . . . .   . .   .   .   .           .   .   .   .
                                                                         .   .   .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .    89
       3.1.2                   .   . .   .   .   .           .   .   .   .
                                                                         .   .   .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .    89
       3.1.3           . . . . .   . .   .   .   .           .   .   .   .
                                                                         .   .   .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .    89
       3.1.4                 . .   . .   .   .   .           .   .   .   .
                                                                         .   .   .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .    90
       3.1.5                   .   . .   .   .   .           .   .   .   .
                                                                         .   .   .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .    90
       3.1.6                       . .                       .   .   .   .
                                                                         .   .   .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .    92
3.2    print     . . . . . . . . . . .                       .   .   .   .
                                                                         .   .   .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .    93
       3.2.1         . . . . . . . . .                       .   .   .   .
                                                                         .   .   .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .    93
3.3            . . . . . . . . . . . .                       .   .   .   .
                                                                         .   .   .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .    95
3.4        . . . . . . . . . . . . . .                       .   .   .   .
                                                                         .   .   .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .    98
3.5            . . . . . . . . . . . .                       .   .   .   .
                                                                         .   .   .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .    99
3.6                  . . . . . . . . .                       .   .   .   .
                                                                         .   .   .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   100
       3.6.1 while for . . . .                               .   .   .   .
                                                                         .   .   .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   100
       3.6.2 range . . . . . . . .                           .   .   .   .
                                                                         .   .   .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   101
       3.6.3 continue break                                  .   .   .   .
                                                                         .   .   .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   101
3.7                  . . . . . . . . .                       .   .   .   .
                                                                         .   .   .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   102
       3.7.1 def . . . . . . . . .                           .   .   .   .
                                                                         .   .   .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   102
       3.7.2 return . . . . . . .                            .   .   .   .
                                                                         .   .   .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   103
       3.7.3               . . . . . .                       .   .   .   .
                                                                         .   .   .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   104
       3.7.4                                                 .   .   .   .
                                                                         .   .   .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   104
       3.7.5                                                 .   .   .   .
                                                                         .   .   .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   105
3.8                    . . . . . . . .                       .   .   .   .
                                                                         .   .   .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   106
       3.8.1 class . . . . . . . .                           .   .   .   .
                                                                         .   .   .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   106
       3.8.2                     . . .                       .   .   .   .
                                                                         .   .   .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   107
       3.8.3 self . . . . . . . .                            .   .   .   .
                                                                         .   .   .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   108
       3.8.4                                                             .               .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   109
3.9                    . . . . . . . .                       . . . . . . .               .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   110
vi

          3.9.1 try . . . . . . . . . .                   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   110
          3.9.2 raise . . . . . . . . .                   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   110
          3.9.3 except . . . . . . . .                    .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   111
          3.9.4                     . .                   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   112
     3.10 import (              ) . . .                   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   113

     4                                                                                             115
      4.1                              . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
      4.2                        . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
      4.3    sys.stdin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121

     5                                                                                                                                                                    123
      5.1    input . . . .    . . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   123
      5.2    raw input .      . . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   125
      5.3    rstr, repr,      ‘...‘ .     .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   126
      5.4    filter . . .     . . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   126
      5.5    map . . . . .    . . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   127
      5.6    reduce . . .     . . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   127
      5.7    eval . . . . .   . . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   128
      5.8    exec . . . . .   . . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   129
      5.9    execfile . .     . . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   129
      5.10   compile . . .    . . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   129
      5.11   id . . . . . .   . . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   130
      5.12   type . . . . .   . . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   131
      5.13   hash . . . . .   . . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   131
      5.14   callable . .     . . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   131
      5.15   dir . . . . .    . . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   131
      5.16   vars . . . . .   . . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   132
      5.17   locals . . .     . . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   132
      5.18   globals . . .    . . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   133


     III        Python                                                                                                                                                    135

     1                                                                                                                                                                    137
      1.1                            .    .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   137
      1.2                  . . . . . .    .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   140
      1.3            . . . . . . . . .    .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   141
      1.4                . . . . . . .    .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   142
             1.4.1   create line . . .    .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   142
             1.4.2   create rectangle     .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   144
                                                                                                                                                                    vii

      1.4.3     create polygon      .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   145
      1.4.4     create oval . .     .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   146
      1.4.5     create arc . . .    .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   147
      1.4.6     create text . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   148
1.5                  (      ). .    .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   150
      1.5.1     font . . . . . .    .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   150
      1.5.2     color . . . . .     .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   152
      1.5.3     stipple . . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   153
      1.5.4     capstyle . . . .    .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   153
      1.5.5     joinstyle . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   154
      1.5.6     tags . . . . . .    .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   155
1.6           . . . . . . . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   157

  A                                                                                               161
A.1                           . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
A.2                 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162

  B                                                                                               165
B.1 math                    . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
B.2 string                  . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167

  C colors1.py                                                                                                                                                      169

  D colors2.py                                                                                                                                                      171
    I

Python
                                                                                                           3




     1              Python

Python                            1                                                              Python

                                                   Python

  Windows            Python                                  Windows
                                                         1
                         Python       IDLE




                                         1.1: Python IDLE


              1.2




                                         1.2: Python Shell




  1 Windows     Python                                           www.python..org
     MacOSX UNIX                                         IDLE
          MacOSX IDLE                        MacPython                   http://ar.aichi-u.ac.jp/python/
4                                                                          1       Python

1.1
    Python

        >>> 3*(5+8)
        39

                                                                               *
         39    Python

                                                          ()                                    []




        3*(7*(5*(1+2)+3)+11)


                                             C                                              Python


        >>> 1/3
        0

                                 1/3              1.0/3            1/3.0

        0.333333333333




                   (Python       10              16                    )
                                                               %

        >>> 18 % 7
        4
         2
                             3              ( *, /, % )


        31/3*6%7

    (                                                     )

        31/3      10
        10*6      60
        60%7      4
    2                                  II   2    2
1.1.                                                                                                      5



                             **

       >>> 2**10
       1024

                                              2    100                                     Python
                                                       3


       >>> 2**100
       1267650600228229401496703205376

                                                           0
                        5
        1.23         10

       1.23E5

                                   E5    ×105                                   1.23E5     123000
                   1.23E-5        E-5    ×10−5                      0.0000123               E

  Python 8                   16                                       8                    0          8
  177 10

       >>> 0177
       127


  16               0x               16            7F       10

       >>> 0x7f
       127


  10                         8           16                                                         oct
       hex

       >>> oct(127)
       ’0177’
       >>> hex(127)
       ’0x7f’
       >>> hex(0xc+0xd)
       ’0x19’


  Python                                                        j
  3 Python   2.2          2L**100                                                  L                  2**100
                                L                                                      Python
6                                                                      1       Python

        >>> (2+3j)*(3-5j)
        (21-1j)
        >>> (2+3j)**5
        (122-597j)
        >>> abs(2+3j)
        3.605551275464

              j                      j

        1j

          j                      1        1                    j



1.2

        >>> from math import *
                   4


        >>> pi
        3.14159265359
        >>> e
        2.718281828459
        >>> tan(1)
        1.557407724655
        >>> s=sin(1)
        >>> c=cos(1)
        >>> s,c
        (0.841470984808, 0.540302305868)
        >>> s/c
        1.557407724655

          pi               π e          e         Python           2
                                     sin(x)    cos(x) tan(x)
                                          ()
                                                       (360        2π                   )
          60       sin

        >>> sin(pi/180*60)
        0.866025403784

                  60       pi/180
    4   Python         C                                                   C
         math
1.3.                                                                      7

1.3
       2

       s=sin(1)

   sin(1)                             s

                [   1]    ‘ =’

                                              1           (       )



       1: Python                          6   1       7       2


       >>> 3*6.276429*(6.276429+7)



       >>> x=6.276429
       >>> 3*x*(x+7)


                         3*x     3x               *




1.4
  Python



                                                                      2




1.5
   1        5

       923746
       736427
       783644
       103847
       348582
8                                                                                              1         Python




     2 Python


(3*(2+5)-1)*2
17/3*2
3*(2+3)**3
1+2**3
-2**3+1

     3          2             7636272           93838
                                                                                        7636272         93838
                                                                    (           :
                                .0                                                                                          1.0
                     )

     4          16             10                               ?

    16              10
         F7
         7F
         FF
         77


     5 71 , 72 , 73 , 74 , 75 , 76 , 77 , 78 , 79 , 710                                            11
                            710 11                              1

     6                                                (Fermat           ):

          m                        xm−1       m                     1               5
                                                                                                    x     1, 2, · · · , m − 1


                     (x = 7 m = 11)                       x=2                              m                         m
                        1      m

     7                                            2             3.278        73.2                        2
                                     239.9496




    5m                         1
                                                                                         9




      2



                           Windows Vista                                    Python

                          Python IDLE




2.1
                                  Python
  Python
                                                     (   2.1)
                                               Python




                                        2.1:




2.2         1
  Python Shell     File                 New Window              Python Editor        (
2.2)

      print "OK"
10                                                              2




                                     2.2: Python Editor


                   2.3           Python Editor                       ”Untitled”




                                  2.3: OK


      File                Save
     Python                          (        a.py )

 Python                                       ”.py”
                                 Python



              Run                Run Module
               Python Shell                       (    2.4)   2.4:
2.3.       2                                                                             11

2.3            2
                                                                        (   2.1)


   2.1                   1.       cal.py
wday=("sun","mon","tue","wed","thu","fri","sat")
def cal0(n,m):
    # cal0(n,m)    1
    # n                           (0      6)
    # 0
    # m                           1      m=31
    #       2000 1                   cal0(6,31)
    for x in wday: print " ",x,
    print
    for x in range(0, n): print " ---",
    for x in range(1, m+1):
        print "%5d"%x,
        if (x+n)%7==0 : print
    print
cal0(6,31)




2.3.1
            Python

   1.               #
                                                                                   (
                                                         )

   2.                         (                                  )
                                                             1
                                                                     Windows


         # coding: shift-jis



   3.                              (           )                                   2.5


                                           (         )       4
                   4
                   TAB                         TAB


  1                      UTF-8
12                                                       2

          wday=("sun","mon","tue","wed","thu","fri","sat")
          def cal0(n,m):
              for x in wday: print " ",x,
              print
              for x in range(0, n): print " ---",
              for x in range(1, m+1):
                  print "%5d"%x,
                  if (x+n)%7==0 : print
              print
          cal0(6,31)


                                 2.5: Python




     4.




                1
          def cal0(n,m):


          def       cal0(n,m):




          range(0, m)


          range(0,m)



                                                             3




2.3.2


                     calendar     3            cal.py        2




     2
2.3.       2                                                                                  13

2.3.3


  sun          mon    tue     wed        thu         fri        sat
  ---          ---    ---     ---        ---         ---          1
    2            3      4       5          6           7          8
    9           10     11      12         13          14         15
   16           17     18      19         20          21         22
   23           24     25      26         27          28         29
   30           31
         2000         1



                                                                            (
                                                                                       ...)


2.3.4                                          ...


       File "cal.py", line 11
           for x in range(0, n+m);
                                 ˆ
          SyntaxError: invalid syntax
                                                     11
                (;)                                                     ?
                                                                  (ˆ)




                                     (
                          )
       Python Editor          Edit                             Go to Line       2.6:
                                                                       (
2.6)

  SyntaxError
    NameError(                                             )
14                                                          2

                          (ˆ)                                                 Python
                                   (=Python)
                (ˆ)




     1 2000    4                               (
               )

     2 SyntaxError    NameError

     3                                                                    1   1




2.4
 IDLE                                              python
                          python                                                  OSX
     UNIX                                                       Windows



                                      (             )




              Python
                 Python
                                                                            15




      3

              2
                  print def if for in range




3.1
                                                            print


  1       2             7636272      93838
                                                  7636272   93838



  3.1
x=7636272
y=93838
print x+y
print x-y
print x*y
print x/y
print x%y
print 1.0*x/y




                   1           3              (                        )
                                                                    print
          6            print   1.0
      Python




      print 1.0*x/y
16                                                   3



         print float(x)/y

                                                                     float(x)   x

           6                  1

         print x+y, x-y, x*y, x/y, x%y, float(x)/y



         print   x+y,
         print   x-y,
         print   x*y,
         print   x/y,
         print   x%y,
         print   float(x)/y

                 1                print                  (,)




3.2

                                                               def, return


     2                  3

                                      3, 4, 5


     3.2
from math import *
def v(r): return 4*pi*r*r*r/3
print v(3)
print v(4)
print v(5)




                                       Python
3.3.                                                                                                     17

Python



               pi

       from math import *



       def v(r): return 4*pi*r*r*r/3

                                                                                 def    Python
                                                   [      ]
                                     (:)               return                      return
                                                            r
       (                                   )              v

                    :


   1           f (x) = 1/(x2 + 1)              x   0.5, 1.0, 1.5, 2.0   4

       from math import *



       print f(1)

                          0.5



3.3

                                                                                       if


   3                                                       1                     0
           (                        leap                                         leap year           )
                                                         1996       1999    1900      2000       4
18                                                              3

     3.3
def leap(x):
    if x%400 == 0: return 1
    if x%100 == 0: return 0
    if x%4 == 0: return 1
    return 0
print 1996, leap(1996)
print 1999, leap(1999)
print 1900, leap(1900)
print 2000, leap(2000)




                                   :
a. 4
b. 100
c. 400
                     c, b, a                         1900   a, b    b
                            2000       a, b, c              c
                          c, b, a

                                    leap                    1
                               (                 )


                                1
                          Python

def leap(x):
    if x%400 == 0: return 1
    if x%100 == 0: return 0
    if x%4 == 0: return 1
    return 0

           leat(x)

       if x%400 == 0: return 1

       x    400               0                       return 1
                          return 1                         1


       if x%100 == 0: return 0
       if x%4 == 0: return 1
       return 0
3.3.                                                                                               19

                            if                       Pyhton                                   ==
              (=                                        =
       !=               <>                       )

       x%400 == 0



       if x%400 == 0: return 1




           if x%400 == 0: return 1                                    x%400 == 0 の場合に実行される
           if x%100 == 0: return 0
           if x%4 == 0: return 1                                      x%400 == 0 でない場合に実行される
           return 0



                             3.1:              x%400==0


                                 (                                      )
                if                       (if    )
                                               (def     )                     1
           Python

       print 1996, leap(1996)



       print leap(1996)




   2                    3            4

       3            leap(x)

   3                (                     )     1582        10   15               [   1]
                                                                                       :            1
       365.2425(= 365 + 1/4 − 1/100 + 1/400)                                                 400   []
                            7                                         1600                 2000
20                                                                       3

     4                                   leap(x)      if
                             ?
             :           x                                      x−1
                 (
                     )

                                                            1
                     :                        365.242191        1                  1
                                                                                                     1

                                         1       365                4          1
                                 1             365.250000            4
                                                                    1              ?        Python


>>> a=365.250000-365.242192
>>> a
0.007809
>>> 1/a
128.057369701481

         2                                   128                 100     400                             128




3.4

                                                                                       for, in


         3                           3

  3.4
def leap(x):
    if x%400 == 0: return 1
    if x%100 == 0: return 0
    if x%4 == 0: return 1
    return 0
for x in [1996, 1999, 1900, 2000]: print x, leap(x)




     1                           (            1998)
3.4.                                                                                          21

       print   1996,    leap(1996)
       print   1999,    leap(1999)
       print   1900,    leap(1900)
       print   2000,    leap(2000)

       for x in [1996, 1999, 1900, 2000]: print x, leap(x)


       x   1996        1999   1900     2000                  print x, leap(x)

                        (       1996, 1999, 1900, 2000                        )

                       for    Python                           in
                                                                                        for
                                                         ?                4

                                       (                         ) for                         x
                         (                       )

  [1996, 1999, 1900, 2000]                                                        [ ]
    Python




       3.4 for
       for x in (1996, 1999, 1900, 2000): print x, leap(x)

       for x in 1996, 1999, 1900, 2000: print x, leap(x)


  (1996, 1999, 1900, 2000)                                                    ( )




       for x in 1996, 1999, 1900, 2000: print x, leap(x)
                                                       for
                print x, leap(x)   for

for x in [1996, 1999, 1900, 2000]:
    print x, leap(x)
22                                                                   3

                                                for
                         Python
                                                                     (:)
             2
                                                                                        for           if       def
                                                                           Python
(:)

      5          2                    for

      6                           1                     1                                         (        3
                                            )
          wday=("sun","mon","tue","wed","thu","fri","sat")
          for x in wday: print " ",x,
          print

          print " ",x,
                   (,)                                           (          :
             )                        print



3.5

                                                                                    range


  1                                         1   31

                       1     31
                1    31
          for x in range(1,32): print x

                                                                                          [3,4,5,6,7]

                     range(n,m)                 range(n,m)   n                             1    m
                                                                                          [3,4,5,6,7]
range(3,8)

          [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,
          25,26,27,28,29,30,31]

     21                                           (;)                        II     3         1
3.6.                                                                                                    23

                                                                    range(1,32)
            range

   7 1            31                                (           :        4        5                     )

   8          f (x) = 1/(x2 + 1)          x

                                   0.00 0.01 0.02 · · · 0.98 0.99 1.00

            101                                 (          : x=0.01*n             n   0           100
                       )



3.6




   4                                      31

        1          2    3        4       5      6          7
        8          9   10       11      12     13         14
       15         16   17       18      19     20         21
       22         23   24       25      26     27         28
       29         30   31



   for x in range(1, 32):
       print "%5d"%x,
       if x%7==0 : print

                            2                                        1                             2

                                                                                          x                 7
                                                        print                                 x


        if x%7==0: print

                                         2


        print "%5d"%x,
24                                                                     3

         "%5d"

             (         )                                       5
                                     %
d                10                                                               %
                                                                            x
                                                                   %
                      s

         wday=("sun","mon","tue","wed","thu","fri","sat")
         for x in wday: print "%5s"%x,
         print

           print                          "%5s"                5
                                     x                     x               wday


     sun     mon           tue     wed   thu   fri     sat


                                                                                      II   3   2
print

     9

      1           2
      3           4            5     6     7       8     9
     10          11           12    13    14      15    16
     17          18           19    20    21      22    23
     24          25           26    27    28      29    30
     31

     10

     ---     ---           ---     ---   ---       1     2
       3       4             5       6     7       8     9
      10      11            12      13    14      15    16
      17      18            19      20    21      22    23
      24      25            26      27    28      29    30
      31

     11               print                            %

         x=18
         y=x+2
         print "alice=%5d,bob=%d"%(x,y)
3.7.       2                    1                                                                25

3.7             2                             1
   5       2                    1

       2

   wday=("sun","mon","tue","wed","thu","fri","sat")
   def cal0(n,m):
       for x in wday: print " ",x,
       print
       for x in range(0, n): print " ---",
       for x in range(1, m+1):
           print "%5d"%x,
           if (x+n)%7==0 : print
       print
   cal0(6,31)



       def cal0(n,m)

                                                        cal0
                                                                           cal0(6,31)
cal0(6,31)                                                   6   31   2          def cal0(n,m)
          2                 n       m                    6                n                  n
  6                    31                     m                       m     31
cal0(6,31)

       wday=("sun","mon","tue","wed","thu","fri","sat")
       n=6
       m=31
       for x in wday: print " ",x,
       print
       for x in range(0, n): print " ---",
       for x in range(1, m+1):
           print "%5d"%x,
           if (x+n)%7==0 : print

                                                  4          4

       wday=("sun","mon","tue","wed","thu","fri","sat")
       for x in wday: print " ",x,
       print



  sun          mon   tue    wed         thu       fri    sat
26                                                        3

      n=6
      for x in range(0, n): print "             ---",



     ---   ---       ---     ---    ---       ---

                (                  )n     m

      for x in range(1, 32):
          print "%5d"%x,
          if (x+6)%7==0 : print

                         4                                    x   1,
8, 15, 22, 29       if

     sun   mon       tue     wed    thu       fri   sat
     ---   ---       ---     ---    ---       ---     1
       2     3         4       5      6         7     8
       9    10        11      12     13        14    15
      16    17        18      19     20        21    22
      23    24        25      26     27        28    29
      30    31



     12    5

           if (x+n)%7==0 : print



           if x%7==7 - n : print
3.8. Zeller                                                           27

3.8    Zeller
                                     Zeller

                                                     1582   10   15




  3.5 Zeller
# h(y,m,d): day of week (Zeller’s formula)
#                                       (          ,1989)
# y: year, 0,1,2,..
# m: month, 1,2,..,12
# d: day of month, 1,2,..31
# return: day of week, 0,1,2,..,6
# example: h(2000,1,1) -> 6    # Saturday
def h(y,m,d):
    if m<3: y=y-1; m=m+12
    return (y+y/4-y/100+y/400+(13*m+8)/5+d)%7

wday=("sun","mon","tue","wed","thu","fri","sat")
def cal0(n,m):
    # cal0(n,m)    1
    # n                           (0,1,..,6)         0
    # m                           1     m=31
    #       2000 1                  cal0(6,31)
    for x in wday: print " ",x,
    print
    for x in range(0, n): print " ---",
    for x in range(1, m+1):
        print "%5d"%x,
        if (x+n)%7==0 : print
    print

def cal(y,m):
    n=h(y,m,1)
    n1=h(y,m+1,1)
    r=(n1-n)%7
    d=28+r
    cal0(n,d)

cal(2000,1)
28                                                                 3

3.9       1752        9
                Python               calendar                                cal(y,m)
     prmonth(y,m)                                  1752    9

     September 1752
Mo   Tu We Th Fr Sa         Su
               1 2           3
 4    5 6 7 8 9             10
11   12 13 14 15 16         17
18   19 20 21 22 23         24
25   26 27 28 29 30

          UNIX        cal                         cal              1752      9


      cal 9 1752



   September 1752
 S M Tu W Th F S
       1 2 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30

                                                          UNIX         cal

                                                               (
                 )

     13                                                                                        4
                                 (      1       365.25                            )                    1582
     10   4   (       )                                                      10       15   (       )
                     Zeller

      def h0(y,m,d):
          if m<3: y=y-1; m=m+12
          return (y+y/4+(13*m-2)/5+d)%7

           1582      9
           1582      10                                    (           :
                                         )
3.9. 1752     9                                            29



                       2                               ?
               March                February   1           (
      February              )                      :
  9       September    sept-          7
 10       October      oct-           8
 11       November     nove(    )     9
 12       December     decade        10
                                                                                 31




       4




                   4

  1.
  2.
  3.
  4.                   3

                               ?




                                                 4



4.1

                                                             2       1       1
                       2
       1   1   2       3   5       8       ...

                                                                         8




  1                                    8             5   (       )
32                                                                            4

1    +   1   2
1    +   2   3
2    +   3   5
3    +   5   8
                                  3                                       3               (   )
                              (         )x y z
x + y        z
              (       :
                                                              )                                   x y
z
             x    y       z
    STEP1    1    1       2
    STEP2    1    2       3
    STEP3    2    3       5
    STEP4    3    5       8

                                      Python                                      z   x   y


z=x+y
                                         x       y
x=y
y=z
                                                      x y         1   1
                                                     Python


x=1
y=1
             :
         z = x + y
         x=y
         y=z
                                             ?
                                  x
x=1
y=1
             :
         print x
         z = x + y
         x=y
         y=z
4.1.                                                                      33



       Python                                                   10000

 x < 10000                                 Python       while x < 10000
                         Python

   4.1
x=1
y=1
while x < 10000:
    print x
    z = x + y
    x=y
    y=z




   2                              30


   3            1
x=y
y=z


y=z
x=y
                                   STEP4            STEP5


                                           100
                                       ?

   4.2 for
x=1
y=1
for n in range(1,101):
    print n, x
    z = x + y
    x=y
    y=z
34                                                                     4

     1.
     2.
     3.                           (             Python )

                              1       2                                                             3

             (coding)

     4
          6201    11349                                                              (
                          )
    11349     6201                              5148             11349%6201              5148
    6201     5148                              1053               6201%5148              1053
    5148     1053                              936                5148%1053              936
    1053     936                              117                  1053%936              117
    936     117                              0                      936%117              0
            0                               117
                          5442853         4555013

     5                        gcd(x,y)

gcd(11349,6201) , gcd(6201,11349)
    x, y         0       gcd(x,y)


     6                                    5%    3000                               200
                                           ?                                             ?



4.2
    2000         10                                10    1                                       2000
1     1                                                 10   1                                   1      9
                                   (2000                                      ):
31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30
                7                                            1                      10       1      (
         )
4.2.                                             35

4.2.1


            d=[31,29,31,30,31,30,31,31,30]




  4.3
d=[31,29,31,30,31,30,31,31,30]
s = 0
for x in d:
    s = s + x
print s




 0 + 31           31
31 + 29           60
60 + 31           91
...


x + y         z
                       y                     d
z       x


d=[31,29,31,30,31,30,31,31,30]
x = 0
for y in d:
    z = x + y
    x=z
print x


z=x+y
x=z
36                                                          4

x=x+y
     1
d=[31,29,31,30,31,30,31,31,30]
x = 0
for y in d:
    x = x + y
print x
                                         2

                           sum                                      s




              d=[31,29,31,30,31,30,31,31,30,31,30,31]           9




          1


  4.4             9
d=[31,29,31,30,31,30,31,31,30,31,30,31]
s = 0
n=0
for x in d:
    s = s + x
    n = n + 1
    if n == 9: break
print s


                                             (          n           ) n   9
                              break

         n = n + 1

                     n    1
4.2.                                                                         37

  4.5             9
d=[31,29,31,30,31,30,31,31,30,31,30,31]
s = 0
for n in range(0,9):
    s = s + d[n]
print s



        2

                                 d[n]   d   n+1                     Python   d


d[0],       d[1],   d[2],    ..., d[11]
                                 [ ]              d       (index)
        1                    0                                        1
                             0                            Python




        3


  4.6             9
d=[31,29,31,30,31,30,31,31,30,31,30,31]
s = 0
for x in d[:9]:
    s = s + x
print s


  d[:9]              d           9
[31,29,31,30,31,30,31,31,30]
                     d[:9]                            1
38                                                                             4

4.3

                                              x    y                  m        x       y          m

         4.1     x = 1, · · · , 12 y = 1, · · · , 12 m = 13                                     x=3 y=5
               x × y 15                  m(= 13)                  2                              3 5
         2

                 1      2       3     4        5        6    7     8       9   10          11    12
                 2      4       6     8       10       12    1     3       5    7           9    11
                 3      6       9    12        2        5    8    11       1    4           7    10
                 4      8      12     3        7       11    2     6      10    1           5     9
                 5     10       2     7       12        4    9     1       6   11           3     8
                 6     12       5    11        4       10    3     9       2    8           1     7
                 7      1       8     2        9        3   10     4      11    5          12     6
                 8      3      11     6        1        9    4    12       7    2          10     5
                 9      5       1    10        6        2   11     7       3   12           8     4
                10      7       4     1       11        8    5     2      12    9           6     3
                11      9       7     5        3        1   12    10       8    6           4     2
                12     11      10     9        8        7    6     5       4    3           2     1

                                          4.1: mod 13


                                                                                       1
                                                                                                      1
12                                                            1    12
                                          !                                        ?



                         4.7


  4.7
m=13
for x in range(1,m):
    for y in range(1,m):
        print "%4d"%(x*y%m),
    print



     1
4.3.                                                                                                                               39

    m                                                                        m

             0, · · · , 12                                                                                                         2
            x y x−y                  m

                                                             x≡y              mod m


                                                           3×5≡2                  mod 13

             m                                                          (mod m                                     )

                                                                    3×5≡2


                                                                                         ?

                                                                                             1                                 x
            x×y≡1                    y                                      x=3                      y=9               y       x
             x−1
                                                                                      2

                                         2, 22 , 23 , · · · , 212

        2     4     8            3           6       12        11            9       5       10           7   1

                     1                                                      212     m(= 13)


Fermat

    m                         x = 1, · · · , m − 1                      x

                                                           xm−1 ≡ 1               mod m

                  Fermat
    m                                                                                                     m = 12       x=2

        2     4     8            4           8         4            8        4       8           4        8




                                            Fermat                                                    ?
                                                                                                                           3
m
    2                    0, · · · , 12
    3                                       4.7
40                                                                                  4

4.4
           y = cos(x)            y=x                                                                       (
               )

                                                           x             x0    x1                    x0   x1
                                 x0    x1                          1
                             x0 < x1




                                            1




                        -1                      0   x0         x       1 x1                 2


                                                    4.2:

               x = (x0 + x1 )/2
                      x1     x                                                 x0       x


     4.8
#
# root of a function
# Bisection method
#
from math import *
def f(x):
     return cos(x)-x
x0=0
x1=pi/2
while x1 - x0 > 1.0e-8:
     x = (x0+x1)/2
     y = f(x)
     print x,y,x0,x1
     if y > 0: x0=x
     elif y < 0: x1=x
     else: break



               f(x)      cos(x) − 1                                              elif       Python             if
               y>0                                                 (elif      else if                           )
4.5.                                                                                        41

           else                                                            y==0
               y==0                                                                    else
        break
         while               x1 - x0 > 1.0e-8          1.0e-8
        Python                      1.0e-16                 1.0e-16

       print x,y, x0, x1

                                                      f(x0)>0          f(x1)<0




   7                         2

                                        y = −x2 + 1
                                        y =     x

                            (2              )



4.5
4.5.1



                                                                ....             2
             ....                                                                30         1
       365                                              ...


4.5.2
                                                                            1         365
                       30




  Python
from random import *
                   random
     random()  0≤ x<1                           x                                4

  4            [0,1)
42                                                  4

  4.9
from random import *
for i in range(0,30):
    x=int(365*random())+1
    print x



365*random()                    0    365            int
                              int(365*random())+1         1               365
                                        print x                   x             1        365




        30                                                                          30
                                                                      ?




  4.10            4.9
from random import *
d=[]
for i in range(0,30):
    x=int(365*random())+1
    d.append(x)
print d
d.sort()
print d


                                       (d=[])
     (d.append(x)) d.sort()      d                        2               print d




                        (                       )
                                                              2
4.6.                                                                                              43

  4.11                     4.10
from random import *
d=[]
for i in range(0,30):
    x=int(365*random())+1
    d.append(x)
print d
d.sort()
print d
for i in range(0,29):
    if d[i]==d[i+1]: print d[i]



                                                                                              ?

   8                                                                                     30
                                                        3            ...
  3                                        P
                                           365 364 363
                                      P=      ×   ×
                                           365 365 365
                                                                      30
                          P       5



4.6
            Fermat(           )                                                  n   3

                                           xn + yn = zn
                                                   5
              (x, y, z)                                Fermat6
              Fermat



              Fermat
   6

                                       x3 + y3 + z3 = u3


  5n   =2                                  (3, 4, 5)   (1, 12, 13)         n=2

  6 1601-65
44                                                              4

                      (x, y, z, u)

                                          x≤y≤z

                         z               1, 2, 3, · · ·                               20
                         u                                           x +y +z = u
                                                                      3   3   3   3

         u                   (x + y + z )
                              3      3     3 1/3
                                                          u                 u



  4.12
for z in range(1,20):
    for y in range(1,z+1):
        for x in range(1,y+1):
            v = x**3 + y**3 + z**3
            u = int(v**(1.0/3)+0.5)
            if u**3== v: print x,y,z,u



     9

                                     x4 + y4 + z4 = u4

                                           ?



4.7
                                                                                      4.3
                                                          m−1
                                             m          x     m
                    x = 117                 m = 1644455544992686074722684291497



x=117
m=1644455544992686074722684291497
print x**(m-1) % m




x=117
m=1644455544992686074722684291497
y=1
4.7.                                                                     45

for n in range(0,m-1):
    y=y*x %m
print y


Traceback (most recent call last):
  File "a.py", line 4, in ?
    for n in range(0,m-1):
OverflowError: range() result has too many items
                range
                                                xrange(0,m-1)
Traceback (most recent call last):
  File "a.py", line 4, in ?
    for n in xrange(0,m-1):
OverflowError: long int too large to convert to int


x=117
m=1644455544992686074722684291497
y=1
n=0
while n<m-1:
    y=y*x %m
    n=n+1
print y
            ?

                ...
                                      216
  ? 15                                          4                        m


                             22    2×2→4
                             24    4 × 4 → 16
                             28    16 × 16 → 256
                             216   256 × 256 → 65536

                         m                  ?                   m = 17
       2 ×2
       16

                                    pow(x,n)        xn
def pow(x,n):
46                                                               4

         if n==0:
             return 1
         k=n/2
         y=pow(x,k)
         if n%2 == 0:
             return y*y
         return y*y*x
                               xn     n = 2k                 xn = (xk )2   n = 2k + 1
                     x = x · (xk )2
                      n

          (                  )

                                                                                        pow
                pow
                          pow
 7

 Python
 x**n


  4.13 xm−1 m
def mpow(x,n,m):
    if n==0:
         return 1
    k=n/2
    y=mpow(x,k,m)
    if n%2 == 0:
         return y*y%m
    return y*y*x%m

m= 1644455544992686074722684291497
x=117
print pow(x,m-1,m)


                                 448225599079959033691973915232
          1644455544992686074722684291497




     7     (Hoare)                                (quick sort)
4.8.                                                                                               47

4.8
4.8.1


                                                                                               5      5
                                              8
                 (                   )             2




        Bob                  Alice           Bob                       Alice                    Bob
                                                                                   Alice       Bob
                                                       Alice


4.8.2


next(d)                                                                d



        m=5
        d=[]
        for i in range(0,m):
            for j in range(0,m):
                d.append((i,j))
               [(0,0),(0,1),...,(4,4)]                         d                           d
p               p                                         q        p                   1
    d.remove(q) d       q                                              d       q
                               d p
        for i in -1,0,1:
            for j in -1,0,1:
                q=(p[0]+i,p[1]+j)
                if d.count(q): d.remove(q)
              next(d)                    d

    8                5   5
48                                                               4

              None                       d
             ?

         Frank                                                        Alice      Frank
                                     Alice                                       Alice
                           Frank                                Frank


                            Alice
                                                     Alice    Frank                  Frank
                             Alice
                   Frank                     Alice

Python           next(d)                                     next(d)
                                                                         Alice
1    1                       Frank
4.8.                                                                    49

  4.14
from copy import *
def put(d,p):
    for i in -1,0,1:
        for j in -1,0,1:
            q=(p[0]+i,p[1]+j)
            if d.count(q): d.remove(q)
def pr(d):
    for p in d: print p,
    print
def next(d):
    if len(d)==0: return None # No space to put a stone. I’ve lost.
    pr(d)
    for p in d:
        print p,":",
        e=copy(d)    # make a copy of d to protect from modification.
        put(e,p)              # put a stone
        if next(e)==None:     # and glance at Frank
            return p          # he looks pale. I will win.
    return None    # Frank is smiling for my all trials. He will win.

# initialize
m=5
d=[]
for i in range(0,m):
    for j in range(0,m):
        d.append((i,j))

print "RESULT:", next(d)
50                                                                                 4

4.9       Boyce
4.9.1
           1                                                  4             6
                                                                                   100
               100




                        ?            1            1
                                                100                                                    1




                                            Boyce


4.9.2


                   100                                                             1.33
133                                               m               p                V(m, p)                     1
      0            :                                               V(1, 0) = 0   0           1             :
                                         V(0, 1) = 1     1               1       :
               1                                                       1
               1                                                                                   −1 + V(0, 1)
                                                 +1 + V(1, 0)
                            1/2                                     1/2                  1         1


                                         1                 1
                                           (−1 + V(0, 1)) + (+1 + V(1, 0)) = 0.5
                                         2                 2
                                                                                   V(1, 1) = 0.5
                   V(m, p)                      V(m − 1, p)       V(m, p − 1)
                                               m                         p
           V(m, p) = max 0,                        (−1 + V(m − 1, p)) +      (+1 + V(m, p − 1))
                                              m+ p                      m+ p
           V(0, p) =             p
           V(m, 0) = 0

                       V(m, p)
4.9. Boyce                                                                                          51

  4.15 Boyce
def V(m,p):
    if m==0: return p
    if p==0: return 0
    return max(0,
         float(m)*(-1+V(m-1,p))/(m+p)+float(p)*(1+V(m,p-1))/(m+p))
for p in range(0,10):
    print p,
    for m in range(0,10): print "%5.2f"%V(m,p),
    print



                                 V(m, p)                   V(m − 1, p)    V(m, p − 1)



    V(m, p)

0   0.00      0.00       0.00   0.00   0.00        0.00   0.00   0.00    0.00   0.00
1   1.00      0.50       0.00   0.00   0.00        0.00   0.00   0.00    0.00   0.00
2   2.00      1.33       0.67   0.20   0.00        0.00   0.00   0.00    0.00   0.00
3   3.00      2.25       1.50   0.85   0.34        0.00   0.00   0.00    0.00   0.00
4   4.00      3.20       2.40   1.66   1.00        0.44   0.07   0.00    0.00   0.00
5   5.00      4.17       3.33   2.54   1.79        1.12   0.55   0.15    0.00   0.00
6   6.00      5.14       4.29   3.45   2.66        1.91   1.23   0.66    0.23   0.00
7   7.00      6.12       5.25   4.39   3.56        2.76   2.01   1.34    0.75   0.30
8   8.00      7.11       6.22   5.35   4.49        3.66   2.86   2.11    1.43   0.84
9   9.00      8.10       7.20   6.31   5.43        4.58   3.75   2.95    2.21   1.52


                          p                                 m=0                            m=1, m=2
                                 3         3          1.33 V(2, 1)                              V(6, 4)
    0.07                                       6          4




4.9.3          4.15


               V(3, 5)                         V(2, 5)                           V(2, 6)
           V(2, 5)

                 V(m, p)                                                                       Python
52                                                   4



u={}

            d
           V(m,p)                    u[m,p]
        (m,p)               (m,p) in u   True                       (
4.16)

  4.16 4.15
u={}
def V(m,p):
    if m==0: return p
    if p==0: return 0
    if (m,p) in u : return u[m,p]
    r=max(0,
        float(m)*(-1+V(m-1,p))/(m+p)+float(p)*(1+V(m,p-1))/(m+p))
    u[m,p]=r
    return r
for p in range(0,10):
    print p,
    for m in range(0,10): print "%5.2f"%V(m,p),
    print
    II

Python
                                                                                                       55




      1


1.1
1.1.1



      256             1.23                 1.23E5                       "alice"
      (2,3,"alice")   [2,3,"alice"]        {’bob’:20, ’alice’:16}

  1                           256              1.23   123000              alice                        2
                       1                                            1

                                                                    Python




                                                      Python
                                    ....
                                           2             :
(1)
(2)
                              1.23E5                                                   (1)       (2)

                              1                                                              1     1.0




                                                                            809-1234
                       1234                                  ?
          ‘-’                                                    1234         ?
56                                                                   1



      a=(2,3,"alice")
                    (2,3,"alice")          a
  Python
                                                  abs(x)
      f=abs
     abs        f                          f(x)




                                                           5
                                                      Python
                                                                         0
                a  (2,3,"alice")                           a[0]   2   a[1]   3
     a[2] "alice"                   a[2]                   a[2][0] ‘a’ a[2][1]
     ‘l’ a[2][2] ‘i’




      b=[2,3,"alice"]
      b[2]="bob"
           b   [2,3,"bob"]




                    (2,3,[4,5])




1.1.2
                    Python

Python                                                         (         Python
                                     )
1.1.   57
58                                                                                        1

1.2
                                                                                      1
 Python                                                          3


           x + y, x - y, x * y, x / y, x % y, -x, +x
           *                                   /             %
                          6   3

          Python



           : 1.23        3.12E-5
E-5       ×10−5                                    3.12E-5   0.0000312               E
                                                                    Python         10       16
                                           1.0/3                             0.33333333333333331
                                                   10308               0             10−323



                          j                      j                                j
                                             (1+j)            (1+1j)
z
z.real
z.imag
  z
z.conjugate()




1.3                     (string)
         Python                    1

                                                                       (                      )
                                                       1




     1     Python             (        )                                                          Python
                    3
1.3.            (string)                                                                              59

1.3.1
                                                              (")                             (’)
                      "alice"             ’alice’
                                               2




                                                                                      ?
       3              (                                  )
’’’All in the golden afternoon
Full leisurely we glide;
For both our oars, with little skill,
By little arms are plied,
While little hands make vain pretence
Our wanderings to guide.’’’
                 afternoon
                                      afternoon
                                           ?                                                  (\)


’’’All in the golden afternoon\
Full leisurely we glide;\
For both our oars, with little skill,\
By little arms are plied,\
While little hands make vain pretence\
Our wanderings to guide.’’’
                                                                                                  1



                                      \
  Python        2
        I don’t know.
  print
       print "I don’t know."


       print ’I don\’t know.’
                               (   "I don’t know."                                        )
  Python                                             R   U             (r     u               )
                           3

  2                                                          ‘alice’        “alice”

  3         R
60                                                                                           1



                  ’                 \’                      Null            \0
                  "                 \"                 Vertical tab         \v
                  \                 \\             Carriage return          \r
                 TAB                \t                 Formfeed             \f
                                    \n                     Escape           \e
                 Bell               \a                 8                    \0XX
               Backspace            \b              16                      \xXX

                                          1.1:



1.3.2
                                s                                                          s
        len(s)                             s     ’alice’                              len(s)             5



                 s   n                         s[n]        n                                     n       0
               s[0] ’a’                       s[2] ’i’          s[n:]         s[n]                   s
                     s[2:]               "ice"        s[:m] s[0]              m
      s[:4]   "alic"                     s[n:m]   s[n:]   s[:m]
  s[2:4] "ic"                                                                         (slice)
  [ ]
           -1
           s[-2]   ’c’                           s[-4:]            ’lice’
           s[:-2] ’ali’                          s[-4:-2]          ’li’

                       +        *                             %
’alice’ + ’bob’   ’alicebob’
’alice’*3 ’alice’ + ’alice’ + ’alice’                         ’alicealicealice’
’alice=%d’%x x                    18                            ’alice=18’



’alice=%d’%x
          ’alice=%d’        x                      %                                                     %
          (       ’alice=%d’ )

                                                                        U     Unicode
                      (Python                     Unicode
                                                                                   Unicode

     Unicode                        )
1.3.           (string)                                                                          61

         %




1.3.3




             "Alice"       "Anna" 2                                         ’l’   ’n’
                                "Alice"           "Anna"                                       "An"
   "Anna"         "An"




   1.2                                           ASCII                                          JIS



                          00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
                     20       ! " # $ % & ’ ( ) * + , - . /
                     30    0 1 2 3 4 5 6 7 8 9 : ; < = > ?
                     40    @ A B C D E F G H I J K L M N O
                     50    P Q R S T U V W X Y Z [ \ ] ˆ _
                     60    ‘ a b c d e f g h i j k l m n o
                     70    p q r s t u v w x y z { | } ˜


                                              1.2: ASCII

         ‘A’                       ‘A’                       40       ‘A’                 01
                            41                                      16
                00         1F            32

                          20             7F                   DEL
  ASCII



       ’0’ < ’1’ <             < ’9’ < ’A’ < ’B’ <           < ’Z’ < ’a’ < ’b’ < ... < ’z’



                       Python                                                     ord(c)
                                         chr(n)                                         1.2
                                                           chr(n)
62                                                                       1

     print " ",
     for n in range(0,16): print "%02X"%n,
     for n in range(32,128):
         if n%16 ==0: print; print "%X"%n,
         print "%2s"%chr(n),



1.3.4     string
                                          string                         string
                          string
                     (                                                           )
     from string import *
     s=’alice’
     print upper(s)      # ALICE
     print find(s,’ic’) # 2
     print find(s,’iq’) # -1

  upper                                                         lower(               )
swapcase(                                 )           find
                     index                    index




      a=’     alice=18       bob=20       ’
                a
        [’alice’, ’18’]


     from string import *
     a=’     alice=18   bob=20   ’   #
     b=strip(a)
     print b     # alice=18   bob=20
     c=split(b)
     print c     # [’alice=18’, ’bob=20’]
     x=c[0]
     print x     # alice=18
     d=splitfields(x,’=’)
     print d     # [’alice’, ’18’]


                                      1        1
tuple                                                    list                #


     a="alice"
     print tuple(a) # (’a’, ’l’, ’i’, ’c’, ’e’)
     print list(a) # [’a’, ’l’, ’i’, ’c’, ’e’]
1.3.         (string)                                                            63

                                       1                    string
join(t,s)                    t                                 s
                  s              1                                   #


   from string import *
   a="alice"
   b="bob"
   print join((a,b))       # alice bob
   print join((a,b),"-")   # alice-bob
   print join((a,b),"")    # alicebob



1.3.5


                                                                4




   # coding: SHIFT-JIS
   print "       "

            SHIFT-JIS                SHIFT-JIS        Windows
                                                                     (Unicode)
                                           UTF-8




                            1.1:

             MacOSX                          Safari




  4
64                                                                                                1



                                    (                                                                    )

     # coding: shift-jis
     a="       "
     print a, len(a)
     b=u"        "
     print b, len(b)

                            SHIFT-JIS

                    8
                    4
                5
                    len(a)                a              len(b)       b

         a="            "

                        8

         b=u"           "

                                                16                                    (
          4                  )                   "        u           (           U          )




  ASCII      (                            )s                      u
u=unicode(s)
                              u         ASCII        s
s=str(u)

                                                 ASCII                        SHIFT-JIS

          codes                                                       codes
          getdecoder         getencoder




     5                  b   print                                 Python   2.3jp(SJIS enhanced)
 SJIS                                                    MacOSX                                       print
1.4.         (tuple)                                                                          65

   # coding: shift-jis
   import codecs
   s="       "
   f=codecs.getdecoder("shift-jis")
   print f(s) # f(s) is ("       ", 8)

   u=u"       "
   f=codecs.getencoder("shift-jis")
   print f(u) # f(u) is (u"       ", 4)



1.4                  (tuple)
  (6201,11349)               ( )                                                        (tuple)
                         (’alice’, 18)
                                                                            (’alice’, 18,
(’bob’, 3))                    ()                       (2)             2
                 2                     (2,)


1.4.1
                           t                  len(t)
       t=(’alice’, 18, (’bob’, 3))
           len(t) 3

                                                                                    :
(3,5)+(4,6,7)            (3,5,4,6,7)

                             a
       a=(2, ’alice’, (abs, -5))

       a[0]          2
       a[1]              ’alice’
       a[2]              (abs, -5)
       a[2][0]            abs
       a[2][1]            -5
                                              a[2][0](-7)     abs(-7)                     7



       (x,y)=(2,3)
            x 2            y   3                                              ( )
                                                 :
       x,y=2,3
66                                         1

      [ ]        [ ]             [ ]
        ‘:’                  3


      a[0]=3




                         (             )


1.4.2
                                               *



     def f(a,*t):
          print t
     f(1)         # ()
     f(1,3,7)     # (3, 7)
1.5.             (list)                                              67

       1.1                                          gcd


  1.1
#
# greatest common devision
# usage: gcd(x,y,z,...)
#
def gcd(x,*t):
    x=abs(x)
    if len(t) == 0:
        return x
    if len(t) == 1:
        y=abs(t[0])
        while y:
            z = x % y
            x,y = y,z
        return x
    else:
        u = gcd(x,t[0])
        for z in t[1:]:
            u = gcd(u,z)
        return u
print gcd(123)           # 123
print gcd(12857,21229) # 299
print gcd(299, 27761)    # 23
print gcd(12857,21229,27761) #         23




1.5                       (list)
             (list)
                                            [3,7]     [ ]
       []


1.5.1
                                   a                        len(a)
68                                                                              1



         a=[3,7]
                                                  a[0], a[1]              [ ]           [
]                                          a[0]    3 a[1] 7



         a[0] = 5
                          a              [5,7]


         a=[2,’alice’,[abs,-5]]


         a[0] 2
         a[1] ’alice’
         a[2] [abs,-5]
         a[2][0] abs
         a[2][1] -5
                                                  a[2][0](-7)   abs(-7)             7



                                                                                    :
[3,5]+[4,6,7]          [3,5,4,6,7]


a = a + [2,8,1]
               +

append                   1
         a = a + [2]


         a.append(2)
          append                     6

    a + [2] a.append(2)         2                                               +
                                                  append
         a=[3,7]
         b=a
         a=a+[2]


     6     a             (.)
1.5.          (list)                                                                  69



       b   [3,7]
       a   [3,7,2]


       a=[3,7]
       b=a
       a.append(2)
                         a   b       [3,7,2]      append



                                 /
             a=[3,7,2,5]
       a[2:2] = [1,8,4]
              a    [3, 7, 1, 8, 4, 2, 5]               a[2]
            a[2:2]
       a[n:m] = [1,8,4]
   a[n:m]     [1,8,4]
       a[n:m] = []
           Python                                del
       del a[n:m]


    range for                    range                                   range(1,5)
[1,2,3,4]


1.5.2
               a.append(2)           append       a           (method)         append




                       1.2                sort
70                                                                                    1



          a.append(x)                 a         x
          a.sort()                    a
          a.sort(t)                   a             t
          a.reverse()                 a
          a.index(x)                  a                 x
                           (                            )
          a.insert(i,x)               a                     i            x
          a.count(x)                  a         x
          a.remove(x)                 a         x
                           (                            )

                               1.3:




                               a.sort()     sort
      a                               a                                sort




                 sort
                 x, y                                               x=(’alice’,16)
      x[0]   ’alice’      x[1]  16                  y                      cmp(x,y)       x < y
         x > y             x==y            0            Python




1.5.3     2
  2
                                                               
                                             3
                                            
                                                   1       5   
                                                                
                                                                
                                            
                                                               
                                                                
                                          a= 2
                                            
                                            
                                            
                                                   4       8   
                                                                
                                                                
                                                                
                                                                
                                            
                                                               
                                                                
                                              7     6       1


      a=[ [ 3, 1, 5],
          [ 2, 4, 8],
          [ 7, 6, 1]]
                                            0
      a[0]    [ 3, 1, 5]
1.5.          (list)                                               71

  1.2
a=[8,2,1,3,4,0,9,5,3]
print a.count(3) # 2
print a.index(0) # 8
a.sort()
print a # [0, 1, 2, 3, 3, 4, 5, 8, 9]
a.reverse()
print a # [9, 8, 5, 4, 3, 3, 2, 1, 0]
a.remove(5)
print a # [9, 8, 4, 3, 3, 2, 1, 0]


  1.3
def cmpf(x,y):
    return -cmp(x[1],y[1])
d=[(’alice’, 16), (’bob’, 20), (’carol’, 13)]
d.sort(cmpf)
print d         # [(’bob’, 20), (’alice’, 16), (’carol’, 13)]


       a[1] [ 2, 4, 8]
       a[2] [ 7, 6, 1]
       a[0][0] 3 a[2][1]          6

                            a[2][1]
                   a[2,1]
                                                           0


       a=[[0]*3]*3
          a            [[0, 0, 0], [0, 0, 0], [0, 0, 0]]


       a[0][0]=2
   a       [[2, 0, 0], [2, 0, 0], [2, 0, 0]]                    Python
   a=[[0]*3]*3              (     )
       t=[0]*3
       a=[t]*3


          a=[0]*3
       a[0]=[0]*3
       a[1]=[0]*3
       a[2]=[0]*3
72                                                                                     1

1.5.4                  (             )
                                                                 factors(x)        x
                                     36000
      [2, 2, 2, 2, 2, 3, 3, 5, 5, 5]



  1.4
def factors(x):
    "factor decomposition"
    f=[]
    while x % 2 == 0:
        f=f+[2]
        x = x / 2
    n=3
    while x >= n * n:
        while x % n == 0:
            f=f+[n]
            x = x / n
        n = n + 2
    if x == 1: return f
    return f + [x]
print factors(36000)


                                                      14443

                           2 3   5   7 9     11   13        15    ···


3                                                                                          11
                      1313(= 14443/11)                 11                     13
            101(= 1313/13)           13                                 13         13 × 13 > 101
     101                       (        13                                                     )
                                                  3
      f=f+[2]
      f=f+[n]
      return f + [x]
           append
      f.append(2)
      f.append(n)
      return f.append(x)
1.6.          (dictionary)                                                          73

                                                               (
                                                           )



1.6               (dictionary)
1.6.1
                                      a
a[0], a[1], a[2], ...
                             Pyhton            (                                )
                                7


a[’alice’], a[’bob’]
                                          ’alice’      ’bob’




       a={}
                      a
       a={’alice’:13, ’bob’:15}
                                                   2      ’alice’      ’bob’
                                    13    15
                                                                   a      ’carol’
       17
       a[’carol’] = 17
                                a[’carol’]


1.6.2


       a={’alice’:13, ’bob’:15, ’carol’: 17}


a.get(’alice’) 13
a.keys() [’bob’, ’alice’, ’carol’]
a.values() [15, 13, 17]
a.items() [(’bob’, 15), (’alice’, 13), (’carol’, 17)]
       keys   values items
  7
74                                                                                            1

                            (                                            )
                                                              in
       ’alice’ in a             True
       ’david’ in a             False



                                                del
       del a[’alice’]
         ’alice’

                                                                       a.clear()



                    b=a.copy()          a                 b


1.6.3                       (               )



      alice   23
      bob     52
      alice   81
      carol   37
      carol   53
  1             1



       alice 104
       bob 52
       carol 90




                                                                   2


 1.           d                         pr(d)
 2.           d             k                                 v                  put(d,k,v)
                    k   d                             k                      v
1.6.       (dictionary)                           75

  1.5
from string import *
def put(d,k,v):
    if k in d: d[k]=d[k]+v
    else: d[k]=v
def pr(d):
    for k in d: print k,d[k]

# test data
s=[ "alice 23",
    "bob 52",
    "alice 81",
    "carol 37",
    "carol 53" ]

# test program
d={}
for x in s:
    k,v=split(x)
    v=int(v)
    put(d,k,v)
pr(d)



    1.5   pr(d)       put(d,k,v)




                  4    1


1.6.4


3
a={}                   #
a[1]=3                 #           OK
a[1.2]=3               #           OK
a[’alice’]=3           #               OK
a[(1,4)]=3             #             OK
a[1,4]=3               #           OK [ ]   1,4
76                                                                       1

a[1,’alice’]=3          #            OK




                                                            2
                                                       
                                             3 1
                                            
                                                   5   
                                                        
                                                        
                                            
                                            
                                                       
                                                        
                                                        
                                          a= 2 4
                                            
                                            
                                                   8   
                                                        
                                                        
                                                        
                                            
                                                       
                                                        
                                              7 6   1
     (              )
         a={(1,1):3, (1,2):1, (1,3):5,
            (2,1):2, (2,2):4, (2,3):8,
            (3,1):7, (3,2):6, (3,3):1}
                                                                0
a[1,1]       3   a[3,2]     6


1.6.5


         f(alice=18, carol=10)
                                                                              f
                                              GUI                   Tkinter




  1.6
def f(**k):
    print k          # {’carol’: 10, ’alice’: 18}
    d={’alice’:16, ’bob’:20, ’carol’:12}
    for x in k.items():
        d[x[0]]=x[1]
    print d          # {’alice’: 18, ’bob’: 20, ’carol’: 10}
f(alice=18, carol=10)


                                **


         f(alice=18, carol=10)
1.6.       (dictionary)                                    77

                          k   k={’alice’:18, ’carol’:10}



       for x in k.items():
           d[x[0]]=x[1]
                                                                                                                           79




         2

                                                    1



          :
                                              ()                          (               )



      x s alice Alice a0x 01
           123 123.45 1E-3 3+4                                                                        L.Carroll       Lewis
Carroll
                                                          alice      Alice
                         Python

     access              and          break        class       continue           def                     del
     elif                else         except       exec        finally            for                     from
     global              if           import       in          is                 lambda                  not
     or                  pass         print        raise       return             try                     while

                                                   2.1:




         x=5
                   ‘=’                                                                                        x
                                          x                         ‘=’               5


 1       1: Python                                                            (FORTRAN, BASIC, PASCAL, C               )
                  :
                                                                              (               )




 Python                                                                                                   (
                   )         Python                                                       (                       )
     (        C                Python                                     ) Python                (
               )
                                                                    Python
              Python                                       Python
                                  (            3   3           )
80                                                                          2

                                                                                x         5


        y=x*(x+1)


        y=5*(5+1)
                                       30           y
                                                            n       3
        n=n+1
                n                 3    4
                                            5                       x           "alice"


        x=5
        ...
        x="alice"


      ‘=’                                               ‘=’


        a=[’apple’,1]
        b=[’apple’,1]
        c=b
                    a    b                                                  c       b
                        (                               3       3       )



2.1




        a*x*(x+b)
                    a, b, x



                                  ‘+’ ‘*’ ‘(’ ‘)’
‘+’      ‘ *’
        ( 2.2                 )                                         ‘( )’
2.1.                                                                                             81

            x or y, lambda
            x and y
            not x
            <, <=, >, >=, ==, <>, !=,
            is, is not, in, not in
            x | y                                                          OR
            x ˆ y                                                          XOR
            x & y                                                          AND
            x << y, x >> y
            x + y, x - y
            x * y, x / y, x % y
            -x, +x, ˜x
            x[i], x[i:j], x.y, x(· · ·)
            (· · ·), [· · ·], {· · ·}, ‘· · ·‘


                                                 2.2:


                                                             x   y




                                                                                    (
  )




       for x in [1996,1999,1900,2000]:
           print x, leap(x):
                                                        leap(x)
            1                                               Python       for
       print 1996, leap(1996)
             Python leap(1996)                                                          Python
       leap(x)                                              1        3          3
         Python    leap(1996)

                                   (                         )
82                                                                                            2

2.2

      5
      +           -       *       /            %




      x + y, x - y, x * y, x / y, x % y, -x, +x
         *                                        /               %                                             23/5
     4 23%5 3                                 -23/5        −5 -23%5 2                         −4       −3
           Python                            (-)                (/ %)                                       -23/5
     (-23)/5      -23%5                   (-23)%5                         Python
                                                                y       x y                        r
          x

                                                   x = py + r       (0≤r<y)

              r               (                                             x                               Python
                                                                                )y        x   y
      r                               x

                                                   x = py + r       (0≥r>y)

              r


      x + y, x - y, x * y, x / y, x % y, -x, +x



                                                                                      x                     y
                                                                        y                              x            y
                                          Python                                x%y                             r
                      (x, y                                     )
      p=floor(x/y)
      r=x-p*y


      x + y, x - y, x * y, x / y, x % y, -x, +x
                                           x       y                             Python
2.3.                                                                                                              83

2.3
                   2
        x              100              x < 10000
                                                                       ‘=’               ‘==’




                                       X == Y           X      Y
                                       X != Y           X      Y
                                       X <> Y           X != Y
                                        X<Y             X      Y
                                        X>Y             X      Y
                                       X <= Y           X      Y
                                       X >= Y           X      Y
                                       X is Y           X      Y
                                   X is not Y           X      Y
                                       X in Y           X      Y
                                   X not in Y           X      Y


                                            2.3:                   (     X, Y        )

                   2           Y


                             True                      False                 2
                                                                                                        1         0
                                       Python 2.3
       True == 1
  True
  True        False                                1 0                                          1   0
                                                   True            1   False     0                          int
                                              int(True)            1
  Python
       0 < X < Y == Z
             3
       0 < X and X < Y and Y==Z




  2 Python   2.2                   1    0
84                                                                                                             2

X==Y          X is Y

    Python                                                                X==Y        X       Y
                               X is Y               X     Y



2.4
                         (True=      False=                               )
                             and or not                                                                  2.4

                         X and Y        X       Y
                         X or Y         X                Y                     (                    )
                            not X       X

                                                        2.4:
                                                X       Y


              x        50     y             200
       x < 100 and y < 100


              True     False                     0                  1                                    2.3
0             1                    2.4                   X          Y     0           1                            0       1
                                  1 0                                         (and)               (or)                     3


                                                X and Y             Y=0       Y=1
                                                    X=0              0         0
                                                    X=1              0         1


                                                             2.5:


                                                X or Y          Y=0       Y=1
                                                    X=0             0         1
                                                    X=1             1         1


                                                             2.6:

                                    X       Y       0               1                                                  0       0
                                                                                          1                                    0

     3 True   False
2.5.                                                                                                                 85

2.5
                                                                                                                 (
                                                                                        )
                                                                       (
                                          )                  2.7           3
                   x       y                                           ˜    0       1            1     0

             x|y        y=0         y=1        xˆy     y=0    y=1               x&y         y=0            y=1
             x=0           0          1       x=0       0          1        x=0                  0          0
             x=1           1          1       x=1       1          0        x=1                  0          1
                               OR                           XOR                                      AND

                                                2.7:


    Python
                                                             Python 2.2                                (              )
                 (32                 )
C




                   32
        3    2                                00000000000000000000000000000011
        5    2                                00000000000000000000000000000101
                                   OR,        XOR,          AND,

                                             2
                       3|5         00000000000000000000000000000111                         7
                       3ˆ5         00000000000000000000000000000110                         6
                       3&5         00000000000000000000000000000001                         1
                       ˜5          11111111111111111111111111111010                         -6

                                                                                I
        I << n
    I                          n                             n         0
        5 << 2                      00000000000000000000000000010100                                  20


        5 >> 2                      00000000000000000000000000000001                                   1
                                                                                                      1
                       1
86                                                                  2

         -6 >>2         11111111111111111111111111111110            -2



 Python 2.3
                                                       Python 2.2
          (                         )   Python 2.4          (             )


     1                      0   1                          bin
         -8       16



     def bin(i):
         s=""
         for n in range(0,32):
              s=s+str(int(i&(1<<31-n)!=0))
         return s
     for x in range(-8,17): print "%3d"%x, bin(x)

                  32                                                str


 -8      11111111111111111111111111111000
 -7      11111111111111111111111111111001
 -6      11111111111111111111111111111010
 -5      11111111111111111111111111111011
 -4      11111111111111111111111111111100
 -3      11111111111111111111111111111101
 -2      11111111111111111111111111111110
 -1      11111111111111111111111111111111
  0      00000000000000000000000000000000
  1      00000000000000000000000000000001
  2      00000000000000000000000000000010
  3      00000000000000000000000000000011
  4      00000000000000000000000000000100
  5      00000000000000000000000000000101
  6      00000000000000000000000000000110
  7      00000000000000000000000000000111
  8      00000000000000000000000000001000
  9      00000000000000000000000000001001
 10      00000000000000000000000000001010
 11      00000000000000000000000000001011
 12      00000000000000000000000000001100
2.6. lambda                                          87

 13   00000000000000000000000000001101
 14   00000000000000000000000000001110
 15   00000000000000000000000000001111
 16   00000000000000000000000000010000




2.6     lambda
 lambda


      def f(         ): return


      def f(x,y): return x+y
      print f(2,3)     # 5
                          lambda
      f=lambda x,y: x+y
      print f(2,3)      # 5
 lambda
      lambda          :
 lambda                   def
           lambda                1
      print (lambda x,y: x+y)(2,3) # 5
def
                     lambda


  f=[0]*5
  for n in 1,2,3,4: f[n]=eval("lambda x: x**%d"%n)
  print f[1](2) # 2
  print f[2](2) # 4
  print f[3](2) # 8
  print f[4](2) # 16

def                                      lambda

          : lambda
                                                                             89




      3


3.1
3.1.1
                  (statement)                                ‘statement’


      x = 5
          5        x
              (simple statement)    (compound statement)             print

                                             try

                                                       ‘;’



              ( def   )            (class     )

                                    1    1




3.1.2
                          ‘#’




3.1.3


1.            (           )
2.
90                                                                           3

3.


                                         x=5 ; a="#"        # ............


                                            3.1:




3.1.4
                                                                             (              )
              :

                                           Python
                                     (                               )
                                                       Python



                           #1   #3                                   0           #4    #7
                           4

  3.1            1
x=1                             #1
y=1                             #2
while x < 10000:                #3
    print x                     #4
    z = x + y                   #5
    x=y                         #6
    y=z                         #7




3.1.5
     2            A    B                                        A        B        (A    B   )
                                                                                 3.1        1
         #1           #3                               #4       #7
3.1.                                                                                                         91

                                                     1
         3.2                                                                     4

  3.2            2
def sim(x,p,r):                                                                                        #1
    n=0                                                                                                #2
    while x > 0:                                                                                       #3
        y=x*(1+r)                                                                                      #4
        z=y-p                                                                                          #5
        n=n+1                                                                                          #6
        # print "%3d %10.4f %10.4f %10.4f" % (n,x,y,z)                                                 #7
        x=z                                                                                            #8
    return (n,y)                                                                                       #9
                                                                                                      #10
for x in range(0,11):                                                                                 #11
    print "%3d %10.4f" % sim(3000,200+10*x,0.05)                                                      #12




         #1 #11
         #2 #3 #9
         #4 #5 #6                 #8
         #12

#7             #10                                         #12   #9
                     #11




           ‘:’                (                             )
         def sim(x,p,r)
         while x > 0
         for x in range(0,11)
     3                                 (            def               while     for                  )
                                                                      1     H         H                  H
                                           H                              #1
         def sim(x,p,r)
                     #2           #9

     1               2                         5%   3000                                  ( 200        210
          300            )                                                                        sim(x,p,r)
  x                                   r              p
                             sim(x,p,r)
92                                                                                 3



               ‘:’                        1                                            2   #3   #8
while            #1      #9             def




3.1.6


                          +       -     *     /  %         |    ˆ   &
                          ,       .     :     ;  ‘         ’    "
                          =       ==    !=    <> <         <=   >   >=   <<   >>
                          (   )        [ ]    { }

                                                    3.2:




      z = x + y


      z=x+y
                                         2
1.                                            1.2

2.

           1
      def sim(x,p,r):
     def       sim            1


      def             sim(x,p,r):
3.2. print                                                                                                93

                                 (                                 )
      def sim(x,p,r):
  def      sim                                                           defsim




3.2       print
  print
                 1                                                         print


                     print
                     print
                     print           ,      ,        ,


                                         3.3:                      print


                                                                                         print
                                                                                                      %


                     print           ,
                     print           ,      ,        ,       ,


                                 3.4:                                  print


                 Python                              print
                                 print




3.2.1
                             %


      "name=%s age=%d" % (’alice’, 18)
           (’alice’, 18)                         %                     "name=%s age=%d"


      "name=alice age=18"
                                                name             "alice"           age           18
94                                                                                  3

     print "name=%s age=%d" % (name, age)


     name=alice age=18


                       "name=%s age=%d"               %           s   d
                                                                 "x=%X"%x                          %X
     x   16                                                    x       12                         ’x=C’

         3.1   Python                                                                   %i   %u




               s                           x, X           16
               c                           e, E
               d                           f
               o                8          g, G                        /

                                               3.1:


                                %
"%5d"%18               ’       18’                        18                3
                   5                  -5                                                     "%05d"%18
     ’00018’               0

                                                               5                                          10
          "%10.5f"                                                 x       (1.0/3)
"%10.5f"%x
     ’   0.33333’


                                     "%12.4E"%(1.0/3)
     ’   3.3333E-01’
           E                                                       G

Python                      C                                                                 %s
                           (#                                                   )
     s="alice"
     print "---%s---"%s              # ---alice---
     print "---%10s---"%s            # ---     alice---
3.3.                                                                                          95

       print "---%-10s---"%s     # ---alice       ---
       n=123
       print "---%s---"%n        # ---123---
       print "---%10s---"%n      # ---       123---
       print "---%-10s---"%n     # ---123       ---
       x=10.0/3
       print "---%s---"%x        # ---3.333333333333---
       print "---%10.5s---"%x    # ---      3.333---
       print "---%-10.5s---"%x   # ---3.333      ---
Python



3.3
                                       (                                  )             ‘=’
            ‘=’                                                            [   1]


                       =


                                     3.5:


                                              (Python

                                                                      )
         1. Python
           X=Y=3
                      C                                  Python                     C
                                                          1


Python                                                  3.6

                                                              print


       a=[’apple’,1]
       b=[’apple’,1]
       c=b
       b[0]=’orange’
       print a     # [’apple’, 1]
       print b     # [’orange’, 1]
96                                                                 3




                                名札
                                 a
                                                   データ


                                 3.6: Python


     print c      # [’orange’, 1]
                                 ?
a         b                  ["apple",1]
                                  c=b          b                   c




                                                    名札
          名札
                                                    b         名札
          a
                             データ
                                                              c        データ



          b[0]="orange"              b                                       c

                     1                   1



    X,Y                              X is Y         X    Y
                         1                                0
     a=[’apple’,1]
     b=[’apple’,1]
     c=b
     print a is b         # 0
     print c is b         # 1


     a=[’apple’,1]
     b=[’apple’,1]


      ?
3.3.                                 97




   1                         1
       a=’apple’
       b=’apple’
       print a is b    # 1
        a   b

   2                         0
       a=(’apple’,1)
       b=(’apple’,1)
       print a is b    # 0
        a   b
                                 ?
98                                                     3

3.4


           3                   (Zeller        )
                                             #


  3.3
"""
h(y,m,d): day of week (Zeller’s formula)
                                     (        ,1989)
y: year, 0,1,2,..
m: month, 1,2,..,12
d: day of month, 1,2,..31
return: day of week, 0,1,2,..,6
example: h(2000,1,1) -> 6    # Saturday
"""
def h(y,m,d):
    if m<3: y=y-1; m=m+12
    return (y+y/4-y/100+y/400+(13*m+8)/5+d)%7




                                  2
         Python
                                                           (   )




     2            C   Python             6
3.5.                                                                                                    99

3.5



  Python


                   if         :

                   elif           :

                   elif           :

                   ···
                   else:




                                              3.7: if               1




                 Python                                         True              (       0                )

                                                                                                      elif
                                                                             if               else
                                                        (elif    ‘else if’                             )
           if


                   if         :



                                              3.8: if               2



   7                                                                                  0       1   2
           200                0       1   2                     5       2    3
                   0      1
100                                                           3

  3.4
from random import *
n=0
while n < 200:
    x=random()
    if x < 0.5: print 0,
    elif x < 0.7: print 1,
    else: print 2,
    n=n+1



3.6
3.6.1     while       for
  Python      2


                      while        :



                                             3.9: while




                      for               in       :



                                             3.10: for


  while
      x=0
      while x < 5:
          print x
          x=x+1
        x<5
      print x
      x=x+1
                  (     0, 1, 2, 3, 4                     )
  for
3.6.                                                                                                 101

       for x in [5,2,3,6]: print x


       print   5
       print   2
       print   3
       print   6




3.6.2     range
  for
range                                 range       1       3

       range(b)
       range(a,b)
       range(a,b,c)

 range             a b c       x                      x           (x < b)
x a                 x < b                     c
c 1                 range(a,b)                                a                              0


       for x in range(3,13,4):
               x   3, 7, 11
  range                                                                              range


       range(13)              [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
       range(3,13)            [3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
       range(3,13,4)          [3, 7, 11]
  range
                                                  range            xrange                    3




3.6.3     continue            break


           continue           break                                   continue

  3      Python     xrange                                                  xrange
xrange    xrange                                                                             for
                                                                                 for               xrange
          range
102                                                                    3

                                                                  break
                                         if
                         3.5                  continue    break
                               (                         )

  3.5 continue    break
for x in [3,4,5,6,7]:
    print x
    if x==5: continue
    print "alice"
    if x==6: break
    print "bob"




      3
      alice
      bob
      4
      alice
      bob
      5
      6
      alice
  x     5     print "alice"                                 x      6       print "bob"




3.7
3.7.1       def
                  (def     )


                         def       (      ):



                                       3.11: def


  def
                   (           )
3.7.                                                                                            103

             3.6
       sim(3000,200,0.05)
                   sim                                             x, p, r    3000, 200, 0.05
                          (                                 )

  3.6
def sim(x,p,r):
    # x: amount of loan
    # p: every year payment to return the loan
    # r: rate
    # return: number of years to finish and the last payment
    if x*r >= p: # unable to return the loan
        return None
    n=0
    while x > 0:
        y=x*(1+r)
        z=y-p
        n=n+1
        x=z
    return (n,y)

print "%3d %10.4f" % sim(3000,150,0.05)




3.7.2       return


                                               return                         return
                          return


                         return


                                           3.12: return


                                                          return                            return
                                  return                                     None
           None                                             None                       return

       (                                          )
104                                                                      3

3.7.3


      def            ():




              ()
                           ()            ()


3.7.4


                                                                                         sim
  x, p, r, n, y, z

                                                           ?




                                                                                 (        )




            3.7

        2                       :
                                                                wday
                                                    cal0(n,m)
      for x in wday: print " ",x,
  wday
                                                                         4
                                                                                         global
                                       global              3.8
      3.8                           global                   f(x)          g()       a
            f(3)                                a     3                 g()
        a                                       3                   global
  4
3.7.                                                         105

  3.7
wday=("sun","mon","tue","wed","thu","fri","sat")
def cal0(n,m):
    for x in wday: print " ",x,
    print
    for x in range(0, n): print " ---",
    for x in range(1, m+1):
        print "%5d"%x,
        if (x+n)%7==0 : print
cal0(6,31)


  3.8 global
def f(x):
    global a
    a=x
def g():
    global a
    print a
f(3)
g() # 3
print a # 3
a=4
g() # 4



                                                   3

  2                   global
       global a,b,c




3.7.5
  Python                       (     )                 3.9




2 3 13 20 () {}
106                                                                            3

  3.9
def f(x,y,a=13,b=20,*t,**k):
    print x,y,a,b,t,k

f(2,3)
f(2,3,alice=18, carol=10)
f(2,3,5,alice=18,carol=10)
f(2,3,5,7,8,9,alice=18,carol=10)



2 3 13 20 () {’carol’: 10, ’alice’: 18}
2 3 5 20 () {’carol’: 10, ’alice’: 18}
2 3 5 7 (8, 9) {’carol’: 10, ’alice’: 18}



                  4

                                                       4
 1.                                                        f                       2       x       y

                          2                                                                    f
                      2
 2.                                                                    a   b
                                                                                       3
              a               4                                    b
 3.                                    *                                                   t
                                                               4
                                           t
 4.                               **                                               k



                                                               1       4
          1   4                    1           6



3.8
3.8.1     class
  class           (                                )                                                   Python
3.8.                                                                                          107




                                Python
                    (2, 3, 7)
                                                        (2, 3, 7) + (5, 1, 4)    (7, 4, 11)
        Python       (2,3,7)              2
                           (2,3,7)+(5,1,4) (2,3,7,5,1,4)
                                                                        ?
                                                                         1
                                                           (
  )




3.8.2
          3.10                                                               Vector
                        (                                                    )
  1. v=Vector(2,3,7)                  (2,3,7)                                v
  2. Vector              Vector
  3. Vector                                                                              Vector


  4. Vector


  class Vector: —
  v=Vector(2,3,7)

                 def __init__(self,*t):             1i
                     if len(t)==1: t=t[0]           2i
                     self.v=t                       3i
                       __init__

  Vector(2,3,7)             (2,3,7)      __init__   t                                   t=(2,3,7)
             Vector              1                                                    t=((2,3,7))
                      2i
108                                                        3

  3.10
class Vector:
    def __init__(self,*t):
        if len(t)==1: t=t[0]
        self.v=t
    def value(self):
        return self.v
    def __add__(x,y):
        u=[]
        if hasattr(x,"v"): x=x.v
        if hasattr(y,"v"): y=y.v
        for n in range(0,len(x)):    u.append(x[n]+y[n])
        return Vector(tuple(u))
    def __sub__(x,y):
        u=[]
        if hasattr(x,"v"): x=x.v
        if hasattr(y,"v"): y=y.v
        for n in range(0,len(x)):    u.append(x[n]-y[n])
        return Vector(tuple(u))

v=Vector(2,3,7)
u=Vector(5,1,4)
s=Vector(8,2,6)
print (u+v+s).value()    # (15, 6, 17)
print (v+u-s).value()    # (-1, 2, 5)
z=Vector(0,0,0)
print (z + (2,3,7) + (5,1,4) + (8,2,6)).value()      # (15, 6, 17)
print (z + (2,3,7) + (5,1,4) - (8,2,6)).value()      # (-1, 2, 5)




3.8.3   self
          3i                  self
                    v     t             i
                                        3                  __init__   1
self
  x Vector                               x.value()


      def value(self):
          return self.v
3.8.                                                                                  109

                self     x                      x.value()               v
                             value(x)                       x
   v     x.v                       x                            value       x.value




3.8.4


       def __add__(x,y):
           u=[]
           if hasattr(x,"v"): x=x.v
           if hasattr(y,"v"): y=y.v
           for n in range(0,len(x)):       u.append(x[n]+y[n])
           return Vector(tuple(u))
                         __add__                            2      if         x, y



       return Vector(tuple(u))
                                   Vector
                                     __add__   __sub__


               x+y                       __add__
               x-y                       __sub__
               x*y                       __mul__
               x/y                       __div__
               x%y                       __mod__
               -x                        __neg__
               +x                        __pos__
               x**y                      __pow__
               x or y                    __or__
               x xor y                   __xor__
               x and y                   __and__
               x<<y                      __lshift__
               x>>y                      __rshift__
               ˆx                        __invert__
110                                                    3

               getattr(obj,name)
               hasattr(obj,name)
               setattr(obj,name,value)
               delattr(obj,name)

        obj                     name        (              ) value



3.9
3.9.1    try
                                 goto                                    Python
  goto                                          goto                 (exception)


  3.11
def func1():
   func2(0)
def func2(x):
   y=1/x
func1()


                    e1.py
bash$ python e1.py
Traceback (innermost last):
  File "e1.py", line 5, in ?
    func1()
  File "e1.py", line 2, in func1
    func2(0)
  File "e1.py", line 4, in func2
    y=1/x
ZeroDivisionError: integer division or modulo




3.9.2    raise


                                           Python
3.9.                                                       111

  3.12 exception "Hello"
def func1():
   func2(0)
def func2(x):
   raise "Hello"
func1()



                        raise        (exception)
              "Hello"                 "Hello"
                                                   e2.py


bash$ python e2.py
Traceback (innermost       last):
  File "e2.py", line       5, in ?
    func1()
  File "e2.py", line       2, in func1
    func2(0)
  File "e2.py", line       4, in func2
    raise "Hello"
Hello



3.9.3    except
          3.13         "Hello"
        input()
1              Alice
0              Bob
2
0.5
Carol



       try:


       func1(input())
                   except
        "Hello"
       except "Hello":
112                                        3

  3.13    (exception)
"""
exception demonstration code
keywords: raise, try, except, else
"""
def func1(x):
    print func2(x)
def func2(x):
    if x == 1:
        raise "Hello"
    y = 1.0 / x
    return y
try:
    func1(input())
except "Hello":
    print "Alice"
except:
    print "Bob"
else:
    print "Carol"




      except:




      else:
              5




3.9.4
         Python                                (   )
ArithmeticError
AssertionError
AttributeError
EOFError
FloatingPointError
IOError
ImportError
  5                              finally
3.10. import    (          )                                            113

IndexError
KeyError
KeyboardInterrupt
LookupError
MemoryError
NameError
OverflowError
RuntimeError
StandardError
SyntaxError
SystemError
SystemExit
TypeError
ValueError
ZeroDivisionError




3.10     import      (                 )



                                                                   import

                           Bob (                   )
                                       Python
                                   6
                                       Bob
      foo.py

  3.14
#
# Number functions
#
def gcd(x,y):
    x=abs(x); y=abs(y)
    while y:
        x,y=y,x%y
    return x

                                                foo.py


                    ‘py’                                 Bob
      from foo import *
  6                                                            !
114                                                                                  3

                          foo.py                                                          7
                                                                                              (foo.py    foo
                      )

 Python                                                                              foo.py
       ?                                                                            Python OS
PYTHONPATH                                       PYTHONPATH           foo.py
                                                                        Bob        foo.py               import
                                                                                      Python
                            foo.py



 Alice Bob                                                    Python
   Bob Alice                              bar.py             Bob
      from foo import *
      from bar import *
                           Bob                                                      foo.py      bar.py
                gcd                          2

                Python              2         import
      import bar
                             Bob                   bar
      bar.gcd




      from bar import factors, prime
               bar                        factors        primes
  Bob     factors           primes                                    bar
   bar                          bar

                      Pyhon                                       (            )
                                                                                   math                 string




  7                              foo.py
                                                                               115




      4


4.1


                                                                      2
                                                                  (       10
                                              )

           1980    91M3069    IMAI TAKAFUMI
            0       813741     772763
            1       839734     796501
            2       873852     832203
            3       896520     852643
            4       942253     895206
            5       987894     939188
            6      1043386     990115
            7      1057899    1009314
            8      1038900     986149
            9      1014408     964781
           10       986691     934427

                           4.1:                   (   : p.txt )




                   p.txt             1
                                                                          3

 1.
 2.
 3.


          Python                  p.txt

 1            Python
116                                                                                  4

  f=open(’p.txt’)
  for s in f.readlines():
      print s,
  f.close()

  f.readlines()               f    open           f

                f.readlines()
      [’1980 91M3069              IMAI TAKAFUMI\n’, ’ 0       813741       772763\n’, ... ]
                                                                                \n
      for                 s
      print s
               s                                           print                              print
                                           ‘,’
                                                      readlines
                      readline

  f=open(’p.txt’)
  s = f.readline()
  for s in f.readlines():
      print s,
  f.close()

                              f.readlines()
      [’ 0            813741       772763’,’ 1    839734      796501’, ...]


                                              3
Python                                                                        Python
            (Python     ‘,’                              )
       3                       string                 split
      t = split(s)
           t                  [’0’,’813741’,’772763’]
                          (                                            )                      int
                                      age male female
      age=int(t[0])
      male = int(t[1])
      female=int(t[2])
            t[0]                                             ’0’               t[1]      ’813741’
t[2]         ’772763’
4.1.                                    117

  4.1
from string import *
f=open(’p.txt’)
s = f.readline()
for s in f.readlines():
    t = split(s)
    age=int(t[0])
    male = int(t[1])
    female=int(t[2])
    print age,male,female
f.close()




       from string import *
        string                      split



            sum_male   sum_female

  4.2
from string import *
f=open(’p.txt’)
s = f.readline()
sum_male=0
sum_female=0
for s in f.readlines():
    t = split(s)
    age=int(t[0])
    male = int(t[1])
    female=int(t[2])
    print age,male,female
    sum_male=sum_male+male
    sum_female=sum_female+female
f.close()
print sum_male, sum_female



   1
118                                                                     4

  2




4.2


                                                                        1
                    Python             1
                          Python
               foo                 s                       bar          s
                 foo                   bar

  4.3                                        1
f=open("foo","r")
s=f.read()
f.close()
# you can change s here if you need
f=open("bar","w")
f.write(s)
f.close()




# you can change s here if you need
                         s
open        close
                               close                                            close
                                        (            1

                                                                    ) open

 DOS      OS(Microsoft Windows       )                             OS
           2                       (’\015’       ’\012’)                     "r"
                   read ’\015’                             write   ’\015’     ’\012’

         DOS        OS
4.2.                                                 119



 "r"                              (        )
 "w"
 "a"
 "r+"
 "w+"
 "a+"
 "rb","wb","ab",     DOS
 "r+b","w+b","a+b"

                             4.1: open



         (TAB          )
                                               4.3
   1

  4.4                                  2
f=open("foo")
x=f.readlines()
f.close()
f=open("bar","w")
for s in x:
    # you can change s here if you need
    f.write(s)
f.close()


        Python
120                                                                                  4




 f=open(name)
 f=open(name,mode)              name:
 f=open(name,mode,bufsize)      mode:                (                 ’r’                  )
                                bufsize:
 f.close()
 s=f.read()                                      s
 s=f.read(size)                 size:
 f.write(s)                                      s
 f.seek(offset,whence)
                                offset:                                 whence
                                0:
                                1:
                                2:                   (EOF)
 f.flush()
 f.tell()
 s=f.readline()                                           1                  s
                                s                             [   1]
 x=f.readlines()                                                                 x
 f.writelines(x)                         x
 f.isatty()                                  [       2]


                         4.2:

      1.



                                                                                 readline
             readlines
      2.           OS
4.3. sys.stdin                                         121

4.3     sys.stdin
 sys                            sys.stdin



                          2



                                                   e




  4.5          1. count.py
import sys
f=sys.stdin
c=[0]*256
def count(c,s):
    for x in s: c[ord(x)]=c[ord(x)]+1
def pr(c):
    for x in range(32,127): print chr(x),c[x]
f=sys.stdin
while 1:
    s=f.readline()
    if len(s)==0: break
    count(c,s)
pr(c)




      f=sys.stdin
         f
      python count.py




              (        a.txt    )
      python count.py < a.txt


  2                                         UNIX
             Windows
122                                                      4

                                    a.txt

       count.py           (UNIX         )
      tr ’[A-Z]’ [a-z]’ < a.txt | python count.py
                   UNIX                             tr
      tr ’[A-Z]’ [a-z]’ < a.txt
           a.txt                                             |
                                   tr
      python count.py
                                                                                  123




      5

            Python             (        )



5.1       input
      input(prompt?)
                                                  Python


                                                             Python
      input()
                ()                                                       prompt
          ‘?’                                                   BASIC(
                      )                         Python     input

 1. Python        input
 2. Python        input      Python




            input()

while 1:
    s=input("> ")
    print s




      >
                          input
                            (prompt =       )
      > 3
      3
124                                        5

                          s
input
      > 2*3
      6


      > ’alice’
      alice
      > (’alice’,16)
      (’alice’, 16)
      > [’bob’,20]
      [’bob’, 20]
      > ’alice’,16
      (’alice’, 16)


      > len(’alice’)
      5
                                    math
                  input

      > a=3
      Traceback (innermost last):
        File "x", line 2, in ?
          s=input("> ")
        File "<string>", line 1
          a=3
            ˆ
      SyntaxError: invalid syntax


                  input


a=5; b=3
while 1:
    s=input("> ")
    print s
5.2. raw input                                            125

      > a
      5
      > a*4
      20
      > a*b
      15


5.2     raw input
      raw input(prompt?)


        input              raw input




while 1:
    s=raw_input("> ")
    print s




      > 2
      2
      > 2*3
      2*3
      > alice
      alice



      : Python                         eval        eval


      a=5
      s=eval("a*3")
      s     a*3             15           input()
eval(raw input())
126                                          5

5.3    rstr, repr, ‘...‘
      str(x), repr(x), ‘x‘
                    x

 repr(x)     ‘x‘                    str(x)




>>> str(123)
’123’
>>> ‘123‘
’123’
>>> str(’123’)
’123’
>>> ‘’123’‘
"’123’"
>>> f
<function f at 1f81d0>
>>> str(f)
’<function f at 1f81d0>’
>>> str(’<function f at 1f81d0>’)
’<function f at 1f81d0>’
>>> ‘f‘
’<function f at 1f81d0>’
>>> ‘’<function f at 1f81d0>’‘
"’<function f at 1f81d0>’"



5.4    filter
      filter(func,s)
                s            func




               filter
5.5. map                                                127

def f(x): return x%2
v=[1,3,4,2,3,5,6]
print filter(f,v) # [1, 3, 3, 5]



      def filter(f,v):
          r=[]
          for x in v:
              if func(x): r=r+[x]
          return r


5.5       map
      map(func,s)
                s                func




def f(x): return x%2
v=[1,3,4,2,3,5,6]
print map(f,v) # [1, 1, 0, 0, 1, 1, 0]


                map
      def map(f,v):
      r=[]
      for x in v:
      r=r+[func(x)]
      return r


5.6       reduce
      reduce(func, s, init?)
      2         func                     s   init
                               s[0]

                reduce                              :
      def reduce(f,s):
          t=s[0]
          for x in s[1:]: t=f(t,x)
          return t
128                                          5

                     :
      def reduce(f,s,i):
          t=i
          for x in s: t=f(t,x)
          return t


  1


def f(x,y): return x+y
v=[1,3,4,2,3,5,6]
print reduce(f,v) # 24                   v




  2


T=(type(""),type((1,)),type([1]))
def g(x,y):
    if type(x) in T: x=reduce(g,x,0)
    if type(y) in T: y=reduce(g,y,0)
    return x+y
def sum(s):
    return reduce(g,s,0)
print sum([2,3,[4,5]]) # 14
print sum([[4,5]]) # 9
print sum([2]) # 2
print sum([]) # 0




5.7    eval
      eval(code)
      Python                     code




           input()   eval(raw input())
5.8. exec                                                     129

a=3
print eval(’a*7’) # 21



5.8     exec
      exec(code)
       Python            code       code
      compile




exec(’a=3’)
print a # 3




5.9     execfile
      execfile(file)
      Python              file




execfile(’a1.py’)               #   a1.py




5.10     compile
      compile(code, label, kind)
      Python                                label
                                                    kind   "eval"
                "exec"
130                                                           5

s="""
#
# Fibonacci series
#
x=1;y=1
n=1
while n < 100:
    print n, x
    z=x+y
    x=y
    y=z
    n=n+1
"""
c=compile(s,’Fibo’,’exec’)
exec(c)



1 1
2 1
3 2
4 3
[    ]
44 701408733
45 1134903170
Traceback (innermost last):
  File "a1.py", line 15, in ?
    exec(c)
  File "Fibo", line 9, in ?
OverflowError: integer addition

                      "a1.py"                                     "Fibo"
      compile   2                    Python
                                py_compile          compile



5.11     id
      id(obj)
                obj   ID           (          obj                          )
5.12. type                                                                      131

5.12        type
      type(obj)
      obj




      >>> type("")
      <type ’string’>
      >>> type(0)
      <type ’int’>



5.13        hash
      hash(obj)
                   obj



5.14        callable
      callable(obj)
                                     1
                   obj                   1                0



5.15        dir
      dir(obj?)
                   obj                            obj                     dir
                                 (            )




>>> a=[2,3]
>>> x=5
>>> dir()
[’__builtins__’, ’__doc__’, ’__name__’, ’a’, ’x’]
>>> dir(__builtins__)
[’ArithmeticError’, ’AssertionError’, ’AttributeError’, ’EOFError’,
’Ellipsis’,’Exception’, ’FloatingPointError’, ’IOError’, ’ImportError’,
’IndexError’, ’KeyError’, ’KeyboardInterrupt’, ’LookupError’, ’MemoryError’,
’NameError’, ’None’, ’OverflowError’, ’RuntimeError’, ’StandardError’,
’SyntaxError’, ’SystemError’, ’SystemExit’, ’TypeError’, ’ValueError’,
  1
132                                                                   5

’ZeroDivisionError’, ’_’, ’__debug__’, ’__doc__’, ’__import__’, ’__name__’,
’abs’, ’apply’, ’callable’, ’chr’, ’cmp’, ’coerce’, ’compile’, ’complex’,
’delattr’, ’dir’, ’divmod’, ’eval’, ’execfile’, ’filter’, ’float’,
’getattr’, ’globals’, ’hasattr’, ’hash’, ’hex’, ’id’, ’input’, ’int’, ’intern’,
’isinstance’, ’issubclass’, ’len’, ’list’, ’locals’, ’long’, ’map’, ’max’,
’min’, ’oct’, ’open’, ’ord’, ’pow’, ’range’, ’raw_input’, ’reduce’, ’reload’,
’repr’, ’round’, ’setattr’, ’slice’, ’str’, ’tuple’, ’type’, ’vars’, ’xrange’]
>>> dir(a)
[’append’, ’count’, ’index’, ’insert’, ’remove’, ’reverse’, ’sort’]
>>> dir(x)
[]




5.16      vars
       vars(obj?)
                     obj                      obj              vars
                    (local scope dictionary [ 1])
  1:




  vars
>>> a=[2,3]
>>> x=5
>>> d=vars()
>>> print d
{’x’: 5, ’__doc__’: None, ’__name__’: ’__main__’,
’__builtins__’: <module ’__builtin__’>, ’a’: [2, 3]}
>>> e=d[’__builtins__’]
>>> print e
<module ’__builtin__’>
>>> vars(e)
{’cmp’: <built-in function cmp>, ’dir’: <built-in function dir>,
’round’: <built-in function round>,
’AttributeError’: <class exceptions.AttributeError at 1f684
[       ]

         vars            dir



5.17      locals
       locals()
5.18. globals                                       133

    locals               (local scope dictionary)



5.18   globals
    globals()
                 (global scope dictionary)
         III

Python
                                                                                                     137




      1

Python                                                  Canvas                    Python    Canvas

         eps
                                                                                             1
                            Python       Canvas
           Python           Canvas             Tcl/Tk                       Tcl/Tk       [4][5]
Python     Canvas                                                          Python Canvas
                   Python
      python/Lib/lib-tk/Canvas.py
      python/Lib/lib-tk/Tkinter.py
         Python           Canvas               UNIX      Python                                  2
                      :
      Python/Demo/tkinter/Guido/
      Python/Demo/tkinter/Matt/
                                                                                   Python




  1
  2
  3
  4
  5                        (       )
  6




1.1
  Python                   Canvas                                 Canvas
     1
  1            1999                    [8]
138                                                1


  1.1          sample.py
from Tkinter import *
from Canvas import *
import sys
def pr():
    d=c.postscript(file="a.eps")
def quit():
    sys.exit()
f=Frame()
b1=Button(f,text=’write canvas to a.eps’, command=pr)
b1.pack(side=’left’,expand=YES,fill=’x’)
b2=Button(f,text=’quit’,command=quit)
b2.pack(side=’right’,expand=YES,fill=’x’)
f.pack(fill=’x’)

# --- Canvas starts from this line ---
c=Canvas(width=400,height=300,background=’cyan’)
c.pack()

c.create_rectangle(2,2,401,301);# The maximum rectangle we can draw.

c.create_line(230,170,350,170)
c.create_rectangle(75, 30, 175,80,outline=’blue’)
c.create_rectangle(100, 50, 200,100,fill=’#F00’)
c.create_polygon(300,200,350,250,250,250,fill=’yellow’,width=2,outline=’black’)
c.create_oval(100, 200, 200,250,outline=’green’,width=20)
c.create_arc(250,30,350,80,start=90,extent=145,width=5,fill=’pink’)
c.create_text(250, 100,text=’ABC’,font=’Times 30 bold italic’,anchor=’nw’)
for n in range(0,35):
    c.create_line(30,100+5*n,70,100+5*n)
c.create_text(10,10,text=’0’,font=’Courier 12’)
c.create_line(20,10,360,10,arrow=’last’)
c.create_text(370,10,text=’x’,font=’Courier 12’)
c.create_line(10,20,10,270,arrow=’last’)
c.create_text(10,280,text=’y’,font=’Courier 12’)
c.create_line(100,150,130,180,160,150,190,180,smooth=YES,width=5,fill=’blue’,
    arrow=’last’)

mainloop()
1.1.                                                                                  139

  Python                                                                       ‘py’
                                            sample.py                            sample.py
                                                        Python

                 Python

                                                                 Windows             DOS
                           cd                   sample.py
       python sample.py




                                    1.1: sample.py

                      19
       # --- Canvas starts from this line ---


‘write canvas to a.eps’
          a.eps                 (                                          )         ‘quit’
140                                                                            1



                                  (
      [1],[2],[3]                                 )



1.2

      # --- Canvas starts from this line ---
                     Python                ‘#’


      c=Canvas(width=400,height=300,background=’cyan’)
                                  width       height
               (pixcel)
             backgroud

                                       c                                           c
      c.pack()
             c                                                                         c    pack
                      c                            (                               )
                                                         (         )
                                                              Canvas

                 Python
 Canvas           width, height, background
                                                             relief                    relief   borderwidth


      c=Canvas(width=400,height=300,background=’cyan’)

      c=Canvas(width=400,height=300,background=’cyan’,relief=’raised’, borderwidth=6)


          relief       ’raised’               ’sunken’, ’groove’, ’ridge’, ’flat’

 relief                               ’flat’                      borderwidth


      mainloop()
  Canvas
1.3.                                                                                                141




                                               1.2:
                      (relief)
                                      (       flat, raised, sunken, groove,ridge)



1.3

x                             y
                                                                        (2,2)                           1


       c.create_rectangle(2,2,401,301)


    rectangle             ( )
                             Python                    create_rectangle
                  create_rectangle                               (2,2)                       (401,301)

                                                       (0,0)
                                  2                                             ?
       c=Canvas(width=400,height=300,background=’cyan’)


       c=Canvas(width=400,height=300,background=’cyan’,highlightthickness=10)
                                                               2




       width="8c"
                          c


       width="80m", width="3.15i", width="234p"
                                  1             2.54                                1            1/72

    Python
             Python                       1             96                              Canvas    width
142                                                                             1

      print c.cget(’width’)
                                                                                      c
                                           3                640 x 480 800 x 600     1024 x 768
                      96           1                (            Windows                   )
Python                                                                   1

    Python
                                       5                                                                  5
                                                                            (                         5
                               )
                                                                                                 Python

5                 (        )       tags



1.4


         create_line
         create_rectangle                      (        )
         create_polygon
         create_oval
         create_arc
         create_text
         create_bitmap                         (2   )
         create_image                          (        )
         create_window



                                                                                                  (
             create_bitmap             create_image            create_window                              )


1.4.1     create line
    create_line                                                     2                       create_line


      c.create_line(230,170,350,170)
         (230,170)     (350,170)                                        c
1.4.                                                                                         143

         c.create_line(20,10,360,10,arrow=’last’)
          (20,10)   (360,10)
         ’none’, ’first’, ’last’, ’both’
     4                  ’none’                                arrow                        ’none’
                           arrow



                                                      none
                                                      first
                                                      last
                                                      both


                                         1.3: arrow


     create_line
         c.create_line(100,150,130,180,160,150,190,180,smooth=YES,width=5,
             fill=’blue’, arrow=’last’)
     create_line
         c.create_line(100,150,130,180,160,150,190,180)
                           4         (100,150)        (130,180)   (160,150)    (190,180)
                          width=5                                 5         fill=’blue’
                                 smooth=YES

              smooth                                                  create_line
              smooth




                                   spline curve



                               1.4: smooth


     smooth
1.
2.
144                                                            1

3.
4.              (            )        0

  smooth=YES                                     splinesteps
splinesteps

           create_line
      arrow        ’none’, ’first’, ’last’, ’both’
      capstyle     ’butt’, ’projecting’, ’round’
      fill         ’red’, ’green’, ...
      joinstyle    ’bevel’, ’miter’, ’round’
      smooth       YES, NO
      splinestep 1, 2, 3, ..
      stipple      ’gray12’, ’gray25’, ’gray50’, ’gray75’
      width        1, 2, 3, ..
      tags         ( 5      tags           )


1.4.2     create rectangle
     create_rectangle            (         )             2                2
                                                     2
       c.create_rectangle(75, 30, 175,80,outline=’blue’)
              (75,30)   (175,80)


                                       (75,30)




                                                 (175,80)

                         1.5: c.create rectangle(75,30,175,80)


     outline=’blue’
       c.create_rectangle(100, 50, 200,100,fill=’#F00’)
                                     fill                           #F00




       c.create_rectangle(100,50,200,100,fill=’black’,stipple=’gray12’)
1.4.                                                                               145

              stipple



          create_rectangle

        fill          ’red’, ’green’, ...          (                  )
        outline       ’red’, ’green’, ...          (        )
        stipple       ’gray12’, ’gray25’, ’gray50’, ’gray75’
        width         1, 2, 3, ... (        )
        tags            5     tags




1.4.3    create polygon
  create_polygon


       c.create_polygon(300,200,350,250,250,250,fill=’yellow’,width=2,
       outline=’black’)
          3             (300,200)     (350,250)        (250,250)
                  width=2

                                             (300,200)




                               (250,250)                  (350,250)

   1.6: c.create polygon(300,200,350,250,250,250,fill=’yellow’,width=2,outline=’black’)


  5                                               5

                        create_line                   smooth=YES          (   splinestep
                  )                                     smooth=YES
146                                                                1


                                               (300,200)




                               (250,250)               (350,250)

                                       1.7: smooth


         create_polygon

        fill           ’red’, ’green’, ...          (                  )
        outline        ’red’, ’green’, ...          (        )
        smooth         YES, NO
        splinestep     1, 2, 3, ..
        stipple        ’gray12’, ’gray25’, ’gray50’, ’gray75’
        width          1, 2, 3, ... (        )
        tags             5     tags




1.4.4    create oval
  create_oval                                                          create_oval
                           x               y


      c.create_oval(100, 200, 200,250,outline=’green’,width=20)


      c.create_rectangle(100,200,200,250)


                          (100,200)




                                                    (200,250)

                           1.8: c.create oval(100,200,200,250)



         create_oval                                       )
1.4.                                                                                   147

         fill      ’red’, ’green’, ...          (                         )
         outline   ’red’, ’green’, ...          (        )
         stipple   ’gray12’, ’gray25’, ’gray50’, ’gray75’
         width     1, 2, 3, ... (        )
         tags        5     tags


1.4.5     create arc
  create_arc                                  create_arc                        Oval
         Oval                2              Oval                          Arc
       c.create_arc(250,30,350,80,start=90,extent=145,width=5,fill=’pink’)


       c.create_oval(100, 200, 200,250)
                                        start   extent

                            (250,30)

                                                start



                                                        (350,80)

       1.9: c.create arc(250,30,350,80,start=90,extent=145,width=5,fill=’pink’)


                                                                          145
                                                90

                                 1.10                              1.10

                            (250,30)




                                                        (350,80)

                            1.10:
                c.create_arc(250,30,350,80,start=90,extent=145)
             c.create_arc(275,30,325,80,start=90,extent=145)
148                                                                     1

                                create_arc         start   extent



 create_arc       style




                           pieslice            chord                 arc

                                          1.11: style




         create_arc

       extent          (         )
       fill       ’red’, ’green’, ...          (                               )
       outline    ’red’, ’green’, ...          (        )
       start           (     )
       stipple    ’gray12’, ’gray25’, ’gray50’, ’gray75’
       style      ’pieslice’, ’chord’, ’arc’
       width      1, 2, 3, ... (        )
       tags         5     tags




1.4.6 create text
 create_text
      c.create_text(250, 100,text=’ABC’,font=’Times 30 bold italic’,
      anchor=’nw’)
        ABC               (250,100)         font
anchor=’nw’                              ABC     (250,100)
                            (250,100)               ABC
                                             Python                         anchor
         anchor
      ’n’, ’ne’, ’nw’, ’s’, ’se’, ’sw’, ’e’, ’w’,’center’
                                        ’center’                    ’center’         e, w, s, n
1.4.                                                                                                149

        anchor                                                                   1.12
                                eps

                                                      Windows                    MacOSX            UNIX




                                                                                anchor=’w’
                                                                  anchor=’ne’



                              1.12: anchor

       anchor=*ne’            anchor=’w’
                              eps




                                             Python                                          (’)
                 (”)      3
       s=’’’My name is Alice.
       I am waiting for your mail.
       Thank you.’’’
       c.create_text(250,100,text=s,font=’Times 12’,anchor=nw,justify=’center’)
                                                        justify                         justify
’center’         ’left’       ’right’                   justify                                ’left’
                              justify
150                                                             1



                           My name is Alice.
                           I am waiting for your mail.
                           Thank you.


                               My name is Alice.
                           I am waiting for your mail.
                                   Thank you.


                                   My name is Alice.
                           I am waiting for your mail.
                                           Thank you.

                                   1.13: justify
                                          left, center, right


         create_text

       anchor    ’nw’, ’n’, ’ne’, ’w’, ’center’, ’e’, ’sw’, ’s’, ’se’
       fill      ’red’, ’green’, ...          (           )
       font      ’Times 12’, ...
       justify   ’left’, ’right’, ’center’
       stipple   ’gray12’, ’gray25’, ’gray50’, ’gray75’
       text      ’ABC’
       width     100                  (                        0           )
       tags        5     tags




1.5                    (       )
1.5.1 font
                 1
      c.create_text(250, 100,text=’ABC’,font=’Times 30 bold italic’,anchor=’nw’)


      font=’Times 30 bold italic’
                                                                        Python
1.5.               (     )                                                   151

       font=(’Times’, 30, ’bold’, ’italic’)


  font                                                                bold
          italic                                            1         1/72



                                                                     Windows


  Times         Helvetica    Bookman     Courier   Lucida   Script   Century




                             1.14: Window95


  Windows


       Times New Roman




       font=’          ’
                                              Python
152                                                                       1

      font=’Times-New-Roman’
      font=’    -    ’




                                        Windows                                      TrueType
                       TrueType               1.14                 TT
                                                                                   Python
                                            EPS                                                 EPS
       PostScript                             PostScript
TrueType                              Windows

                                                                                  Times Helvetica
Courier


1.5.2     color
  Python
      black    darkgray     gray    lightgray      white     snow     seashell
      AntiqueWhite     bisque    PeachPuff      NavajoWhite     LemonChiffon
      cornsilk    ivory     honeydew     LavenderBlush      MistyRose      azure
      SlateBlue    RoyalBlue     blue     DodgerBlue      SteelBlue      DeepSkyBlue
      SkyBlue    LightSkyBlue     LightSteelBlue      LightBlue      LightCyan
      PaleTurquoise     CadetBlue     turquoise     cyan     SlateGray
      DarkSlateGray     aquamarine     DarkSeaGreen      SeaGreen      PaleGreen
      SpringGreengreen     chartreuse     OliveDrab      DarkOliveGreen      khaki
      LightGoldenrod     LightYellow     yellow     gold     goldenrod
      DarkGoldenrod     RosyBrown     IndianRed     sienna     burlywood      wheat
      tan    chocolate     firebrick     brown     salmon     LightSalmon
      orange    DarkOrange     coral     tomato     OrangeRed      red     DeepPink
      HotPinkpink    LightPink     PaleVioletRed      maroon      VioletRed
      magentaorchid     plum    MediumOrchid      DarkOrchid      purple
      MediumPurple     thistle

  gray              gray30                                                gray0      gray100
          gray                                     1, 2, 3, 4

           Pyhton     16          (0, 1, 2, · · · , 9, A, B, · · · , F)


      c.create_rectangle(100, 50, 200,100,fill=’#F00’)
  fill=’#F00’                F    0     0
                                        1          16                         F             0
1.5.                 (             )                                                                          153

                                                                                                        #F00
                                                                                         16
                                                                                              Python
                                                                                                       #FFA400
                         6             16
       2      16                                                     FF         A4            00            Python
                3            16                                                      #          9      16

                                                                          Python
                                                   color1.py                color2.py

  Python                      Tk                       Tk       UNIX        X                                   X
                                        [6]


1.5.3      stipple
  Python                                         stipple
       ’gray12’
       ’gray25’
       ’gray50’
       ’gray75’


       c.create_rectangle(100,50,200,100,fill=’black’,stipple=’gray12’)




                             gray12           gray25        gray50         gray75


                              1.15: stipple




1.5.4      capstyle
  capstyle                                       capstyle    create_line
       c.create_line(230,170,350,170,width=20,capstyle=’round’)
154                                                            1

      ’butt’
      ’projecting’
      ’round’




                                                  butt
                                                  projecting
                                                  round
                          1.16: capstyle


  butt    projecting                       butt                    projecting
              capstyle


1.5.5    joinstyle
  joinstyle                                   capstyle


      ’bevel’
      ’miter’
      ’round’
  3




                bevel                       miter                     round




                         1.17: joinstyle
1.5.             (    )                                                                        155

1.5.6    tags
  Python

                 Python                                    ( )

                          1        oval     1    arc             2       line
                     1




                                   1.18:

                                  (                                                    sample.py
 # --- Canvas starts from this line ---                              )
       c=Canvas(width=200,height=150,background=’cyan’)
       c.pack()
       c.create_oval(-1,1,1,0.2,tags=’drum’)
       c.create_arc(-1,-1,1,-0.2,start=180,extent=180,style=’arc’,tags=’drum’)
       c.create_line(-1,-0.6,-1,0.6,tags=’drum’)
       c.create_line(1,-0.6,1,0.6,tags=’drum’)
       c.scale(’drum’,0,0,50,-50)
       c.move(’drum’,100,75)
       mainloop()
                                        ’drum’
                                                                                1.19



                               (−1,1)                  (1,1)




                              (−1,−1)                  (1,−1)

                                    1.19:
156                                                                                         1



1.                            y
2.           (0, 0)
3.



           c.scale(’drum’,0,0,50,-50)                              --- [a]
           c.move(’drum’,100,75)                                   --- [b]
     2
     scale                                                     1             [a]            50
                        [a]                        4                               2     (50, −50)          x       y
                                                           y                                                    y
                                                       y
     [a]               2                   (0, 0)                                                  (0, 0)
                                  (0, 0)
                                                    [b]                                (100, 75)
                                                                                        y
                           [a]      [b]                1
           c.scale(’drum’,-2,1.5,50,-50)                             --- [c]
                           scale                       2             (−2, 1.5)
                                               (       1.19)

                      Python

                      (     )
                      addtag_enclosed
           c.create_oval(-1,1,1,0.2)
           c.create_arc(-1,-1,1,-0.2,start=180,extent=180,style=’arc’)
           c.create_line(-1,-0.6,-1,0.6)
           c.create_line(1,-0.6,1,0.6)
           c.addtag_enclosed(’drum’, -1.1,-1.1,1.1,1.1)


                      ’all’
’all’
1.6.                                                                                  157

1.6
 Python           background
                                           2
Ghostscript

              3




                                          Dog                 36 points


                                          36 points Letters

                      1.20:

                          (   1.12                                                )


                                     OS        Windows
   Dog



  1. ‘write to a.eps’
                                                          a.eps
  2.              a.eps       Ghostview                               Ghostview


  3. Ghostview



                                                     Canon        BJC-80v   bjc800




  2 MacOSX                             Ghostscript
  3      Windows                      MacOSX UNIX
                                                                                          159




[1] Mark Lutz                                                Python         (O’Reilly Japan,
    1998)
[2] Mark Lutz                                             Python                  (O’Reilly
    Japan, 1998)
[3] Mark Lutz “Programming Python” (O’Reilly & Associates,Inc. 1996)
[4] John K.Ousterhout      /                       Tcl&Tk                   (
    1995)
[5]                            Tcl/Tk                 (             1995)
[6] V.Quercia,T.O’Reily/                X                                             (
               1993)
[7]             Ghostscript Another Manual (                1997)
[8]            Python                          ( Com Vol.10,No.2
             1999 9        )
                                                              161




      A


A.1


      x+y, x-y
      x*y, x/y, x%y
      -x,+x
      x|y, xˆy, x&y                         OR, XOR,AND
      x<<n, x>>n
       x
      abs(x)
      int(x)           x
      long(x)
      float(x)
      round(x)             x            (                 )
      round(x,n)           x            n
      divmod(x,y)      (x/y, x%y)
      x**y, pow(x,y)                (                )
      pow(x,y,z)       pow(x,y)%z
      coerce(x,y)              (            + )


                            A.1:
162                                                                       A

A.2




 chr(i)                                           i             (1.3)
 ord(c)                             c                 (1.3)
 max(s)                                      s
 max(x1 ,x2 ,...)            x1 , x2 , ...
 min(s)                                      s
 min(x1 ,x2 ,...)            x1 , x2 , ...
 str(x)                                           x
 repr(x)                     x                        ‘x‘
 oct(x)                      x      8
 hex(x)                      x      16
 range(n?,m,i?)                                           (3.6)
 xrange(n,m,i)               range                                        (3.6)
 tuple(s)                                    s
 list(s)                                     s
 cmp(x,y)                    x<y, x==y, x>y                       -1, 0, 1         (1.5)
 input(prompt?)                                                            (5.1)
 raw input(prompt?)                                                        (5.2)
 open(name,mode?,bufsize?)                            (4.2)
 filter(func,s)                              s                     func
                             (5.4)
 map(func,s)                                 s                     func
                                        (5.5)
 reduce(func,s,init)         2               func                             s        (5.6)
 apply(func,t,d)                    func
                                              (5.7)


                             A.2:                 (               )

      ?
      ()                                  (1.3)       1     3
A.2.                                                                                                  163



 eval(code)                                       (5.8)
 exec(code)                                       (5.9)
 compile(code,label ,kind)   Python
                             (5.11)
 execfile(file)               Python                                          (5.10)
 id(obj)                                          obj           ID           (5.12)
 type(obj)                                        obj                              (5.13)
 hash(obj)                                        obj                                   (5.14)
 callable(obj)                                    obj                                            (5.15)
 dir(obj?)                   obj                                                                 (5.16)
 vars(obj?)                  obj                                                                 (5.17)
 locals()                    locals                                                          (5.18)
 globals()                                                                          (5.19)
 getattr(obj,name)                                  (3.8)
 hasattr(obj,name)                                                                (3.8)
 setattr(obj,name,value)                                        (3.8)
 delattr(obj,name)                                  (3.8)
 reload(module)                                                          (   1)


                                   A.3:                     (        )

       ?
       ()                                 (5.8)         5        8

            1: reload                                                             [1]
                                                    165




           B

Python
                        1

http://docs.python.org/lib/modindex.html
               2



B.1      math
  math

      import math



      from math import *

                                           3   10   math
                cmath




  1
166                                                                                                  B


 Python
 pi           π                                                    (3.1415 · · ·)
 e            e                                                        (2.71828 · · ·)
 acos(x)      arccos(x)                                                    ( 0              +π                    )
                                                      cos(y)                           y
 asin(x)      arcsin(x)                                                    ( −π/2                   +π/2                    )
                                                      sin(y)           x               y
 atan(x)      arctan(x)                                                    ( −π/2                   +π/2                    )
                                                      tan(y)           x            y
                                                                                  (1, x)                       (1, 0)
 atan2(x,y)   arctan(y/x)                                                ( −π               +π                    )
                                                      tan(z)           y/x             z
                                                                                  (x, y)                       (1, 0)
 ceil(x)                                              x
                                                           :   ceil(2.3)                   3.0 ceil(2)                2.0
 cos(x)       cos(x)                                                   (                                   )
                                                                                            −x
 cosh(x)      cosh(x)                                                            (e + e )/2
                                                                                   x

 exp(x)       e   x
                                    exp(x)
 fabs(x)      |x|
 floor(x)     [x]                                     x
              (Gauss                  )                    :floor(2.3)                 2.0 floor(2)                   2.0
 fmod(x,y)                                            x-int(x/y)*y
                                                              x>0                      x%y
                                                      x<0                        fmod(x,y)
 frexp(x)                                             a × 2n           x                          (a, n)
                                                                   n                             0≤a<1
 hypot(x,y)           x2   +   y2                     sqrt(x*x + y*y)
 ldexp(x,y)                                           x*2.0**int(y)
 log(x)       loge (x)                 ln(x)
                                                      ey       x                            y
 log10(x)     log(x)                      log10 (x)   10
                                                      10y          x                            y
 modf(x)                                              x
                                                        : modf(3.14)    (0.14, 3)
                                                      modf(-3.14)  (−0.14, −3)
 pow(x,y)     xy                                      x**y                 x      y
 sin(x)       sin(x)                                                   (                                   )
                                                                                            −x
 sinh(x)      sinh(x)                                                            (e − e )/2
                                                                                   x
              √
 sqrt(x)         x                                    x
 tan(x)       tan(x)                                                   (                                   )
 tanh(x)      tanh(x)                                                            sinh(x)/ cosh(x)

                                             B.1:
B.2. string                                                                                 167

B.2        string
  string

      import string



      from string import *

                                                       3       10

               s

   Python
   atof(s)                   s
                             (float(s)                     )
   atoi(s,base?)             s
                             (int(s,base?)                           )
   expandtabs(s,tabsize)     s
   find(s,sub,start?)        s                         sub
   rfind(s,sub,start?)       s                         sub


   index(s,sub,start?)       s                         sub
   rindex(s,sub,start?)      s                         sub


   replace(s,old,new,max?)   s                         old          new
                                         ( max                                          )
   count(s,sub, start?)      s                         sub
   split(s)                                            s
   splitfields(s,sep)        sep                                          s


   join(x, sep?)                                                              x
                                                 sep                              sep
                                         sep                              1


   joinfields(x,sep?)        join
   strip(s)


   maketrans(from,to)        translate
168                                                                     B



      translate(s,table,delete?)               s
                                              (                             delete
                                                         )
      swapcase(s)                   s


      upper(s)                      s
      lower(s)                      s
      ljust(s,width)                         width                  s


      rjust(s,width)                         width                  s


      center(s,width)                        width                  s


      zfill(s,width)                         width
                                                     0

                                          B.2:




             s                       ?

    atoi(s,base?)
               base                     10                                 atoi("100")
100          atoi atol                              10                         16
                                             atoi("100",16)    16       "100"
             256
 find   rfind index rindex                      start?
       0                                     find, rfind                             −1
       index, rindex
 translate                                         maketrans
      t=maketrans("abc", "xyz")
            ’a’     ’x’       ’b’   ’y’       ’c’     ’z’                    t


      print translate("alice",t,"le")


      xiz
                  translate
                                                                   169




            C         colors1.py

                       Python

http://ar.aichi-u.ac.jp/netlib/Python/samples/
--------------------------- colors1.py -------------------------
#
# colors
# coded by Kenar
# REF: Tcl/lib/tk8.0/demos/colors.tcl
#
from Canvas import *
import sys, string
from Tkinter import *
colors=’’’
black darkgray gray lightgray
white snow seashell AntiqueWhite bisque
PeachPuff NavajoWhite LemonChiffon cornsilk
ivory honeydew LavenderBlush MistyRose azure
SlateBlue RoyalBlue blue DodgerBlue SteelBlue
DeepSkyBlue SkyBlue LightSkyBlue LightSteelBlue
LightBlue LightCyan PaleTurquoise CadetBlue
turquoise cyan SlateGray DarkSlateGray aquamarine
DarkSeaGreen SeaGreen PaleGreen SpringGreen
green chartreuse OliveDrab DarkOliveGreen
khaki LightGoldenrod LightYellow yellow
gold goldenrod DarkGoldenrod RosyBrown
IndianRed sienna burlywood wheat tan
chocolate firebrick brown salmon LightSalmon
orange DarkOrange coral tomato
OrangeRed red DeepPink HotPink pink LightPink
PaleVioletRed maroon VioletRed magenta
orchid plum MediumOrchid DarkOrchid
purple MediumPurple thistle
’’’

colorlist=string.split(colors)
numcolor=len(colorlist)

def pr(event):
global t
n,m=event.x/20,event.y/20
num=16*m+n
if num >= numcolor: return
t.delete()
color=colorlist[num]
170                                                            C   colors1.py

red,green,blue=c.winfo_rgb(color)
red=red/256
green=green/256
blue=blue/256
t=c.create_text(150,120,
text="%s      #%02X%02X%02X"%(color,red,green,blue),
anchor="w")

c=Canvas(width=320,height=140,background=’white’)
c.pack()
c.bind("<Button-1>",pr)

n,m=0,0
for color in colorlist:
c.create_rectangle(20*n, 20*m, 20*n+20, 20*m+20, fill=color)
n=n+1
if n == 16: n=0; m=m+1
t=c.create_text(150,420,text="")
c.mainloop()
--------------------------------------------------------
                                                                    171




            D         colors2.py

                       Python

http://ar.aichi-u.ac.jp/netlib/Python/samples/
------------------------- colors2.py ---------------------
#
# colors
# coded by Kenar
# REF: Tcl/lib/tk8.0/demos/colors.tcl
#
from Canvas import *
import sys, string
from Tkinter import *
colors=’’’
    gray60 gray70 gray80 gray85 gray90 gray95
    snow1 snow2 snow3 snow4 seashell1 seashell2
    seashell3 seashell4 AntiqueWhite1 AntiqueWhite2 AntiqueWhite3
    AntiqueWhite4 bisque1 bisque2 bisque3 bisque4 PeachPuff1
    PeachPuff2 PeachPuff3 PeachPuff4 NavajoWhite1 NavajoWhite2
    NavajoWhite3 NavajoWhite4 LemonChiffon1 LemonChiffon2
    LemonChiffon3 LemonChiffon4 cornsilk1 cornsilk2 cornsilk3
    cornsilk4 ivory1 ivory2 ivory3 ivory4 honeydew1 honeydew2
    honeydew3 honeydew4 LavenderBlush1 LavenderBlush2
    LavenderBlush3 LavenderBlush4 MistyRose1 MistyRose2
    MistyRose3 MistyRose4 azure1 azure2 azure3 azure4
    SlateBlue1 SlateBlue2 SlateBlue3 SlateBlue4 RoyalBlue1
    RoyalBlue2 RoyalBlue3 RoyalBlue4 blue1 blue2 blue3 blue4
    DodgerBlue1 DodgerBlue2 DodgerBlue3 DodgerBlue4 SteelBlue1
    SteelBlue2 SteelBlue3 SteelBlue4 DeepSkyBlue1 DeepSkyBlue2
    DeepSkyBlue3 DeepSkyBlue4 SkyBlue1 SkyBlue2 SkyBlue3
    SkyBlue4 LightSkyBlue1 LightSkyBlue2 LightSkyBlue3
    LightSkyBlue4 SlateGray1 SlateGray2 SlateGray3 SlateGray4
    LightSteelBlue1 LightSteelBlue2 LightSteelBlue3
    LightSteelBlue4 LightBlue1 LightBlue2 LightBlue3
    LightBlue4 LightCyan1 LightCyan2 LightCyan3 LightCyan4
    PaleTurquoise1 PaleTurquoise2 PaleTurquoise3 PaleTurquoise4
    CadetBlue1 CadetBlue2 CadetBlue3 CadetBlue4 turquoise1
    turquoise2 turquoise3 turquoise4 cyan1 cyan2 cyan3 cyan4
    DarkSlateGray1 DarkSlateGray2 DarkSlateGray3
    DarkSlateGray4 aquamarine1 aquamarine2 aquamarine3
    aquamarine4 DarkSeaGreen1 DarkSeaGreen2 DarkSeaGreen3
    DarkSeaGreen4 SeaGreen1 SeaGreen2 SeaGreen3 SeaGreen4
    PaleGreen1 PaleGreen2 PaleGreen3 PaleGreen4 SpringGreen1
    SpringGreen2 SpringGreen3 SpringGreen4 green1 green2
    green3 green4 chartreuse1 chartreuse2 chartreuse3
172                                                                 D   colors2.py

      chartreuse4 OliveDrab1 OliveDrab2 OliveDrab3 OliveDrab4
      DarkOliveGreen1 DarkOliveGreen2 DarkOliveGreen3
      DarkOliveGreen4 khaki1 khaki2 khaki3 khaki4
      LightGoldenrod1 LightGoldenrod2 LightGoldenrod3
      LightGoldenrod4 LightYellow1 LightYellow2 LightYellow3
      LightYellow4 yellow1 yellow2 yellow3 yellow4 gold1 gold2
      gold3 gold4 goldenrod1 goldenrod2 goldenrod3 goldenrod4
      DarkGoldenrod1 DarkGoldenrod2 DarkGoldenrod3 DarkGoldenrod4
      RosyBrown1 RosyBrown2 RosyBrown3 RosyBrown4 IndianRed1
      IndianRed2 IndianRed3 IndianRed4 sienna1 sienna2 sienna3
      sienna4 burlywood1 burlywood2 burlywood3 burlywood4 wheat1
      wheat2 wheat3 wheat4 tan1 tan2 tan3 tan4 chocolate1
      chocolate2 chocolate3 chocolate4 firebrick1 firebrick2
      firebrick3 firebrick4 brown1 brown2 brown3 brown4 salmon1
      salmon2 salmon3 salmon4 LightSalmon1 LightSalmon2
      LightSalmon3 LightSalmon4 orange1 orange2 orange3 orange4
      DarkOrange1 DarkOrange2 DarkOrange3 DarkOrange4 coral1
      coral2 coral3 coral4 tomato1 tomato2 tomato3 tomato4
      OrangeRed1 OrangeRed2 OrangeRed3 OrangeRed4 red1 red2 red3
      red4 DeepPink1 DeepPink2 DeepPink3 DeepPink4 HotPink1
      HotPink2 HotPink3 HotPink4 pink1 pink2 pink3 pink4
      LightPink1 LightPink2 LightPink3 LightPink4 PaleVioletRed1
      PaleVioletRed2 PaleVioletRed3 PaleVioletRed4 maroon1
      maroon2 maroon3 maroon4 VioletRed1 VioletRed2 VioletRed3
      VioletRed4 magenta1 magenta2 magenta3 magenta4 orchid1
      orchid2 orchid3 orchid4 plum1 plum2 plum3 plum4
      MediumOrchid1 MediumOrchid2 MediumOrchid3 MediumOrchid4
      DarkOrchid1 DarkOrchid2 DarkOrchid3 DarkOrchid4 purple1
      purple2 purple3 purple4 MediumPurple1 MediumPurple2
      MediumPurple3 MediumPurple4 thistle1 thistle2 thistle3
      thistle4
’’’

colorlist=string.split(colors)
numcolor=len(colorlist)

def pr(event):
global t
n,m=event.x/20,event.y/20
num=16*m+n
if num >= numcolor: return
t.delete()
color=colorlist[num]
red,green,blue=c.winfo_rgb(color)
red=red/256
green=green/256
blue=blue/256
t=c.create_text(150,420,
text="%s      #%02X%02X%02X"%(color,red,green,blue))

c=Canvas(width=320,height=440,background=’white’)
c.pack()
c.bind("<Button-1>",pr)
                                                                  173

n,m=0,0
for color in colorlist:
c.create_rectangle(20*n, 20*m, 20*n+20, 20*m+20, fill=color)
n=n+1
if n == 16: n=0; m=m+1
t=c.create_text(150,420,text="")
c.mainloop()
---------------------------------------------------------------

                                         Tk

								
To top