Tuesday, November 6, 2018

Indefinite Loops

First take

def main():
    #basic for loop (definite loops)
    for i in range(10):
       print("h1, vote")

    #indefinite loop
    total=0
    avg=0
    grade=0
    counter =0
    while grade >=0:
        grade=float(input("Enter grade -1 to exit: "))
        if grade ==-1:
            break
        total += grade
        #total = total + grade
        counter += 1
        print(counter)
    
    avg = total/counter
   
    print ("the average score is", avg)


main()

Menu loop

def menu():
    print ("Type the menu number for your option.")
    choice=0
    while choice !=5:
        print("1: birthday:")
        print("2: christmas: ")
        print("3: new years")
        print('4: thanksgiving')
        print('5: Exit')
        choice=int(input("Enter your choice"))

        if choice != 5:
            managechoices(choice)
        
def managechoices(choice):
    if choice==1:
        birthday()
    elif choice == 2:
        christmas()
    elif choice==3:
        newyears()
    else:
        thanksgiving()

def birthday():
    print("happy birthday")

def christmas():
    print ("merry christmas")

def newyears():
    print ("happy new years")

def thanksgiving():
    print( "I ate way too much")

def main():
    menu()

main()

      

Another example with grades and average using functions

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:
        grades.append(grade)
        grade=getGrade()
    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()

No comments:

Post a Comment