150 likes | 259 Views
Mastery Objective:. Students will understand how to use while loops in computer programming. Agenda.
E N D
Mastery Objective: Students will understand how to use while loops in computer programming
Agenda • If-else and if-elif-else assignment due tomorrow (Wednesday) by the end of class with no scheduled in class time. If you haven’t finished the assignment, plan to stay after or come in early to finish the assignment. • Notes: While loops • Programming assignments
While loops Basic principle: • While something is true, repeat something Basic structure: while response != “Because.”: response = raw_input(“Why? “)
Similarities and differences between if and while structure • In both structures, if the condition is true, the block is executed. • What is different: In the while structure, the block is executed until it is false.
Sentry Variable • Often, sentry variables control the while loop • response variable in example code while response != “Because.”: response = raw_input(“Why? “) • Must be intialized prior to use, usually right before while loop. Usually initialized to empty variable response = “ “
example response = “” while response !=“No”: response = “raw_input(“Try again!”): print “All done!”
Infinite Loop • Loop that never ends. • Example counter = 0 while counter <=10 print counter Forgot to increase counter variable Counter +=1
How to Stop an Infinity Loop • Control key +C
Setting values as true or false When using numbers: 0 is false other numbers are true if money: print “Thank you!” else: print “I am sorry there are no seats available.”
Intentional Infinity loops • There is a place for infinite loops Count = 0 While Ture: count +=1 if count >10: break (breaks loop) if count ==5; continue (jump back to top of loop) print count
Break and Continue • Used in any type of loop • Should be used sparingly
Using compound conditions • Uses logical operators
not Logical Operator Example username = “ “ while not username: username = raw_input(“Username: “) Loop continues to ask for a username until the user enters something
And Logical Operator elif username == “S. Meier” and password ==“civilization”:
Or Logical operator example elif username==“guest” or password ==“guest”: print “Welcome, guest.”