Thursday, November 8, 2018

More while loops

Here is a modified version of the grade averaging program

def getGrade():
    grade=float(input("Enter a grade: "))
    return grade

def storeGrades():
    grades=[]
    grade=0
    print ("Enter grades. -1 to exit")
    #this is an example of a sentinal loop
    while grade >= 0:
        grade=getGrade()
        if grade <0:
            break
        grades.append(grade)
        
    print (grades)
    return grades

def getAverage():
    gradeList=storeGrades()
    avg = 0
    total=0
    for g in range(len(gradeList)):
        total += gradeList[g]
    avg=total / len(gradeList)
    return avg

def display():
    avg=getAverage()
    
    print ("the average grade is", avg)

def main():
    display()

main()

Here are the other two while loops, while True and while quit=no

while True:
    print ('Hello')
    exit = input("quit y/n")
    if exit=='y':
        break
print ('loop done')

quit='n'
while quit == 'n':
    print ('Hello')
    quit = input("quit y/n")
    quit=quit.lower()
print ('Loop2 done')

No comments:

Post a Comment