RepetitionExamplesTypes of LoopswhileSlide 5Sentinel-controlledInput ValidationforInfinite LoopsSlide 10AlternativeExercisesProblemNested LoopsSlide 15Slide 16Slide 17ExerciseSlide 19RepetitionExamples•When is repetition necessary/useful?Types of Loops•Counting loop–Know how many times to loop•Sentinel-controlled loop–Expect specific input value to end loop•Endfile-controlled loop–End of data file is end of loop•Input validation loop–Valid input ends loop•General conditional loop–Repeat until condition is metwhilewhile condition:statementsx=1while x < 10:print xx = x + 1whilex=1 #initialization of control variablewhile x < 10: #conditionprint x #task to be repeatedx = x + 1 #update - VERY VERY IMPORTANTSentinel-controllednum = input("Enter number - 0 to quit: ")while num != 0: print “You entered “, num num = input("Enter number - 0 to quit: ")•Which is the control variable?Input Validationnum = input("Enter number between 0 and 100: ")while num < 0 or num > 100: #a more complex condition print "Invalid input" num = input("Enter number between 0 and 100: ")forfor x in range(10): print xmystring = "CS is cool!"for c in mystring: print c•Loop iterates over a list•Initialization and update happen automaticallyInfinite Loops•If your program “hangs” – you probably forgot to update your control variablex=1while x==1:print “x is 1”•Why is this bad?x=1end_value=10while x != end_value:#do somethingInfinite Loops•Why is this bad?x=1end_value=10while x != end_value:#do something x *= 2x=1end_value=10while x < end_value: #better#do somethingAlternativewhile 1:num = input(“Enter a number - 0 to quit: “)if num == 0:break #combines intialization and updateExercises1. Write a while loop that prints all of the even numbers between 1 and 100.•Create two versions of this loop, one that uses an if statement and one that does not.2. Write a program that uses the module random to select a random number between 1 and 10 (example below) and asks the user to repeatedly enter a number until he/she has guessed the random number.#import the module randomimport random#call the randint function passing in the range num = random.randint(1, 10)Problem•Print•The only print statements you can use are the following:–print “*”, #the comma prevents the \n–print***************Nested Loops#print a rectangle of stars#3 times#print a line of starsNested Loops#print a rectangle of starsx=1while x <= 3:#print a line of stars#print a line of starsy=1while y<=3:print “*”,Nested Loops#print a rectangle of starsx=1while x <= 3:#print a line of starsy=1while y<=3:print “*”,#DONE?Nested Loops#print a rectangle of starsx=1while x <= 3:#print a line of starsy=1while y<=3:print “*”,y+=1printx+=1Exercise1. Design a program which prompts the user for a number of rows between 0 and 10 and prints the following pattern:**********Exercise2. Design a program which prompts the user for a number of rows between 0 and 10 and prints the following pattern:** ** * ** * *
View Full Document