# while loop index = 1 while index <= 10: print("while loop with controlled condition : " + str(index)) index += 1 # or index = index + 1 index = 1 while True: if index > 10: break; print("while loop with bad controlled condition : " + str(index)) index += 1 while input("Do you want to continue (Y/N) ? ") == "Y": print("let's continue") done = "" while done != "quit": print("let's continue -- not done yet") done = input("Continue ? (type quit to quit) ") experts = ["wear", "no", "no", "wear", "wear", "no"] ctr = 0 while ctr < len(experts): expert = experts[ctr] if expert == "wear": print("shake") else: print("no") ctr += 1 i = 5 while i > 0: print(i * i * i) i -= 1 # This example illustrates a situation when # a while loop results in an infinite loop. # Notice the infinite variable (i.e., counter of the loop) # and the condition next the a while keyword # # Be careful when setting up the condition and whether to increment/decrement the counter # # infinite = 1 # while infinite > -1: # print(infinite) # infinite +=1 # value = 5 while value >= 0 and value <= 10: value = int(input("Enter a number less than 0 or greater than 10 : ")) value2 = -1 while value2 <= -1 or value2 > 10: # this is the bad case value2 = int(input("Give me a number between 0 and 10: ")) list_of_animals = ["dog", "cat", "fish"] cnt = 0 while len(list_of_animals) > 0: print(list_of_animals[cnt]) list_of_animals.remove(list_of_animals[cnt]) # try comment this line, run, and see what happen ## exercise (while loop) ## consider when does the loop stop number_of_courses = int(input("Enter the number of courses : " )) cnt = 1 while cnt <= number_of_courses: letter = "" grades = input("Enter 3 exams grade : ") list_of_grades = grades.split() print(list_of_grades) print(list_of_grades[0]) grade_average = (float(list_of_grades[0]) + float(list_of_grades[1]) + float(list_of_grades[2])) / 3 # determine a letter grade and store it for later use if grade_average >= 98: letter = "A+" elif grade_average >= 93: letter = "A" elif grade_average >= 90: letter = "A-" elif grade_average >= 87: letter = "B+" elif grade_average >= 83: letter = "B" elif grade_average >= 80: letter = "B-" elif grade_average >= 77: letter = "C+" elif grade_average >= 73: letter = "C" elif grade_average >= 70: letter = "C-" elif grade_average >= 67: letter = "D+" elif grade_average >= 63: letter = "D" elif grade_average >= 60: letter = "D-" else: letter = "F" # Why should we use if-elif-elif... instead of if-if-if..., though both ways work? print(format(grade_average, ".3f") + ", " + letter) cnt += 1 # why do we need to increment cnt?