python 核心编程课后练习(chapter 2)

2-4

1 #2-4(a)
2 print "enter a string"
3 
4 inputstring = raw_input()
5 
6 print"the string is: ", inputstring
View Code
1 #2-4(b)
2 print "enter a number:"
3 
4 num = raw_input()
5 
6 print "the number is: ", int(num)
View Code

2-5

#2-5(a)
i = 0
while i<=10:
  print i
  i+=1
View Code
1 # 2-5(b)
2 for i in range(11)
3   print i
View Code

2-6

 1 #2-6
 2 print "please input a number:"
 3 
 4 num = raw_input()
 5 
 6 if int(num) < 0:
 7   print" a negative number!!!"
 8 elif int(num) > 0:
 9   print "a positive number!!!"
10 else:
11   print "zero"
View Code

2-7

1 #2-7
2 print "please input a string:"
3 
4 inputstring = raw_input()
5 
6 while 
7 
8 for e in inputstring:
9   print e
View Code

2-8

 1 #2-8
 2 print "please input a string:"
 3 
 4 inputstring = raw_input()
 5 i = 0
 6 while i<len(inputstring):
 7   print inputstring[i],
 8   i+=1
 9 print  
10 for e in inputstring:
11   print e
View Code

2-9

 1 #2-9
 2 arrary = [1, 2, 3, 4, 4]
 3 
 4 sum = 0
 5 for e in arrary:
 6   sum += e
 7 
 8 ev = float(sum)/float(len(arrary))
 9 
10 print ev
View Code

2-10

 1 #2-10
 2 print "please input a number between 1-100"
 3 
 4 num = int(raw_input())
 5 
 6 while num<1 or num >100:
 7   print "please input again:"
 8   num = int(raw_input())
 9 
10 print "num is valid
View Code

2-11

 1 #2-11
 2 # to support cn
 3 #encoding: utf-8
 4 print """(1)取五個數的和"""
 5 print "(2)取五個數的平均值..."
 6 print "(x)退出"
 7 def sum(arrary):
 8   s = 0
 9   for e in arrary:
10     s += e
11   return s  
12 
13 def average(arrary):
14   if len(arrary) == 0:
15     return 0
16   else:  
17     return float(sum(arrary))/float(len(arrary))
18 
19 arr = [0, 1, 2, 3, 3]
20 
21 while True:
22  opt = raw_input()
23  if opt == 'x':
24    print "退出"
25    break
26  elif int(opt) == 1:
27    print "the sum of the arrary is :", sum(arr)  
28  elif int(opt) == 2:
29    print "the average of the arrary is:", average(arr)
30  else:
31    print "please input again" 
View Code

2-14

 1 #2-14
 2 #sort
 3 
 4 print "enter three number:"
 5 
 6 print "the first is:"
 7 a = raw_input()
 8 print "the second is:"
 9 b = raw_input()
10 print "the third is:"
11 c = raw_input()
12 
13 print "after sort for low to high:"
14 
15 if a > b:
16    tmp = a
17    a = b
18    b = tmp
19 if a > c:
20    tmp = a
21    a = c
22    c = tmp
23    
24 if b > c:
25   tmp = b
26   b = c
27   c = tmp
28 
29 print a, b, c  
30 
31  
32 print "after sort for high to low:"
33 
34 if a < b:
35    tmp = a
36    a = b
37    b = tmp
38 if a < c:
39    tmp = a
40    a = c
41    c = tmp
42    
43 if b < c:
44   tmp = b
45   b = c
46   c = tmp
47 
48 print a, b, c  
View Code
原文地址:https://www.cnblogs.com/huking/p/3226538.html