-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLPTHD
2333 lines (1801 loc) · 65.3 KB
/
LPTHD
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
练习8
whwu@master:~/script/python/LPTHW> cat ex8.py
formatter="%r %r %r %r"
print formatter % (1,2,3,4)
print formatter % ("one","two","three","four")
print formatter % (True,False,False,True)
print formatter % (
"I had this thing.",
"That you could type up right.",
"But it didn't sing.",
"So I said goodnight."
)
whwu@master:~/script/python/LPTHW> python ex8.py
1 2 3 4
'one' 'two' 'three' 'four'
True False False True
'I had this thing.' 'That you could type up right.' "But it didn't sing." 'So I said goodnight.'
为什么 “one” 要用引号,而 True 和 False 不需要?
因为 True 和 False 是 Python 的关键字,用来表示真假的意义。如果你加了引号,它们就变成
了字符串,也就无法实现它们本来的功能了。习题 27 中会有详细说明。
我在字符中包含了中文(或者其它非 ASCII 字符),可是 %r 打印出的是乱码?
使用 %s 就行了。
为什么 %r 有时打印出来的是单引号,而我实际用的是双引号?
Python 会用最有效的方式打印出字符串,而不是完全按照你写的方式来打印。这样做对于 %r 来
说是可以接受的,因为它是用作 debug 和排错,没必要非打印出多好看的格式。
练习9
whwu@master:~/script/python/LPTHW> cat ex9.py
#Here's some new strange stuff, remember type it exactly.
days = "Mon Tue Wed Thu Fri Sat Sun"
#months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
months = "\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
print "Here are the days:", days
print "Here are the months:", months
print """
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
"""
whwu@master:~/script/python/LPTHW> python ex9.py
Here are the days: Mon Tue Wed Thu Fri Sat Sun
Here are the months:
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
怎样将月份显示在新的一行?
字符串以 \n 开始就可以了,像这样:
"\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
练习10
whwu@master:~/script/python/LPTHW> cat ex10.py
tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = "I'm \\ a \\ cat."
fat_cat = """
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
"""
print tabby_cat
print persian_cat
print backslash_cat
print fat_cat
whwu@master:~/script/python/LPTHW> python ex10.py
I'm tabbed in.
I'm split
on a line.
I'm \ a \ cat.
I'll do a list:
* Cat food
* Fishies
* Catnip
* Grass
whwu@master:~/script/python/LPTHW> cat ex10plus1.py
while True:
for i in ["/","-","|","\\","|"]:
# print "%s\r" % i,
print "%s" % i,
练习11
whwu@master:~/script/python/LPTHW> cat ex11.py
print "How old are you?",
age = raw_input()
print "How tall are you?",
height = raw_input()
print "How much do you weigh?",
weight = raw_input()
print "So, you're %r old, %r tall and %r heavy." %(
age, height,weight)
whwu@master:~/script/python/LPTHW> python ex11.py
How old are you? 35
How tall are you? 6'5''
How much do you weigh? 180lbs
So, you're '35' old, "6'5''" tall and '180lbs' heavy.
Note
注意到我在每行 print 后面加了个逗号(comma) , 了吧?这样的话 print 就不会输出新行符而结束
这一行跑到下一行去了。
input和raw_input在处理数字时是有区别的:
1.输入为纯数字时
input返回的是数值类型,如int,float
raw_inpout返回的是字符串类型,string类型
whwu@master:~/script/python/LPTHW> cat ex11plus1.py
print "how old are you?"
age1 = input()
print "%r" % age1
print
age2 = raw_input()
print "%r" %age2
whwu@master:~/script/python/LPTHW> python ex11plus1.py
how old are you?
22
22
22
'22'//raw_input()把输入整形当做字符串处理
2.输入字符串为表达式
input会计算在字符串中的数字表达式,而raw_input不会。
whwu@master:~/script/python/LPTHW> cat ex11plus2.py
sum = input()
print "%r" % sum
print
sum = raw_input()
print "%r" % sum
whwu@master:~/script/python/LPTHW> python ex11plus2.py
1+2
3
1+2
'1+2'
input() 和 raw_input() 有何不同?
input() 函数会把你输入的东西当做 Python 代码进行处理,这么做会有安全问题,你应该避开
这个函数。
练习12
whwu@master:~/script/python/LPTHW> cat ex12.py
age= raw_input("How old are you?")
height = raw_input("How tall are you?")
weight = raw_input("How much do you weigh?")
print "So, you're %r old, %r tall and %r heavy." % (
age,height,weight)
whwu@master:~/script/python/LPTHW> python ex12.py
How old are you?35
How tall are you?6'2"
How much do you weigh?190lbs
So, you're '35' old, '6\'2"' tall and '190lbs' heavy.
练习13
whwu@master:~/script/python/LPTHW> python ex13.py wu wei hong
The script is called: ex13.py
Your first variable is: wu
Your second variable is: wei
Your third variable is: hong
whwu@master:~/script/python/LPTHW> cat ex13.py
from sys import argv
script,first,second,third = argv
script,first,second,third = argv
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third
练习14
whwu@master:~/script/python/LPTHW> python ex14.py Zed
Hi Zed, I'm the ex14.py script.
I'd like to ask you a few questions.
Do you like me Zed?
>yes
Where do you live Zed?
>usa
What kind of computer do you have?
>laptop
Alright, so you said 'yes' about liking me.
You live in 'usa'. Not sure where that is.
And you have a 'laptop' computer.Nice.
whwu@master:~/script/python/LPTHW> cat ex14.py
from sys import argv
script,user_name = argv
prompt = '>'
print "Hi %s, I'm the %s script." % (user_name, script)
print "I'd like to ask you a few questions."
print "Do you like me %s?" %user_name
likes = raw_input(prompt)
print "Where do you live %s?" % user_name
lives = raw_input(prompt)
print "What kind of computer do you have?"
computer = raw_input(prompt)
print"""
Alright, so you said %r about liking me.
You live in %r. Not sure where that is.
And you have a %r computer.Nice.
""" % (likes, lives, computer)
练习15
whwu@master:~/script/python/LPTHW> cat ex15.py
from sys import argv # 从sys库中引入argv
script,filename = argv # 命名参数
txt = open(filename) # 将文件打开,并赋值于txt
print "Here's your file %r:" % filename
print txt.read() # read txt中的所有内容
print "Type the filename again:"
file_again = raw_input(">")
txt_again = open(file_again)
print txt_again.read()
whwu@master:~/script/python/LPTHW> python ex15.py ex15_sample.txt
Here's your file 'ex15_sample.txt':
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.
Type the filename again:
>ex15_sample.txt
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.
练习16
? close – 关闭文件。跟你编辑器的 文件->保存.. 一个意思。
? read – 读取文件内容。你可以把结果赋给一个变量。
? readline – 读取文本文件中的一行。
? truncate – 清空文件,请小心使用该命令。
? write(stuff) – 将stuff 写入文件。
open/文件操作
f=open('/tmp/hello','w')
#open(路径+文件名,读写模式)
#读写模式:r只读,r+读写,w新建(会覆盖原有文件),a追加,b二进制文件.常用模式
如:'rb','wb','r+b'等等
读写模式的类型有:
rU 或 Ua 以读方式打开, 同时提供通用换行符支持 (PEP 278)
w 以写方式打开,
a 以追加模式打开 (从 EOF 开始, 必要时创建新文件)
r+ 以读写模式打开
w+ 以读写模式打开 (参见 w )
a+ 以读写模式打开 (参见 a )
rb 以二进制读模式打开
wb 以二进制写模式打开 (参见 w )
ab 以二进制追加模式打开 (参见 a )
rb+ 以二进制读写模式打开 (参见 r+ )
wb+ 以二进制读写模式打开 (参见 w+ )
ab+ 以二进制读写模式打开 (参见 a+ )
whwu@master:~/script/python/LPTHW> cat ex16.py
from sys import argv
script,filename = argv
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C(^C)."
print "If you do want that, hit return."
raw_input("?")
print "Opening the file..."
target = open(filename, 'w') # 打开文件,以写模式打开,会覆盖原来内容
print "Truncating the file. Goodbye!"
target.truncate()
print "Now I'm going to ask you for three lines."
line1 = raw_input("line 1:")
line2 = raw_input("line 2:")
line3 = raw_input("line 3:")
print "I'm going to write these to the file."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print "And finally, we close it."
target.close()
whwu@master:~/script/python/LPTHW> cat test.txt
To all the people out there.
I say I don't like my hair.
I need to shave it off
whwu@master:~/script/python/LPTHW> python ex16.py test.txt
We're going to erase 'test.txt'.
If you don't want that, hit CTRL-C(^C).
If you do want that, hit return.
?
Opening the file...
Truncating the file. Goodbye!
Now I'm going to ask you for three lines.
line 1:haha
line 2:baa
line 3:jj
I'm going to write these to the file.
And finally, we close it.
whwu@master:~/script/python/LPTHW> cat test.
cat: test.: No such file or directory
whwu@master:~/script/python/LPTHW> cat test.txt
haha
baa
jj
练习17
whwu@master:~/script/python/LPTHW> cat ex17.py
from sys import argv
from os.path import exists # exists。这个命令将文件名字符串作为参数,如果文件存在的话,它将返回 True,否则将返回 False。
script, from_file, to_file = argv
print "Copy from %s to %s" % (from_file, to_file)
# we could do these two on one line too, how?
in_file = open (from_file)
indata = in_file.read()
print "The input file is %d bytes long" % len(indata)
print "Does the output file exist? %r" % exists(to_file)
print "Ready, hit RETURN to continue, CTRL-C to abort."
raw_input() # 直接从键盘接受命令
out_file = open(to_file, 'w')
out_file.write(indata)
print "Alright, all done."
out_file.close()
in_file.close()
whwu@master:~/script/python/LPTHW> python ex17.py test.txt copied.txt
Copy from test.txt to copied.txt
The input file is 12 bytes long
Does the output file exist? False
Ready, hit RETURN to continue, CTRL-C to abort.
Alright, all done.
练习18
whwu@master:~/script/python/LPTHW> cat ex18.py
# this one is like your scripts with argv
def print_two(*args):
arg1,arg2 = args
print "arg1: %r, arg2: %r" % (arg1, arg2)
# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
print "arg1: %r, arg2: %r" % (arg1, arg2)
# this just takes one argument
def print_one(arg1):
print "arg1: %r" % arg1
# this one takes no arguments
def print_none():
print "I got nothing."
print_two("Zed", "Shaw")
print_two_again("Zed","Shaw")
print_one("First!")
print_none()
whwu@master:~/script/python/LPTHW> python ex18.py
arg1: 'Zed', arg2: 'Shaw'
arg1: 'Zed', arg2: 'Shaw'
arg1: 'First!'
I got nothing.
练习19
whwu@master:~/script/python/LPTHW> cat ex19.py
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "You have %d cheese!" % cheese_count
print "You have %d boxes of crackers!" % boxes_of_crackers
print "Man that's enough for a party!"
print "Get a blanket.\n"
print "We can just give the function numbers directly:"
cheese_and_crackers(20, 30)
print "OR, we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
print "We can even do math inside too:"
cheese_and_crackers(10 + 20, 5 + 6)
print "And we can combine the two, variables and math:"
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
whwu@master:~/script/python/LPTHW> python ex19.py
We can just give the function numbers directly:
You have 20 cheese!
You have 30 boxes of crackers!
Man that's enough for a party!
Get a blanket.
OR, we can use variables from our script:
You have 10 cheese!
You have 50 boxes of crackers!
Man that's enough for a party!
Get a blanket.
We can even do math inside too:
You have 30 cheese!
You have 11 boxes of crackers!
Man that's enough for a party!
Get a blanket.
And we can combine the two, variables and math:
You have 110 cheese!
You have 1050 boxes of crackers!
Man that's enough for a party!
Get a blanket.
练习20
whwu@master:~/script/python/LPTHW> cat ex20.py
from sys import argv
script,input_file = argv
def print_all(f):
print f.read()
def rewind(f):
f.seek(0)
def print_a_line(line_count,f):
print line_count,f.readline()
current_file = open(input_file)
print "First let's print the whole file:\n"
print_all(current_file)
print "Now let's rewind, kind of like a tape."
rewind(current_file)
print "Let's print three lines:"
current_line = 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
whwu@master:~/script/python/LPTHW> python ex20.py test.txt
First let's print the whole file:
123456789
222222222
333333333
444444444
555555555
Now let's rewind, kind of like a tape.
Let's print three lines:
1 123456789
2 222222222
3 333333333
print_all 和其它函数里的 f 是什么?
和 Ex 18 里的一样, f 只是一个变量名而已,不过在这里它指的是一个文件。Python 里的文件
就和老式磁带机,或者 DVD 播放机差不多。它有一个用来读取数据的“磁头”,你可以通过这
个“磁头”来操作文件。每次你运行 f.seek(0) 你就回到了文件的开始,而运行
f.readline() 则会读取文件的一行,然后将“磁头”移动到 \n 后面。后面你会看到更详细
的解释。
问什么文件里会有间隔空行?
readline() 函数返回的内容中包含文件本来就有的 \n,而 print 在打印时又会添加一个
\n,这样一来就会多出一个空行了。解决方法是在 print 语句结尾加一个逗号 ,,这样 print 就
不会把它自己的 \n 打印出来了。
为什么 seek(0) 没有把 current_line 设为 0?
首先 seek() 函数的处理对象是 字节 而非行,所以 seek(0) 只是转到文件的 0 byte,也就
是第一个 byte 的位置。其次, current_line 只是一个独立变量,和文件本身没有任何关系,
我们只能手动为其增值。
file.seek()方法标准格式是:seek(offset,whence=0)
offset:开始的偏移量,也就是代表需要移动偏移的字节数
whence:给offset参数一个定义,表示要从哪个位置开始偏移;0代表从文件开头开始算起,1代表从当前位置开始算起,2代表从文件末尾算起。
whwu@master:~/script/python/LPTHW> cat test2.txt
123456789
whwu@master:~/script/python/LPTHW> python
Python 2.6.6 (r266:84292, Jul 23 2015, 15:22:56)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-11)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> x = file('test2.txt', 'r')
>>> x.seek(3)
>>> x.tell()
3
>>> x.seek(4)
>>> x.tell()
4
>>> x.seek(1, 4)
>>> x.seek(-1, 2)
>>> x.tell()
9
>>> x.seek(-4, 2)
>>> x.tell()
6
>>> x.seek(0,0)
>>> x.tell()
0
练习21
whwu@master:~/script/python/LPTHW> cat ex21.py
def add(a, b):
print "ADDING %d + %d" % (a, b)
return a + b
def subtract(a, b):
print "SUBTRACTING %d - %d" % (a, b)
return a - b
def multiply(a, b):
print "MULTIPLY %d * %d" % (a, b)
return a * b
def divide(a, b):
print "DIVIDING %d / %d" % (a, b)
return a / b
print "Let's do some math with just functions!"
age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)
print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)
# A puzzle for the extra credit, type it in anyway.
print "Here is a puzzle."
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
print "That becomes:", what, "Can you do it by hand?"
whwu@master:~/script/python/LPTHW> python ex21.py
Let's do some math with just functions!
ADDING 30 + 5
SUBTRACTING 78 - 4
MULTIPLY 90 * 2
DIVIDING 100 / 2
Age: 35, Height: 74, Weight: 180, IQ: 50
Here is a puzzle.
DIVIDING 50 / 2
MULTIPLY 180 * 25
SUBTRACTING 74 - 4500
ADDING 35 + -4426
That becomes: -4391 Can you do it by hand?
whwu@master:~/script/python/LPTHW> cat ex21plus.py
def math(a, b, c, d):
print "ADDING %f + %f / %f - %f" % (a, b, c, d)
return a + b / c - d
a = float(raw_input("a:"))
b = float(raw_input("b:"))
c = float(raw_input("c:"))
d = float(raw_input("d:"))
answer = math(a, b, c, d)
print "The answer is %.2f" % answer
whwu@master:~/script/python/LPTHW> python ex21plus.py
a:12
b:2
c:4
d:5
ADDING 12.000000 + 2.000000 / 4.000000 - 5.000000
The answer is 7.50
练习24
whwu@master:~/script/python/LPTHW> cat ex24.py
print "Let's practice everything."
print 'You\'d need to know \'bout escapes with \\ that d \n newlines and \t tabs.'
poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
"""
print "----------"
print poem
print "----------"
five = 10 - 2 + 3 - 6
print "This should be five : %s" % five
def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates
start_point = 10000
beans, jars, crates = secret_formula(start_point)
print "With a starting point of %d" % start_point
print "We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates)
start_point = start_point / 10
print "We can also do that this way:"
print "We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point) #这是函数的工作原理。记住函数内部的变量都是临时的,当你的函数返回以后,返回值可以被赋予
#一个变量。我这里是创建了一个新变量,用来存放函数的返回值。
whwu@master:~/script/python/LPTHW> python ex24.py
Let's practice everything.
You'd need to know 'bout escapes with \ that d
newlines and tabs.
----------
The lovely world
with logic so firmly planted
cannot discern
the needs of love
nor comprehend passion from intuition
and requires an explanation
where there is none.
----------
This should be five : 5
With a starting point of 10000
We'd have 5000000 beans, 5000 jars, and 50 crates.
We can also do that this way:
We'd have 500000 beans, 500 jars, and 5 crates.
练习25
whwu@master:~/script/python/LPTHW> cat ex25.py
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)
def print_first_word(words):
"""Prints the first word after popping it off."""
word = words.pop(0)
print word
def print_last_word(words):
"""Prints the last word after popping it off."""
word = words.pop(-1)
print word
def sort_sentence(sentence):
"""Take in a full sentence and returns the sorted words."""
words = break_words(sentence)
return sort_word(words)
def print_first_and_last(sentence):
"""Prints the first and last words of the sentence."""
words = break_words(sentence)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
"""Sorts the words then prints the first and last one."""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
whwu@master:~/script/python/LPTHW> python
Python 2.6.6 (r266:84292, Jul 23 2015, 15:22:56)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-11)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import ex25
>>> sentence = "All good things come to those who wait."
>>> words = ex25.break_words(sentence)
>>> words
['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.']
>>> sorted_words = ex25.sort_words(words)
>>> sorted_words
['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']
>>> ex25.print_first_word(words)
All
>>> ex25.print_last_word(words)
wait.
>>> words
['good', 'things', 'come', 'to', 'those', 'who']
>>>
>>> ex25.print_first_word(sorted_words)
All
>>> ex25.print_last_word(sorted_words)
who
>>> sorted_words = ex25.sort_sentence(sentence)
>>> sorted_words
['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']
>>> ex25.print_first_and_last(sentence)
All
wait.
>>> ex25.print_first_and_last_sorted(sentence)
All
who
练习28 布尔表达式
whwu@master:~> python
Python 2.6.6 (r266:84292, Jul 23 2015, 15:22:56)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-11)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> True and True
True
>>> False and True
False
>>> 1 == 1 and 2 == 1
False
>>> "test" == "test"
True
>>> 1 == 1 or 2 != 1
True
>>> True and 1 == 1
True
>>> False and 0 != 0
False
>>> True or 1 == 1
True
>>> "test" == "testing"
False
>>> 1 != 0 and 2 == 1
False
>>> "test" != "testing"
True
>>> "test" == 1
False
>>> not (True and False)
True
>>> not (1 == 1 and 0 != 1)
False
>>> not ( 10 == 1 or 1000 == 1000 )
False
>>> not ( 1 != 10 or 3 == 4)
False
>>> not ( "testing" == "testing" and "Zed" == "Cool Guy" )
True
>>> 1 == 1 and (not("testing" == 1 or 1== 0))
True
>>> "chunky" == "bacon" and (not (3 == 4 or 3 == 3))
False
>>> 3 == 3 and (not ("testing" == "testing" or "Python" == "Fun"))
False
练习29
whwu@master:~/script/python/LPTHW> python ex29.py
Too many cats! The world is doomed!
The world is dry!
People are greater than or equal to dogs.
People are less than or equal to dogs.
People are dogs.
whwu@master:~/script/python/LPTHW> cat ex29.py
people = 20
cats = 30
dogs = 15
if people < cats:
print "Too many cats! The world is doomed!"
if people > cats:
print "Not many cats! The world is saved!"
if people < dogs:
print "The world is drooled on!"
if people > dogs:
print "The world is dry!"
dogs += 5
if people >= dogs:
print "People are greater than or equal to dogs."
if people <= dogs:
print "People are less than or equal to dogs."
if people == dogs:
print "People are dogs."
练习30
people = 20
cats = 30
dogs = 15
if people < cats:
print "Too many cats! The world is doomed!"
if people > cats:
print "Not many cats! The world is saved!"
if people < dogs:
print "The world is drooled on!"
if people > dogs:
print "The world is dry!"
dogs += 5
if people >= dogs:
print "People are greater than or equal to dogs."
if people <= dogs:
print "People are less than or equal to dogs."
if people == dogs:
print "People are dogs."
练习31
whwu@master:~/script/python/LPTHW> python ex31.py
You enter a dark room with two doors. Do you go through door #1 or door #2?
> 1
There's a giant bear here eating a cheese cake. What do you do?
1.Take the cake.
2.Scream at the bear.
> 2
The bear eats your legs off. Good job!
whwu@master:~/script/python/LPTHW> python ex31.py
You enter a dark room with two doors. Do you go through door #1 or door #2?
> 2
You stare into the endless abyss at Cthulhu's retina.
1. Blueberries.
2. Yellow jacket clothespins.
3. Understanding revolvers yelling melodies.
> 1
Your body survives powered by a mind of jello. Good job!
whwu@master:~/script/python/LPTHW> cat ex31.py
print "You enter a dark room with two doors. Do you go through door #1 or door #2?"
door = raw_input("> ")
if door == "1":
print "There's a giant bear here eating a cheese cake. What do you do?"
print "1.Take the cake."
print "2.Scream at the bear."
bear = raw_input("> ")
if bear == "1":
print "The bear eats your face off. Good Job!"
elif bear == "2":
print "The bear eats your legs off. Good job!"
else:
print "Well, doing %s is probably better. Bear runs away." % bear
elif door == "2":
print "You stare into the endless abyss at Cthulhu's retina."
print "1. Blueberries."
print "2. Yellow jacket clothespins."
print "3. Understanding revolvers yelling melodies."
insanity = raw_input("> ")
if insanity == "1" or insanity == "2":
print "Your body survives powered by a mind of jello. Good job!"
else:
print "You stumble around and fall on a knife and die. Good job!"
练习32
whwu@master:~/script/python/LPTHW> cat ex32.py
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'qarters']
# this first kind of for-loop goes through a list
for number in the_count:
print "This is count %d" % number
# same as above
for fruit in fruits:
print "A fruit of type: %s" % fruit
# also we can go through mixed lists too
# notice we have to use %r since we don't know what's in it
for i in change:
print "I got %r" % i
# we can also build lists, first start with an empty one
elements = []
# then use the range function to do 0 to 5 counts
for i in range(0, 6):
print "Adding %d to the list." % i
# append is a function that lists understand
elements.append(i)
# now we can print them out too
for i in elements:
print "Element was:%d" % i
whwu@master:~/script/python/LPTHW> python ex32.py
This is count 1
This is count 2
This is count 3
This is count 4