aboutsummaryrefslogtreecommitdiff
path: root/shar/python-0.9.1-01-21.shar
blob: 75c124ec467b2d478f1327a49659131a2a1d36c0 (plain)
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
: This is a shell archive.
: Extract with 'sh this_file'.
: Extract this part first since it makes all directories
echo 'Start of pack.out, part 01 out of 21:'
echo -n 'Making directories ... '
err="no"
test -d 'demo' || mkdir 'demo' || err="yes"
test -d 'demo/scripts' || mkdir 'demo/scripts' || err="yes"
test -d 'demo/sgi' || mkdir 'demo/sgi' || err="yes"
test -d 'demo/sgi/audio' || mkdir 'demo/sgi/audio' || err="yes"
test -d 'demo/sgi/audio_stdwin' || mkdir 'demo/sgi/audio_stdwin' || err="yes"
test -d 'demo/sgi/gl' || mkdir 'demo/sgi/gl' || err="yes"
test -d 'demo/sgi/gl_panel' || mkdir 'demo/sgi/gl_panel' || err="yes"
test -d 'demo/sgi/gl_panel/apanel' || mkdir 'demo/sgi/gl_panel/apanel' || err="yes"
test -d 'demo/sgi/gl_panel/flying' || mkdir 'demo/sgi/gl_panel/flying' || err="yes"
test -d 'demo/sgi/gl_panel/nurbs' || mkdir 'demo/sgi/gl_panel/nurbs' || err="yes"
test -d 'demo/sgi/gl_panel/twoview' || mkdir 'demo/sgi/gl_panel/twoview' || err="yes"
test -d 'demo/stdwin' || mkdir 'demo/stdwin' || err="yes"
test -d 'doc' || mkdir 'doc' || err="yes"
test -d 'lib' || mkdir 'lib' || err="yes"
test -d 'src' || mkdir 'src' || err="yes"
echo 'done'
if test "$err" = "yes"
then echo "didn't make it."
fi
if test -s 'README'
then echo '*** I will not over-write existing file README'
else
echo 'x - README'
sed 's/^X//' > 'README' << 'EOF'
XThis is Python, an extensible interpreted programming language that
Xcombines remarkable power with very clear syntax.
X
XThis is version 0.9 (the first beta release), patchlevel 1.
X
XPython can be used instead of shell, Awk or Perl scripts, to write
Xprototypes of real applications, or as an extension language of large
Xsystems, you name it. There are built-in modules that interface to
Xthe operating system and to various window systems: X11, the Mac
Xwindow system (you need STDWIN for these two), and Silicon Graphics'
XGL library. It runs on most modern versions of UNIX, on the Mac, and
XI wouldn't be surprised if it ran on MS-DOS unchanged. I developed it
Xmostly on an SGI IRIS workstation (using IRIX 3.1 and 3.2) and on the
XMac, but have tested it also on SunOS (4.1) and BSD 4.3 (tahoe).
X
XBuilding and installing Python is easy (but do read the Makefile).
XA UNIX style manual page and extensive documentation (in LaTeX format)
Xare provided. (In the beta release, the documentation is still under
Xdevelopment.)
X
XPlease try it out and send me your comments (on anything -- the
Xlanguage design, implementation, portability, installation,
Xdocumentation) and the modules you wrote for it, to make the first
Xreal release better. If you needed to hack the source to get it to
Xcompile and run on a particular machine, send me the fixes -- I'll try
Xto incorporate them into the next patch. If you can't get it to work
Xat all, send me a *detailed* description of the problem and I may look
Xinto it.
X
XIf you want to profit of the X11 or Mac window interface, you'll need
XSTDWIN. This is a portable window system interface by the same
Xauthor. The versions of STDWIN floating around on some archives are
Xnot sufficiently up-to-date for use with Python. I will distribute
Xthe latest and greatest STDWIN version at about the same time as Python.
X
XI am the author of Python:
X
X Guido van Rossum
X CWI, dept. CST
X Kruislaan 413
X 1098 SJ Amsterdam
X The Netherlands
X
X E-mail: [email protected]
X
XThe Python source is copyrighted, but you can freely use and copy it
Xas long as you don't change or remove the copyright:
X
X/***********************************************************
XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The
XNetherlands.
X
X All Rights Reserved
X
XPermission to use, copy, modify, and distribute this software and its
Xdocumentation for any purpose and without fee is hereby granted,
Xprovided that the above copyright notice appear in all copies and that
Xboth that copyright notice and this permission notice appear in
Xsupporting documentation, and that the names of Stichting Mathematisch
XCentrum or CWI not be used in advertising or publicity pertaining to
Xdistribution of the software without specific, written prior permission.
X
XSTICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
XTHIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
XFITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
XFOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
XWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
XACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
XOF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
X
X******************************************************************/
EOF
fi
if test -s 'python.man'
then echo '*** I will not over-write existing file python.man'
else
echo 'x - python.man'
sed 's/^X//' > 'python.man' << 'EOF'
X.TH PYTHON "19 February 1991"
X.SH NAME
Xpython \(en an extensible interpreted programming language
X.SH SYNOPSIS
X.B python
X[
X.I X11-options
X] [
X.I script
X[
X.I arguments
X] ]
X.SH DESCRIPTION
XPython is an extensible interpreted programming language that
Xcombines remarkable power with very clear syntax.
XFor an introduction to programming in Python you are referred to the
XPython Tutorial.
X.PP
XThe interpreter operates somewhat like the UNIX shell: when called with
Xstandard input connected to a tty device, it reads and executes commands
Xinteractively until an EOF is read;
Xwhen called with a file name argument or with a file as standard
Xinput, it reads and executes a
X.I script
Xfrom that file.
XIf available, the script name and additional arguments thereafter are
Xpassed to the script in the variable
X.I sys.argv ,
Xwhich is a list of strings.
XIn interactive mode, the primary prompt is `>>>'; the second prompt
X(which appears when a command is not complete) is `...'.
X.SH FILES AND DIRECTORIES
X.IP /usr/local/lib/python
XThis might be the directory containing the library of standard modules.
X(Installation-dependent.)
X.SH ENVIRONMENT VARIABLES
X.IP PYTHONPATH
XSets the search path for module files.
XThe format is the same as the shell's $PATH: one or more directory
Xpathnames separated by colons.
XNon-existant directories are silently ignored.
XThe default search path is installation dependent, but always begins
Xwith `.', (for example,
X.I .:/usr/local/lib/python ).
X.SH SEE ALSO
XPython Tutorial
X.br
XPython Library Reference
X.SH AUTHOR
X.nf
XGuido van Rossum
XCWI, dept. CST
XKruislaan 413
X1098 SJ Amsterdam
XThe Netherlands
X.PP
XE-mail: [email protected]
X.fi
X.SH COPYRIGHT
XCopyright 1991 by Stichting Mathematisch Centrum, Amsterdam, The
XNetherlands.
X.IP " "
XAll Rights Reserved
X.PP
XPermission to use, copy, modify, and distribute this software and its
Xdocumentation for any purpose and without fee is hereby granted,
Xprovided that the above copyright notice appear in all copies and that
Xboth that copyright notice and this permission notice appear in
Xsupporting documentation, and that the names of Stichting Mathematisch
XCentrum or CWI not be used in advertising or publicity pertaining to
Xdistribution of the software without specific, written prior permission.
X
XSTICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
XTHIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
XFITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
XFOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
XWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
XACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
XOF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
EOF
fi
if test -s 'demo/sgi/gl_panel/nurbs/nurbs.py'
then echo '*** I will not over-write existing file demo/sgi/gl_panel/nurbs/nurbs.py'
else
echo 'x - demo/sgi/gl_panel/nurbs/nurbs.py'
sed 's/^X//' > 'demo/sgi/gl_panel/nurbs/nurbs.py' << 'EOF'
X#! /ufs/guido/bin/sgi/python
X
X# Fancy NURBS demo. Require Z buffer and Panel Library.
X
Xfrom gl import *
Xfrom GL import *
Xfrom DEVICE import *
Xfrom nurbsdata import *
Ximport panel
X
X#
X# flags = trim_f, invis_f, cpvis_f, tpvis_f, axvis_f, freeze_f
X#
XTRIM = 0
XVIS = 1
XCPVIS = 2
XTPVIS = 3
XAXVIS = 4
XFREEZE = 5
Xflags = [0, 1, 0, 0, 0, 0]
X
Xdef draw_axis () :
X cpack (0x0)
X zero = (0.0, 0.0, 0.0)
X #
X one = (1.0, 0.0, 0.0)
X smallline (zero, one)
X cmov (1.0, 0.0, 0.0)
X charstr ('x')
X #
X one = (0.0, 1.0, 0.0)
X smallline (zero, one)
X cmov (0.0, 1.0, 0.0)
X charstr ('y')
X #
X one = (0.0, 0.0, 1.0)
X smallline (zero, one)
X cmov (0.0, 0.0, 1.0)
X charstr ('z')
X
XDELTA = 0.1
X
Xdef cross (p) :
X p0 = [p[0], p[1], p[2]]
X p1 = [p[0], p[1], p[2]]
X for i in range (0, 3) :
X p0[i] = p0[i] + DELTA
X p1[i] = p1[i] - DELTA
X smallline (p0, p1)
X p0[i] = p0[i] - DELTA
X p1[i] = p1[i] + DELTA
X
Xdef smallline (p0, p1) :
X bgnline ()
X v3f (p0)
X v3f (p1)
X endline ()
X
Xdef draw_pts (pnts, color) :
X linewidth (2)
X cpack (color)
X for i in pnts :
X cross (i)
X
Xdef init_windows():
X foreground()
X wid = winopen('nurbs')
X wintitle('NURBS Surface')
X doublebuffer()
X RGBmode()
X gconfig()
X lsetdepth(0x000, 0x7fffff)
X zbuffer( TRUE )
X
Xdef init_view():
X mmode(MPROJECTION)
X ortho( -5., 5., -5., 5., -5., 5. )
X #
X mmode(MVIEWING)
X loadmatrix(idmat)
X #
X lmbind(MATERIAL, 1)
X
Xdef set_scene(flags):
X #
X lmbind(MATERIAL, 0)
X RGBcolor(150,150,150)
X lmbind(MATERIAL, 1)
X clear()
X zclear()
X #
X if not flags[FREEZE] :
X rotate( 100, 'y' )
X rotate( 100, 'z' )
X
Xdef draw_trim_surface(flags):
X pnts = ctlpoints
X if flags[VIS] :
X bgnsurface()
X nurbssurface(surfknots,surfknots,pnts,ORDER,ORDER,N_XYZ)
X if flags[TRIM]:
X bgntrim()
X nurbscurve(trimknots,trimpoints,ORDER-1,N_STW)
X endtrim()
X endsurface()
X #
X if flags[CPVIS] :
X for i in pnts :
X draw_pts (i, RED)
X #
X if flags[TPVIS] :
X tpts = trimpoints
X draw_pts (tpts, YELLOW)
X #
X if flags[AXVIS] :
X draw_axis ()
X #
X swapbuffers()
X
Xdef make_lights():
X lmdef(DEFLMODEL,1,[])
X lmdef(DEFLIGHT,1,[])
X #
X # define material #1
X #
X a = []
X a = a + [EMISSION, 0.0, 0.0, 0.0]
X a = a + [AMBIENT, 0.1, 0.1, 0.1]
X a = a + [DIFFUSE, 0.6, 0.3, 0.3]
X a = a + [SPECULAR, 0.0, 0.6, 0.0]
X a = a + [SHININESS, 2.0]
X a = a + [LMNULL]
X lmdef(DEFMATERIAL, 1, a)
X #
X # turn on lighting
X #
X lmbind(LIGHT0, 1)
X lmbind(LMODEL, 1)
X
Xdef main():
X init_windows()
X make_lights()
X init_view()
X #
X panel.needredraw()
X panels = panel.defpanellist('nurbs.s')
X p = panels[0]
X #
X def cbtrim (a) :
X flags[TRIM:TRIM+1] = [int (a.val)]
X p.trim.upfunc = cbtrim
X #
X def cbquit (a) :
X import sys
X sys.exit (1)
X p.quit.upfunc = cbquit
X #
X def cbmotion (a) :
X flags[FREEZE:FREEZE+1] = [int (a.val)]
X p.motion.upfunc = cbmotion
X #
X def cbxyzaxis (a) :
X flags[AXVIS:AXVIS+1] = [int (a.val)]
X p.xyzaxis.upfunc = cbxyzaxis
X #
X def cbtrimpnts (a) :
X flags[TPVIS:TPVIS+1] = [int (a.val)]
X p.trimpnts.upfunc = cbtrimpnts
X #
X def cbcntlpnts (a) :
X flags[CPVIS:CPVIS+1] = [int (a.val)]
X p.cntlpnts.upfunc = cbcntlpnts
X #
X def cbnurb (a) :
X flags[VIS:VIS+1] = [int (a.val)]
X p.nurb.upfunc = cbnurb
X #
X set_scene(flags)
X setnurbsproperty( N_ERRORCHECKING, 1.0 )
X setnurbsproperty( N_PIXEL_TOLERANCE, 50.0 )
X draw_trim_surface(flags)
X #
X while 1:
X act = panel.dopanel()
X #
X wid = panel.userredraw ()
X if wid :
X winset (wid)
X reshapeviewport()
X set_scene(flags)
X draw_trim_surface(flags)
X #
X set_scene(flags)
X draw_trim_surface(flags)
X
Xmain()
EOF
chmod +x 'demo/sgi/gl_panel/nurbs/nurbs.py'
fi
if test -s 'doc/tut.tex'
then echo '*** I will not over-write existing file doc/tut.tex'
else
echo 'x - doc/tut.tex'
sed 's/^X//' > 'doc/tut.tex' << 'EOF'
X% Format this file with latex.
X
X%\documentstyle[garamond,11pt,myformat]{article}
X\documentstyle[11pt,myformat]{article}
X
X\title{\bf
X Python Tutorial \\
X (DRAFT)
X}
X
X\author{
X Guido van Rossum \\
X Dept. CST, CWI, Kruislaan 413 \\
X 1098 SJ Amsterdam, The Netherlands \\
X E-mail: {\tt [email protected]}
X}
X
X\begin{document}
X
X\pagenumbering{roman}
X
X\maketitle
X
X\begin{abstract}
X
X\noindent
X\Python\ is a simple, yet powerful programming language that bridges the
Xgap between C and shell programming, and is thus ideally suited for rapid
Xprototyping.
XIts syntax is put together from constructs borrowed from a variety of other
Xlanguages; most prominent are influences from ABC, C, Modula-3 and Icon.
X
XThe \Python\ interpreter is easily extended with new functions and data
Xtypes implemented in C.
X\Python\ is also suitable as an extension language for highly
Xcustomizable C applications such as editors or window managers.
X
X\Python\ is available for various operating systems, amongst which
Xseveral flavors of \UNIX, Amoeba, and the Apple Macintosh O.S.
X
XThis tutorial introduces the reader informally to the basic concepts and
Xfeatures of the \Python\ language and system.
XIt helps to have a \Python\ interpreter handy for hands-on experience,
Xbut as the examples are self-contained, the tutorial can be read
Xoff-line as well.
X
XFor a description of standard objects and modules, see the Library
XReference document.
XThe Language Reference document (XXX not yet existing)
Xgives a more formal reference to the language.
X
X\end{abstract}
X
X\pagebreak
X
X\tableofcontents
X
X\pagebreak
X
X\pagenumbering{arabic}
X
X\section{Whetting Your Appetite}
X
XIf you ever wrote a large shell script, you probably know this feeling:
Xyou'd love to add yet another feature, but it's already so slow, and so
Xbig, and so complicated; or the feature involves a system call or other
Xfuncion that is only accessible from C \ldots
XUsually the problem at hand isn't serious enough to warrant rewriting
Xthe script in C; perhaps because the problem requires variable-length
Xstrings or other data types (like sorted lists of file names) that
Xare easy in the shell but lots of work to implement in C; or perhaps
Xjust because you're not sufficiently familiar with C.
X
XIn all such cases, \Python\ is just the language for you.
X\Python\ is simple to use, but it is a real programming language, offering
Xmuch more structure and support for large programs than the shell has.
XOn the other hand, it also offers much more error checking than C, and,
Xbeing a
X{\em very-high-level language},
Xit has high-level data types built in, such as flexible arrays and
Xdictionaries that would cost you days to implement efficiently in C.
XBecause of its more general data types \Python\ is applicable to a
Xmuch larger problem domain than
X{\em Awk}
Xor even
X{\em Perl},
Xyet most simple things are at least as easy in \Python\ as in those
Xlanguages.
X
X\Python\ allows you to split up your program in modules that can be reused
Xin other \Python\ programs.
XIt comes with a large collection of standard modules that you can use as
Xthe basis for your programs --- or as examples to start learning to
Xprogram in \Python.
XThere are also built-in modules that provide things like file I/O,
Xsystem calls, and even a generic interface to window systems (STDWIN).
X
X\Python\ is an interpreted language, which saves you considerable time
Xduring program development because no compilation and linking is
Xnecessary.
XThe interpreter can be used interactively, which makes it easy to
Xexperiment with features of the language, to write throw-away programs,
Xor to test functions during bottom-up program development.
XIt is also a handy desk calculator.
X
X\Python\ allows writing very compact and readable programs.
XPrograms written in \Python\ are typically much shorter than equivalent C
Xprograms:
XNo declarations are necessary (all type checking is
Xdynamic); statement grouping is done by indentation instead of begin/end
Xbrackets; and the high-level data types allow you to express complex
Xoperations in a single statement.
X
X\Python\ is
X{\em extensible}:
Xif you know how to program in C it is easy to add a new built-in module
Xto the interpreter, either to perform critical operations at maximum
Xspeed, or to link \Python\ programs to libraries that may be only available
Xin binary form (such as a vendor-specific graphics library).
XOnce you are really hooked, you can link the \Python\ interpreter into an
Xapplication written in C and use it as an extension or command language.
X
X\subsection{Where From Here}
X
XNow that you are all excited about \Python, you'll want to examine it in
Xsome more detail.
XSince the best introduction to a language is using it, you are invited
Xhere to do so.
X
XIn the next section, the mechanics of using the interpreter are
Xexplained.
XThis is rather mundane information, but essential for trying out the
Xexamples shown later.
XThe rest of the tutorial introduces various features of the \Python\
Xlanguage and system though examples, beginning with simple expressions,
Xstatements and data types, through functions and modules, and finally
Xtouching upon advanced concepts like exceptions and classes.
X
X\section{Using the Python Interpreter}
X
XThe \Python\ interpreter is usually installed as
X{\tt /usr/local/python}
Xon those machines where it is available; putting
X{\tt /usr/local}
Xin your \UNIX\ shell's search path makes it possible to start it by
Xtyping the command
X\bcode\begin{verbatim}
Xpython
X\end{verbatim}\ecode
Xto the shell.
XSince the choice of the directory where the interpreter lives is an
Xinstallation option, other places instead of
X{\tt /usr/local}
Xare possible; check with your local \Python\ guru or system
Xadministrator.%
X\footnote{
X At CWI, at the time of writing, the interpreter can be found in
X the following places:
X On the Amoeba Ultrix machines, use the standard path,
X {\tt /usr/local/python}.
X On the Sun file servers, use
X {\tt /ufs/guido/bin/}{\em arch}{\tt /python},
X where {\em arch} can be {\tt sgi} or {\tt sun4}.
X On piring, use {\tt /userfs3/amoeba/bin/python}.
X (If you can't find a binary advertised here, get in touch with me.)
X}
X
XThe interpreter operates somewhat like the \UNIX\ shell: when called with
Xstandard input connected to a tty device, it reads and executes commands
Xinteractively; when called with a file name argument or with a file as
Xstandard input, it reads and executes a
X{\em script}
Xfrom that file.%
X\footnote{
X There is a difference between ``{\tt python file}'' and
X ``{\tt python $<$file}''. In the latter case {\tt input()} and
X {\tt raw\_input()} are satisfied from {\em file}, which has
X already been read until the end by the parser, so they will read
X EOF immediately. In the former case (which is usually what
X you want) they are satisfied from whatever file or device is
X connected to standard input of the \Python\ interpreter.
X}
XIf available, the script name and additional arguments thereafter are
Xpassed to the script in the variable
X{\tt sys.argv},
Xwhich is a list of strings.
X
XWhen standard input is a tty, the interpreter is said to be in
X{\em interactive\ mode}.
XIn this mode it prompts for the next command with the
X{\em primary\ prompt},
Xusually three greater-than signs ({\tt >>>}); for continuation lines
Xit prompts with the
X{\em secondary\ prompt},
Xby default three dots ({\tt ...}).
XTyping an EOF (Control-D) at the primary prompt causes the interpreter
Xto exit with a zero exit status.
X
XWhen an error occurs in interactive mode, the interpreter prints a
Xmessage and a stack trace and returns to the primary prompt; with input
Xfrom a file, it exits with a nonzero exit status.
X(Exceptions handled by an
X{\tt except}
Xclause in a
X{\tt try}
Xstatement are not errors in this context.)
XSome errors are unconditionally fatal and cause an exit with a nonzero
Xexit; this applies to internal inconsistencies and some cases of running
Xout of memory.
XAll error messages are written to the standard error stream; normal
Xoutput from the executed commands is written to standard output.
X
XTyping an interrupt (normally Control-C or DEL) to the primary or
Xsecondary prompt cancels the input and returns to the primary prompt.
XTyping an interrupt while a command is being executed raises the
X{\tt KeyboardInterrupt}
Xexception, which may be handled by a
X{\tt try}
Xstatement.
X
XWhen a module named
X{\tt foo}
Xis imported, the interpreter searches for a file named
X{\tt foo.py}
Xin a list of directories specified by the environment variable
X{\tt PYTHONPATH}.
XIt has the same syntax as the \UNIX\ shell variable
X{\tt PATH},
Xi.e., a list of colon-separated directory names.
XWhen
X{\tt PYTHONPATH}
Xis not set, an installation-dependent default path is used, usually
X{\tt .:/usr/local/lib/python}.%
X\footnote{
X Modules are really searched in the list of directories given by
X the variable {\tt sys.path} which is initialized from
X {\tt PYTHONPATH} or from the installation-dependent default.
X See the section on Standard Modules later.
X}
X
XOn BSD'ish \UNIX\ systems, \Python\ scripts can be made directly executable,
Xlike shell scripts, by putting the line
X\bcode\begin{verbatim}
X#! /usr/local/python
X\end{verbatim}\ecode
X(assuming that's the name of the interpreter) at the beginning of the
Xscript and giving the file an executable mode.
X(The
X{\tt \#!}
Xmust be the first two characters of the file.)
X
X\subsection{Interactive Input Editing and History Substitution}
X
XSome versions of the \Python\ interpreter support editing of the current
Xinput line and history substitution, similar to facilities found in the
XKorn shell and the GNU Bash shell.
XThis is implemented using the
X{\em GNU\ Readline}
Xlibrary, which supports Emacs-style and vi-style editing.
XThis library has its own documentation which I won't duplicate here;
Xhowever, the basics are easily explained.
X
XIf supported,%
X\footnote{
X Perhaps the quickest check to see whether command line editing
X is supported is typing Control-P to the first \Python\ prompt
X you get. If it beeps, you have command line editing.
X If not, you can skip the rest of this section.
X}
Xinput line editing is active whenever the interpreter prints a primary
Xor secondary prompt.
XThe current line can be edited using the conventional Emacs control
Xcharacters.
XThe most important of these are:
XC-A (Control-A) moves the cursor to the beginning of the line, C-E to
Xthe end, C-B moves it one position to the left, C-F to the right.
XBackspace erases the character to the left of the cursor, C-D the
Xcharacter to its right.
XC-K kills (erases) the rest of the line to the right of the cursor, C-Y
Xyanks back the last killed string.
XC-underscore undoes the last change you made; it can be repeated for
Xcumulative effect.
X
XHistory substitution works as follows.
XAll non-empty input lines issued are saved in a history buffer,
Xand when a new prompt is given you are positioned on a new line at the
Xbottom of this buffer.
XC-P moves one line up (back) in the history buffer, C-N moves one down.
XAny line in the history buffer can be edited; an asterisk appears in
Xfront of the prompt to mark a line as modified.
XPressing the Return key passes the current line to the interpreter.
XC-R starts an incremental reverse search; C-S starts a forward search.
X
XThe key bindings and some other parameters of the Readline library can
Xbe customized by placing commands in an initialization file called
X{\tt \$HOME/.initrc}.
XKey bindings have the form
X\bcode\begin{verbatim}
Xkey-name: function-name
X\end{verbatim}\ecode
Xand options can be set with
X\bcode\begin{verbatim}
Xset option-name value
X\end{verbatim}\ecode
XExample:
X\bcode\begin{verbatim}
X# I prefer vi-style editing:
Xset editing-mode vi
X# Edit using a single line:
Xset horizontal-scroll-mode On
X# Rebind some keys:
XMeta-h: backward-kill-word
XControl-u: universal-argument
X\end{verbatim}\ecode
XNote that the default binding for TAB in \Python\ is to insert a TAB
Xinstead of Readline's default filename completion function.
XIf you insist, you can override this by putting
X\bcode\begin{verbatim}
XTAB: complete
X\end{verbatim}\ecode
Xin your
X{\tt \$HOME/.inputrc}.
X(Of course, this makes it hard to type indented continuation lines.)
X
XThis facility is an enormous step forward compared to previous versions of
Xthe interpreter; however, some wishes are left:
XIt would be nice if the proper indentation were suggested on
Xcontinuation lines (the parser knows if an indent token is required
Xnext).
XThe completion mechanism might use the interpreter's symbol table.
XA function to check (or even suggest) matching parentheses, quotes
Xetc. would also be useful.
X
X\section{An Informal Introduction to Python}
X
XIn the following examples, input and output are distinguished by the
Xpresence or absence of prompts ({\tt >>>} and {\tt ...}): to repeat the
Xexample, you must type everything after the prompt, when the prompt
Xappears; everything on lines that do not begin with a prompt is output
Xfrom the interpreter.
XNote that a secondary prompt on a line by itself in an example means you
Xmust type a blank line; this is used to end a multi-line command.
X
X\subsection{Using Python as a Calculator}
X
XLet's try some simple \Python\ commands.
XStart the interpreter and wait for the primary prompt,
X{\tt >>>}.
XThe interpreter acts as a simple calculator: you can type an expression
Xat it and it will write the value.
XExpression syntax is straightforward: the operators
X{\tt +},
X{\tt -},
X{\tt *}
Xand
X{\tt /}
Xwork just as in most other languages (e.g., Pascal or C); parentheses
Xcan be used for grouping.
XFor example:
X\bcode\begin{verbatim}
X>>> # This is a comment
X>>> 2+2
X4
X>>>
X>>> (50-5+5*6+25)/4
X25
X>>> # Division truncates towards zero:
X>>> 7/3
X2
X>>>
X\end{verbatim}\ecode
XAs in C, the equal sign ({\tt =}) is used to assign a value to a variable.
XThe value of an assignment is not written:
X\bcode\begin{verbatim}
X>>> width = 20
X>>> height = 5*9
X>>> width * height
X900
X>>>
X\end{verbatim}\ecode
XThere is some support for floating point, but you can't mix floating
Xpoint and integral numbers in expression (yet):
X\bcode\begin{verbatim}
X>>> 10.0 / 3.3
X3.0303030303
X>>>
X\end{verbatim}\ecode
XBesides numbers, \Python\ can also manipulate strings, enclosed in single
Xquotes:
X\bcode\begin{verbatim}
X>>> 'foo bar'
X'foo bar'
X>>> 'doesn\'t'
X'doesn\'t'
X>>>
X\end{verbatim}\ecode
XStrings are written inside quotes and with quotes and other funny
Xcharacters escaped by backslashes, to show the precise value.
X(There is also a way to write strings without quotes and escapes.)
XStrings can be concatenated (glued together) with the
X{\tt +}
Xoperator, and repeated with~{\tt *}:
X\bcode\begin{verbatim}
X>>> word = 'Help' + 'A'
X>>> word
X'HelpA'
X>>> '<' + word*5 + '>'
X'<HelpAHelpAHelpAHelpAHelpA>'
X>>>
X\end{verbatim}\ecode
XStrings can be subscripted; as in C, the first character of a string has
Xsubscript 0.
XThere is no separate character type; a character is simply a string of
Xsize one.
XAs in Icon, substrings can be specified with the
X{\em slice}
Xnotation: two subscripts (indices) separated by a colon.
X\bcode\begin{verbatim}
X>>> word[4]
X'A'
X>>> word[0:2]
X'He'
X>>> word[2:4]
X'lp'
X>>> # Slice indices have useful defaults:
X>>> word[:2] # Take first two characters
X'He'
X>>> word[2:] # Drop first two characters
X'lpA'
X>>> # A useful invariant: s[:i] + s[i:] = s
X>>> word[:3] + word[3:]
X'HelpA'
X>>>
X\end{verbatim}\ecode
XDegenerate cases are handled gracefully: an index that is too large is
Xreplaced by the string size, an upper bound smaller than the lower bound
Xreturns an empty string.
X\bcode\begin{verbatim}
X>>> word[1:100]
X'elpA'
X>>> word[10:]
X''
X>>> word[2:1]
X''
X>>>
X\end{verbatim}\ecode
XSlice indices (but not simple subscripts) may be negative numbers, to
Xstart counting from the right.
XFor example:
X\bcode\begin{verbatim}
X>>> word[-2:] # Take last two characters
X'pA'
X>>> word[:-2] # Drop last two characters
X'Hel'
X>>> # But -0 does not count from the right!
X>>> word[-0:] # (since -0 equals 0)
X'HelpA'
X>>>
X\end{verbatim}\ecode
XThe best way to remember how slices work is to think of the indices as
Xpointing
X{\em between}
Xcharacters, with the left edge of the first character numbered 0.
XThen the right edge of the last character of a string of
X{\tt n}
Xcharacters has index
X{\tt n},
Xfor example:
X\bcode\begin{verbatim}
X +---+---+---+---+---+
X | H | e | l | p | A |
X +---+---+---+---+---+
X 0 1 2 3 4 5
X-5 -4 -3 -2 -1
X\end{verbatim}\ecode
XThe first row of numbers gives the position of the indices 0...5 in the
Xstring; the second row gives the corresponding negative indices.
XFor nonnegative indices, the length of a slice is the difference of the
Xindices, if both are within bounds,
Xe.g.,
Xthe length of
X{\tt word[1:3]}
Xis 3--1 = 2.
X
XFinally, the built-in function {\tt len()} computes the length of a
Xstring:
X\bcode\begin{verbatim}
X>>> s = 'supercalifragilisticexpialidocious'
X>>> len(s)
X34
X>>>
X\end{verbatim}\ecode
X\Python\ knows a number of
X{\em compound}
Xdata types, used to group together other values.
XThe most versatile is the
X{\em list},
Xwhich can be written as a list of comma-separated values between square
Xbrackets:
X\bcode\begin{verbatim}
X>>> a = ['foo', 'bar', 100, 1234]
X>>> a
X['foo', 'bar', 100, 1234]
X>>>
X\end{verbatim}\ecode
XAs for strings, list subscripts start at 0:
X\bcode\begin{verbatim}
X>>> a[0]
X'foo'
X>>> a[3]
X1234
X>>>
X\end{verbatim}\ecode
XLists can be sliced and concatenated like strings:
X\bcode\begin{verbatim}
X>>> a[1:3]
X['bar', 100]
X>>> a[:2] + ['bletch', 2*2]
X['foo', 'bar', 'bletch', 4]
X>>>
X\end{verbatim}\ecode
XUnlike strings, which are
X{\em immutable},
Xit is possible to change individual elements of a list:
X\bcode\begin{verbatim}
X>>> a
X['foo', 'bar', 100, 1234]
X>>> a[2] = a[2] + 23
X>>> a
X['foo', 'bar', 123, 1234]
X>>>
X\end{verbatim}\ecode
XAssignment to slices is also possible, and this may even change the size
Xof the list:
X\bcode\begin{verbatim}
X>>> # Replace some items:
X>>> a[0:2] = [1, 12]
X>>> a
X[1, 12, 123, 1234]
X>>> # Remove some:
X>>> a[0:2] = []
X>>> a
X[123, 1234]
X>>> # Insert some:
X>>> a[1:1] = ['bletch', 'xyzzy']
X>>> a
X[123, 'bletch', 'xyzzy', 1234]
X>>>
X\end{verbatim}\ecode
XThe built-in function {\tt len()} also applies to lists:
X\bcode\begin{verbatim}
X>>> len(a)
X4
X>>>
X\end{verbatim}\ecode
X
X\subsection{Tuples and Sequences}
X
XXXX To Be Done.
X
X\subsection{First Steps Towards Programming}
X
XOf course, we can use \Python\ for more complicated tasks than adding two
Xand two together.
XFor instance, we can write an initial subsequence of the
X{\em Fibonacci}
Xseries as follows:
X\bcode\begin{verbatim}
X>>> # Fibonacci series:
X>>> # the sum of two elements defines the next
X>>> a, b = 0, 1
X>>> while b < 100:
X... print b
X... a, b = b, a+b
X...
X1
X1
X2
X3
X5
X8
X13
X21
X34
X55
X89
X>>>
X\end{verbatim}\ecode
XThis example introduces several new features.
X\begin{itemize}
X\item
XThe first line contains a
X{\em multiple\ assignment}:
Xthe variables
X{\tt a}
Xand
X{\tt b}
Xsimultaneously get the new values 0 and 1.
XOn the last line this is used again, demonstrating that the expressions
Xon the right-hand side are all evaluated first before any of the
Xassignments take place.
X\item
XThe
X{\tt while}
Xloop executes as long as the condition (here: $b < 100$) remains true.
XIn \Python, as in C, any non-zero integer value is true; zero is false.
XThe condition may also be a string or list value, in fact any sequence;
Xanything with a non-zero length is true, empty sequences are false.
XThe test used in the example is a simple comparison.
XThe standard comparison operators are written as
X{\tt <},
X{\tt >},
X{\tt =},
X{\tt <=},
X{\tt >=}
Xand
X{\tt <>}.%
X\footnote{
X The ambiguity of using {\tt =}
X for both assignment and equality is resolved by disallowing
X unparenthesized conditions at the right hand side of assignments.
X}
X\item
XThe
X{\em body}
Xof the loop is
X{\em indented}: indentation is \Python's way of grouping statements.
X\Python\ does not (yet!) provide an intelligent input line editing
Xfacility, so you have to type a tab or space(s) for each indented line.
XIn practice you will prepare more complicated input for \Python\ with a
Xtext editor; most text editors have an auto-indent facility.
XWhen a compound statement is entered interactively, it must be
Xfollowed by a blank line to indicate completion (since the parser
Xcannot guess when you have typed the last line).
X\item
XThe
X{\tt print}
Xstatement writes the value of the expression(s) it is given.
XIt differs from just writing the expression you want to write (as we did
Xearlier in the calculator examples) in the way it handles multiple
Xexpressions and strings.
XStrings are written without quotes and a space is inserted between
Xitems, so you can format things nicely, like this:
X\bcode\begin{verbatim}
X>>> i = 256*256
X>>> print 'The value of i is', i
XThe value of i is 65536
X>>>
X\end{verbatim}\ecode
XA trailing comma avoids the newline after the output:
X\bcode\begin{verbatim}
X>>> a, b = 0, 1
X>>> while b < 1000:
X... print b,
X... a, b = b, a+b
X...
X1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
X>>>
X\end{verbatim}\ecode
XNote that the interpreter inserts a newline before it prints the next
Xprompt if the last line was not completed.
X\end{itemize}
X
X\subsection{More Control Flow Tools}
X
XBesides the {\tt while} statement just introduced, \Python\ knows the
Xusual control flow statements known from other languages, with some
Xtwists.
X
X\subsubsection{If Statements}
X
XPerhaps the most well-known statement type is the {\tt if} statement.
XFor example:
X\bcode\begin{verbatim}
X>>> if x < 0:
X... x = 0
X... print 'Negative changed to zero'
X... elif x = 0:
X... print 'Zero'
X... elif x = 1:
X... print 'Single'
X... else:
X... print 'More'
X...
X\end{verbatim}\ecode
XThere can be zero or more {\tt elif} parts, and the {\tt else} part is
Xoptional.
XThe keyword `{\tt elif}' is short for `{\tt else if}', and is useful to
Xavoid excessive indentation.
XAn {\tt if...elif...elif...} sequence is a substitute for the
X{\em switch} or {\em case} statements found in other languages.
X
X\subsubsection{For Statements}
X
XThe {\tt for} statement in \Python\ differs a bit from what you may be
Xused to in C or Pascal.
XRather than always iterating over an arithmetic progression of numbers
X(as Pascal), or leaving the user completely free in the iteration test
Xand step (as C), \Python's {\tt for} statement iterates over the items
Xof any sequence (e.g., a list or a string).
XFor example (no pun intended):
X\bcode\begin{verbatim}
X>>> # Measure some strings:
X>>> a = ['cat', 'window', 'defenestrate']
X>>> for x in a:
X... print x, len(x)
X...
Xcat 3
Xwindow 6
Xdefenestrate 12
X>>>
X\end{verbatim}\ecode
X
X\subsubsection{The {\tt range()} Function}
X
XIf you do need to iterate over a sequence of numbers, the built-in
Xfunction {\tt range()} comes in handy.
XIt generates lists containing arithmetic progressions,
Xe.g.:
X\bcode\begin{verbatim}
X>>> range(10)
X[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
X>>>
X\end{verbatim}\ecode
XThe given end point is never part of the generated list;
X{\tt range(10)} generates a list of 10 values,
Xexactly the legal indices for items of a sequence of length 10.
XIt is possible to let the range start at another number, or to specify a
Xdifferent increment (even negative):
X\bcode\begin{verbatim}
X>>> range(5, 10)
X[5, 6, 7, 8, 9]
X>>> range(0, 10, 3)
X[0, 3, 6, 9]
X>>> range(-10, -100, -30)
X[-10, -40, -70]
X>>>
X\end{verbatim}\ecode
XTo iterate over the indices of a sequence, combine {\tt range()}
Xand {\tt len()} as follows:
X\bcode\begin{verbatim}
X>>> a = ['Mary', 'had', 'a', 'little', 'boy']
X>>> for i in range(len(a)):
X... print i, a[i]
X...
X0 Mary
X1 had
X2 a
X3 little
X4 boy
X>>>
X\end{verbatim}\ecode
X
X\subsubsection{Break Statements and Else Clauses on Loops}
X
XThe {\tt break} statement breaks out of the smallest enclosing {\tt for}
Xor {\tt while} loop.
XLoop statements may have an {\tt else} clause; it is executed when the
Xloop terminates through exhaustion of the list (with {\tt for}) or when
Xthe condition becomes false (with {\tt while}) but not when the loop is
Xterminated by a {\tt break} statement.
XThis is exemplified by the following loop, which searches for a list
Xitem of value 0:
X\bcode\begin{verbatim}
X>>> for n in range(2, 10):
X... for x in range(2, n):
X... if n % x = 0:
X... print n, 'equals', x, '*', n/x
X... break
X... else:
X... print n, 'is a prime number'
X...
X2 is a prime number
X3 is a prime number
X4 equals 2 * 2
X5 is a prime number
X6 equals 2 * 3
X7 is a prime number
X8 equals 2 * 4
X9 equals 3 * 3
X>>>
X\end{verbatim}\ecode
X
X\subsubsection{Pass Statements}
X
XThe {\tt pass} statement does nothing.
XIt can be used when a statement is required syntactically but the
Xprogram requires no action.
XFor example:
X\bcode\begin{verbatim}
X>>> while 1:
X... pass # Busy-wait for keyboard interrupt
X...
X\end{verbatim}\ecode
X
X\subsubsection{Conditions Revisited}
X
XXXX To Be Done.
X
X\subsection{Defining Functions}
X
XWe can create a function that writes the Fibonacci series to an
Xarbitrary boundary:
X\bcode\begin{verbatim}
X>>> def fib(n): # write Fibonacci series up to n
X... a, b = 0, 1
X... while b <= n:
X... print b,
X... a, b = b, a+b
X...
X>>> # Now call the function we just defined:
X>>> fib(2000)
X1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
X>>>
X\end{verbatim}\ecode
XThe keyword
X{\tt def}
Xintroduces a function
X{\em definition}.
XIt must be followed by the function name and the parenthesized list of
Xformal parameters.
XThe statements that form the body of the function starts at the next
Xline, indented by a tab stop.
XThe
X{\em execution}
Xof a function introduces a new symbol table used for the local variables
Xof the function.
XMore precisely, all variable assignments in a function store the value
Xin the local symbol table; variable references first look in the local
Xsymbol table, then in the global symbol table, and then in the table of
Xbuilt-in names.
XThus, the global symbol table is
X{\em read-only}
Xwithin a function.
XThe actual parameters (arguments) to a function call are introduced in
Xthe local symbol table of the called function when it is called;
Xthus, arguments are passed using
X{\em call\ by\ value}.%
X\footnote{
X Actually, {\em call by object reference} would be a better
X description, since if a mutable object is passed, the caller
X will see any changes the callee makes to it (e.g., items
X inserted into a list).
X}
XWhen a function calls another function, a new local symbol table is
Xcreated for that call.
X
XA function definition introduces the function name in the global symbol
Xtable.
XThe value has a type that is recognized by the interpreter as a
Xuser-defined function.
XThis value can be assigned to another name which can then also be used
Xas a function.
XThis serves as a general renaming mechanism:
X\bcode\begin{verbatim}
X>>> fib
X<function object at 10042ed0>
X>>> f = fib
X>>> f(100)
X1 1 2 3 5 8 13 21 34 55 89
X>>>
X\end{verbatim}\ecode
XYou might object that
X{\tt fib}
Xis not a function but a procedure.
XIn \Python, as in C, procedures are just functions that don't return a
Xvalue.
XIn fact, technically speaking, procedures do return a value, albeit a
Xrather boring one.
XThis value is called {\tt None} (it's a built-in name).
XWriting the value {\tt None} is normally suppressed by the interpreter
Xif it would be the only value written.
XYou can see it if you really want to:
X\bcode\begin{verbatim}
X>>> print fib(0)
XNone
X>>>
X\end{verbatim}\ecode
XIt is simple to write a function that returns a list of the numbers of
Xthe Fibonacci series, instead of printing it:
X\bcode\begin{verbatim}
X>>> def fib2(n): # return Fibonacci series up to n
X... result = []
X... a, b = 0, 1
X... while b <= n:
X... result.append(b) # see below
X... a, b = b, a+b
X... return result
X...
X>>> f100 = fib2(100) # call it
X>>> f100 # write the result
X[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
X>>>
X\end{verbatim}\ecode
XThis example, as usual, demonstrates some new \Python\ features:
X\begin{itemize}
X\item
XThe
X{\tt return}
Xstatement returns with a value from a function.
X{\tt return}
Xwithout an expression argument is used to return from the middle of a
Xprocedure (falling off the end also returns from a proceduce).
X\item
XThe statement
X{\tt ret.append(b)}
Xcalls a
X{\em method}
Xof the list object
X{\tt ret}.
XA method is a function that `belongs' to an object and is named
X{\tt obj.methodname},
Xwhere
X{\tt obj}
Xis some object (this may be an expression), and
X{\tt methodname}
Xis the name of a method that is defined by the object's type.
XDifferent types define different methods.
XMethods of different types may have the same name without causing
Xambiguity.
XSee the section on classes, later, to find out how you can define your
Xown object types and methods.
XThe method
X{\tt append}
Xshown in the example, is defined for list objects; it adds a new element
Xat the end of the list.
XIn this case it is equivalent to
X{\tt ret = ret + [b]},
Xbut more efficient.%
X\footnote{
X There is a subtle semantic difference if the object
X is referenced from more than one place.
X}
X\end{itemize}
XThe list object type has two more methods:
X\begin{description}
X\item[{\tt insert(i, x)}]
XInserts an item at a given position.
XThe first argument is the index of the element before which to insert,
Xso {\tt a.insert(0, x)} inserts at the front of the list, and
X{\tt a.insert(len(a), x)} is equivalent to {\tt a.append(x)}.
X\item[{\tt sort()}]
XSorts the elements of the list.
X\end{description}
XFor example:
X\bcode\begin{verbatim}
X>>> a = [10, 100, 1, 1000]
X>>> a.insert(2, -1)
X>>> a
X[10, 100, -1, 1, 1000]
X>>> a.sort()
X>>> a
X[-1, 1, 10, 100, 1000]
X>>> # Strings are sorted according to ASCII:
X>>> b = ['Mary', 'had', 'a', 'little', 'boy']
X>>> b.sort()
X>>> b
X['Mary', 'a', 'boy', 'had', 'little']
X>>>
X\end{verbatim}\ecode
X
X\subsection{Modules}
X
XIf you quit from the \Python\ interpreter and enter it again, the
Xdefinitions you have made (functions and variables) are lost.
XTherefore, if you want to write a somewhat longer program, you are
Xbetter off using a text editor to prepare the input for the interpreter
Xand run it with that file as input instead.
XThis is known as creating a
X{\em script}.
XAs your program gets longer, you may want to split it into several files
Xfor easier maintenance.
XYou may also want to use a handy function that you've written in several
Xprograms without copying its definition into each program.
XTo support this, \Python\ has a way to put definitions in a file and use
Xthem in a script or in an interactive instance of the interpreter.
XSuch a file is called a
X{\em module};
Xdefinitions from a module can be
X{\em imported}
Xinto other modules or into the
X{\em main}
Xmodule (the collection of variables that you have access to in
Xa script and in calculator mode).
X
XA module is a file containing \Python\ definitions and statements.
XThe file name is the module name with the suffix
X{\tt .py}
Xappended.
XFor instance, use your favorite text editor to create a file called
X{\tt fibo.py}
Xin the current directory with the following contents:
X\bcode\begin{verbatim}
X# Fibonacci numbers module
X
Xdef fib(n): # write Fibonacci series up to n
X a, b = 0, 1
X while b <= n:
X print b,
X a, b = b, a+b
X
Xdef fib2(n): # return Fibonacci series up to n
X ret = []
X a, b = 0, 1
X while b <= n:
X ret.append(b)
X a, b = b, a+b
X return ret
X\end{verbatim}\ecode
XNow enter the \Python\ interpreter and import this module with the
Xfollowing command:
X\bcode\begin{verbatim}
X>>> import fibo
X>>>
X\end{verbatim}\ecode
XThis does not enter the names of the functions defined in
X{\tt fibo}
Xdirectly in the symbol table; it only enters the module name
X{\tt fibo}
Xthere.
XUsing the module name you can access the functions:
X\bcode\begin{verbatim}
X>>> fibo.fib(1000)
X1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
X>>> fibo.fib2(100)
X[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
X>>>
X\end{verbatim}\ecode
XIf you intend to use a function often you can assign it to a local name:
X\bcode\begin{verbatim}
X>>> fib = fibo.fib
X>>> fib(500)
X1 1 2 3 5 8 13 21 34 55 89 144 233 377
X>>>
X\end{verbatim}\ecode
X
X\subsubsection{More on Modules}
X
XA module can contain executable statements as well as function
Xdefinitions.
XThese statements are intended to initialize the module.
XThey are executed only the
X{\em first}
Xtime the module is imported somewhere.%
X\footnote{
X In fact function definitions are also `statements' that are
X `executed'; the execution enters the function name in the
X module's global symbol table.
X}
X
XEach module has its own private symbol table, which is used as the
Xglobal symbol table by all functions defined in the module.
XThus, the author of a module can use global variables in the module
Xwithout worrying about accidental clashes with a user's global
Xvariables.
XOn the other hand, if you know what you are doing you can touch a
Xmodule's global variables with the same notation used to refer to its
Xfunctions,
X{\tt modname.itemname}.
X
XModules can import other modules.
XIt is customary but not required to place all
X{\tt import}
Xstatements at the beginning of a module (or script, for that matter).
XThe imported module names are placed in the importing module's global
Xsymbol table.
X
XThere is a variant of the
X{\tt import}
Xstatement that imports names from a module directly into the importing
Xmodule's symbol table.
XFor example:
X\bcode\begin{verbatim}
X>>> from fibo import fib, fib2
X>>> fib(500)
X1 1 2 3 5 8 13 21 34 55 89 144 233 377
X>>>
X\end{verbatim}\ecode
XThis does not introduce the module name from which the imports are taken
Xin the local symbol table (so in the example, {\tt fibo} is not
Xdefined).
X
XThere is even a variant to import all names that a module defines:
X\bcode\begin{verbatim}
X>>> from fibo import *
X>>> fib(500)
X1 1 2 3 5 8 13 21 34 55 89 144 233 377
X>>>
X\end{verbatim}\ecode
XThis imports all names except those beginning with an underscore
X({\tt \_}).
X
X\subsubsection{Standard Modules}
X
X\Python\ comes with a library of standard modules, described in a separate
Xdocument (Python Library and Module Reference).
XSome modules are built into the interpreter; these provide access to
Xoperations that are not part of the core of the language but are
Xnevertheless built in, either for efficiency or to provide access to
Xoperating system primitives such as system calls.
XThe set of such modules is a configuration option; e.g., the
X{\tt amoeba}
Xmodule is only provided on systems that somehow support Amoeba
Xprimitives.
XOne particular module deserves some attention:
X{\tt sys},
Xwhich is built into every \Python\ interpreter.
XThe variables
X{\tt sys.ps1}
Xand
X{\tt sys.ps2}
Xdefine the strings used as primary and secondary prompts:
X\bcode\begin{verbatim}
X>>> import sys
X>>> sys.ps1
X'>>> '
X>>> sys.ps2
X'... '
X>>> sys.ps1 = 'C> '
XC> print 'Yuck!'
XYuck!
XC>
X\end{verbatim}\ecode
XThese two variables are only defined if the interpreter is in
Xinteractive mode.
X
XThe variable
X{\tt sys.path}
Xis a list of strings that determine the interpreter's search path for
Xmodules.
XIt is initialized to a default path taken from the environment variable
X{\tt PYTHONPATH},
Xor from a built-in default if
X{\tt PYTHONPATH}
Xis not set.
XYou can modify it using standard list operations, e.g.:
X\bcode\begin{verbatim}
X>>> import sys
X>>> sys.path.append('/ufs/guido/lib/python')
X>>>
X\end{verbatim}\ecode
X
X\subsection{Errors and Exceptions}
X
XUntil now error messages haven't yet been mentioned, but if you have
Xtried out the examples you have probably seen some.
XThere are (at least) two distinguishable kinds of errors:
X{\em syntax\ errors}
Xand
X{\em exceptions}.
X
X\subsubsection{Syntax Errors}
X
XSyntax errors, also known as parsing errors, are perhaps the most common
Xkind of complaint you get while you are still learning \Python:
X\bcode\begin{verbatim}
X>>> while 1 print 'Hello world'
XParsing error: file <stdin>, line 1:
Xwhile 1 print 'Hello world'
X ^
XUnhandled exception: run-time error: syntax error
X>>>
X\end{verbatim}\ecode
XThe parser repeats the offending line and displays a little `arrow'
Xpointing at the earliest point in the line where the error was detected.
XThe error is caused by (or at least detected at) the token
X{\em preceding}
Xthe arrow: in the example, the error is detected at the keyword
X{\tt print}, since a colon ({\tt :}) is missing before it.
XFile name and line number are printed so you know where to look in case
Xthe input came from a script.
X
X\subsubsection{Exceptions}
X
XEven if a statement or expression is syntactically correct, it may cause
Xan error when an attempt is made to execute it:
X\bcode\small\begin{verbatim}
X>>> 10 * (1/0)
XUnhandled exception: run-time error: integer division by zero
XStack backtrace (innermost last):
X File "<stdin>", line 1
X>>> 4 + foo*3
XUnhandled exception: undefined name: foo
XStack backtrace (innermost last):
X File "<stdin>", line 1
X>>> '2' + 2
XUnhandled exception: type error: illegal argument type for built-in operation
XStack backtrace (innermost last):
X File "<stdin>", line 1
X>>>
X\end{verbatim}\ecode
XErrors detected during execution are called
X{\em exceptions}
Xand are not unconditionally fatal: you will soon learn how to handle
Xthem in \Python\ programs.
XMost exceptions are not handled by programs, however, and result
Xin error messages as shown here.
X
XThe first line of the error message indicates what happened.
XExceptions come in different types, and the type is printed as part of
Xthe message: the types in the example are
X{\tt run-time error},
X{\tt undefined name}
Xand
X{\tt type error}.
XThe rest of the line is a detail whose interpretation depends on the
Xexception type.
X
XThe rest of the error message shows the context where the
Xexception happened.
XIn general it contains a stack backtrace listing source lines; however,
Xit will not display lines read from standard input.
X
XHere is a summary of the most common exceptions:
X\begin{itemize}
X\item
X{\em Run-time\ errors}
Xare generally caused by wrong data used by the program; this can be the
Xprogrammer's fault or caused by bad input.
XThe detail states the cause of the error in more detail.
X\item
X{\em Undefined\ name}
Xerrors are more serious: these are usually caused by misspelled
Xidentifiers.%
X\footnote{
X The parser does not check whether names used in a program are at
X all defined elsewhere in the program, so such checks are
X postponed until run-time. The same holds for type checking.
X}
XThe detail is the offending identifier.
X\item
X{\em Type\ errors}
Xare also pretty serious: this is another case of using wrong data (or
Xbetter, using data the wrong way), but here the error can be glanced
Xfrom the object type(s) alone.
XThe detail shows in what context the error was detected.
X\end{itemize}
X
X\subsubsection{Handling Exceptions}
X
XIt is possible to write programs that handle selected exceptions.
XLook at the following example, which prints a table of inverses of
Xsome floating point numbers:
X\bcode\begin{verbatim}
X>>> numbers = [0.3333, 2.5, 0.0, 10.0]
X>>> for x in numbers:
X... print x,
X... try:
X... print 1.0 / x
X... except RuntimeError:
X... print '*** has no inverse ***'
X...
X0.3333 3.00030003
X2.5 0.4
X0 *** has no inverse ***
X10 0.1
X>>>
X\end{verbatim}\ecode
XThe {\tt try} statement works as follows.
X\begin{itemize}
X\item
XFirst, the
X{\em try\ clause}
X(the statement(s) between the {\tt try} and {\tt except} keywords) is
Xexecuted.
X\item
XIf no exception occurs, the
X{\em except\ clause}
Xis skipped and execution of the {\tt try} statement is finished.
X\item
XIf an exception occurs during execution of the try clause, and its
Xtype matches the exception named after the {\tt except} keyword, the
Xrest of the try clause is skipped, the except clause is executed, and
Xthen execution continues after the {\tt try} statement.
X\item
XIf an exception occurs which does not match the exception named in the
Xexcept clause, it is passed on to outer try statements; if no handler is
Xfound, it is an
X{\em unhandled\ exception}
Xand execution stops with a message as shown above.
X\end{itemize}
XA {\tt try} statement may have more than one except clause, to specify
Xhandlers for different exceptions.
XAt most one handler will be executed.
XHandlers only handle exceptions that occur in the corresponding try
Xclause, not in other handlers of the same {\tt try} statement.
XAn except clause may name multiple exceptions as a parenthesized list,
Xe.g.:
X\bcode\begin{verbatim}
X... except (RuntimeError, TypeError, NameError):
X... pass
X\end{verbatim}\ecode
XThe last except clause may omit the exception name(s), to serve as a
Xwildcard.
XUse this with extreme caution!
X
XWhen an exception occurs, it may have an associated value, also known as
Xthe exceptions's
X{\em argument}.
XThe presence and type of the argument depend on the exception type.
XFor exception types which have an argument, the except clause may
Xspecify a variable after the exception name (or list) to receive the
Xargument's value, as follows:
X\bcode\begin{verbatim}
X>>> try:
X... foo()
X... except NameError, x:
X... print 'name', x, 'undefined'
X...
Xname foo undefined
X>>>
X\end{verbatim}\ecode
XIf an exception has an argument, it is printed as the third part
X(`detail') of the message for unhandled exceptions.
X
XStandard exception names are built-in identifiers (not reserved
Xkeywords).
XThese are in fact string objects whose
X{\em object\ identity}
X(not their value!) identifies the exceptions.%
X\footnote{
X There should really be a separate exception type; it is pure
X laziness that exceptions are identified by strings, and this may
X be fixed in the future.
X}
XThe string is printed as the second part of the message for unhandled
Xexceptions.
XTheir names and values are:
X\bcode\begin{verbatim}
XEOFError 'end-of-file read'
XKeyboardInterrupt 'keyboard interrupt'
XMemoryError 'out of memory' *
XNameError 'undefined name' *
XRuntimeError 'run-time error' *
XSystemError 'system error' *
XTypeError 'type error' *
X\end{verbatim}\ecode
XThe meanings should be clear enough.
XThose exceptions with a {\tt *} in the third column have an argument.
X
XException handlers don't just handle exceptions if they occur
Ximmediately in the try clause, but also if they occur inside functions
Xthat are called (even indirectly) in the try clause.
XFor example:
X\bcode\begin{verbatim}
X>>> def this_fails():
X... x = 1/0
X...
X>>> try:
X... this_fails()
X... except RuntimeError, detail:
X... print 'Handling run-time error:', detail
X...
XHandling run-time error: domain error or zero division
X>>>
X\end{verbatim}\ecode
X
X\subsubsection{Raising Exceptions}
X
XThe {\tt raise} statement allows the programmer to force a specified
Xexception to occur.
XFor example:
X\bcode\begin{verbatim}
X>>> raise NameError, 'Hi There!'
XUnhandled exception: undefined name: Hi There!
XStack backtrace (innermost last):
X File "<stdin>", line 1
X>>>
X\end{verbatim}\ecode
XThe first argument to {\tt raise} names the exception to be raised.
XThe optional second argument specifies the exception's argument.
X
X\subsubsection{User-defined Exceptions}
X
XPrograms may name their own exceptions by assigning a string to a
Xvariable.
XFor example:
X\bcode\begin{verbatim}
X>>> my_exc = 'nobody likes me!'
X>>> try:
X... raise my_exc, 2*2
X... except my_exc, val:
X... print 'My exception occured, value:', val
X...
XMy exception occured, value: 4
X>>> raise my_exc, 1
XUnhandled exception: nobody likes me!: 1
XStack backtrace (innermost last):
X File "<stdin>", line 7
X>>>
X\end{verbatim}\ecode
XMany standard modules use this to report errors that may occur in
Xfunctions they define.
X
X\subsubsection{Defining Clean-up Actions}
X
XThe {\tt try} statement has another optional clause which is intended to
Xdefine clean-up actions that must be executed under all circumstances.
XFor example:
X\bcode\begin{verbatim}
X>>> try:
X... raise KeyboardInterrupt
X... finally:
X... print 'Goodbye, world!'
X...
XGoodbye, world!
XUnhandled exception: keyboard interrupt
XStack backtrace (innermost last):
X File "<stdin>", line 2
X>>>
X\end{verbatim}\ecode
XThe
X{\em finally\ clause}
Xmust follow the except clauses(s), if any.
XIt is executed whether or not an exception occurred.
XIf the exception is handled, the finally clause is executed after the
Xhandler (and even if another exception occurred in the handler).
XIt is also executed when the {\tt try} statement is left via a
X{\tt break} or {\tt return} statement.
X
X\subsection{Classes}
X
XClasses in \Python\ make it possible to play the game of encapsulation in a
Xsomewhat different way than it is played with modules.
XClasses are an advanced topic and are probably best skipped on the first
Xencounter with \Python.
X
X\subsubsection{Prologue}
X
X\Python's class mechanism is not particularly elegant, but quite powerful.
XIt is a mixture of the class mechanisms found in C++ and Modula-3.
XAs is true for modules, classes in \Python\ do not put an absolute barrier
Xbetween definition and user, but rather rely on the politeness of the
Xuser not to ``break into the definition.''
XThe most important features of classes are retained with full power,
Xhowever: the class inheritance mechanism allows multiple base classes,
Xa derived class can override any method of its base class(es), a method
Xcan call the method of a base class with the same name.
XObjects can contain an arbitrary amount of private data.
X
XIn C++ terminology, all class members (including data members) are
X{\em public},
Xand all member functions (methods) are
X{\em virtual}.
XThere are no special constructors or destructors.
XAs in Modula-3, there are no shorthands for referencing the object's
Xmembers from its methods: the method function is declared with an
Xexplicit first argument representing the object, which is provided
Ximplicitly by the call.
XAs in Smalltalk, classes themselves are objects, albeit in the wider
Xsense of the word: in \Python, all data types are objects.
XThis provides semantics for renaming or aliasing.
XBut, just like in C++ or Modula-3, the built-in types cannot be used as
Xbase classes for extension by the user.
XAlso, like Modula-3 but unlike C++, the built-in operators with special
Xsyntax (arithmetic operators, subscripting etc.) cannot be redefined for
Xclass members.%
X\footnote{
X They can be redefined for new object types implemented in C in
X extensions to the interpreter, however. It would require only a
X naming convention and a relatively small change to the
X interpreter to allow operator overloading for classes, so
X perhaps someday...
X}
X
X\subsubsection{A Simple Example}
X
XConsider the following example, which defines a class {\tt Set}
Xrepresenting a (finite) mathematical set with operations to add and
Xremove elements, a membership test, and a request for the size of the
Xset.
X\bcode\begin{verbatim}
Xclass Set():
X def new(self):
X self.elements = []
X return self
X def add(self, e):
X if e not in self.elements:
X self.elements.append(e)
X def remove(self, e):
X if e in self.elements:
X for i in range(len(self.elements)):
X if self.elements[i] = e:
X del self.elements[i]
X break
X def is_element(self, e):
X return e in self.elements
X def size(self):
X return len(self.elements)
X\end{verbatim}\ecode
XNote that the class definition looks like a big compound statement,
Xwith all the function definitons indented repective to the
X{\tt class}
Xkeyword.
X
XLet's assume that this
X{\em class\ definition}
Xis the only contents of the module file
X{\tt SetClass.py}.
XWe can then use it in a \Python\ program as follows:
X\bcode\begin{verbatim}
X>>> from SetClass import Set
X>>> a = Set().new() # create a Set object
X>>> a.add(2)
X>>> a.add(3)
X>>> a.add(1)
X>>> a.add(1)
X>>> if a.is_element(3): print '3 is in the set'
X...
X3 is in the set
X>>> if not a.is_element(4): print '4 is not in the set'
X...
X4 is not in the set
X>>> print 'a has', a.size(), 'elements'
Xa has 3 elements
X>>> a.remove(1)
X>>> print 'now a has', a.size(), 'elements'
X>>>
Xnow a has 2 elements
X>>>
X\end{verbatim}\ecode
XFrom the example we learn in the first place that the functions defined
Xin the class (e.g.,
X{\tt add})
Xcan be called using the
X{\em member}
Xnotation for the object
X{\tt a}.
XThe member function is called with one less argument than it is defined:
Xthe object is implicitly passed as the first argument.
XThus, the call
X{\tt a.add(2)}
Xis equivalent to
X{\tt Set.add(a, 2)}.
X
XXXX This section is not complete yet!
X
X\section{XXX P.M.}
X
X\begin{itemize}
X\item The {\tt del} statement.
X\item The {\tt dir()} function.
X\item Tuples.
X\item Dictionaries.
X\item Objects and types in general.
X\item Backquotes.
X\item And/Or/Not.
X\end{itemize}
X
X\end{document}
EOF
fi
echo 'Part 01 out of 21 of pack.out complete.'
exit 0