Using the break statement to avoid repeating code in the class-average program. : Break « Language Basics « Python






Using the break statement to avoid repeating code in the class-average program.

Using the break statement to avoid repeating code in the class-average program.

total = 0          # sum of grades
gradeCounter = 0   # number of grades entered

while 1:
   grade = raw_input( "Enter grade, -1 to end: " )   
   grade = int( grade )

   # exit loop if user inputs -1
   if grade == -1:
      break

   total += grade
   gradeCounter += 1
   
if gradeCounter != 0:
   average = float( total ) / gradeCounter
   print "Class average is", average
else:
   print "No grades were entered"


           
       








Related examples in the same category

1.Using the break statement in a for structure.Using the break statement in a for structure.
2.Break and continue Statements, and else Clauses on LoopsBreak and continue Statements, and else Clauses on Loops
3.While with breakWhile with break