Eric Yih's Blog

Do what you like, like what you do.
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

练习程序

Posted on 2008-03-05 21:58  Eric Yih  阅读(265)  评论(0)    收藏  举报
 1# Fig. 3.10: fig03_10.py
 2# Class average program with counter-controlled repetition
 3
 4#Initialization phase
 5total = 0       # sum of grades
 6counter = 0     # number of grades entered
 7
 8# processing phase
 9while counter < 10:            # loop 10 times
10    grade = raw_input("Please enter grade of student:"# get one grade
11    grade = int(grade)            # convert string to an integer
12    total = total + grade
13    counter = counter + 1
14
15print "total:", total
16print "counter:", counter
17
18# termination phase
19average = total / counter    # integer division
20print "Class average is: ", average

 1# Fig. 3.11: fig03_11.py
 2# Class average program with sentinel-controlled repetition
 3
 4#Initialization phase
 5total = 0   # sum of grades
 6counter = 0 # number of grades entered
 7
 8grade = raw_input("Please enter grade of student:")
 9if grade == "" or grade =="end":
10    print "no grades were entered!"
11else:
12    grade = int(grade)
13    total = total + grade
14    counter = counter + 1
15    while grade <> "end":
16        grade = raw_input("Please enter grade of student:")
17        if grade <> "end":
18            grade = int(grade)
19            total = total + grade
20            counter = counter + 1
21
22    print "total:", total
23    print "counter:", counter
24    average = total / counter
25    print "Class average is: ", average