loops
DESCRIPTION
Loops. Introduction to Computing Science and Programming I. Loops. To this point you’ve learned how to write code that executes from top to bottom as well as how to use conditional (if) statements to select or skip parts of the code. - PowerPoint PPT PresentationTRANSCRIPT
LoopsLoopsIntroduction to Computing Introduction to Computing Science and Programming IScience and Programming I
LoopsLoops To this point you’ve learned how to write To this point you’ve learned how to write
code that executes from top to bottom as code that executes from top to bottom as well as how to use conditional (if) statements well as how to use conditional (if) statements to select or skip parts of the code.to select or skip parts of the code.
Loop structures allow the programmer to Loop structures allow the programmer to have sections of code executed multiple have sections of code executed multiple times. This allows many programs that times. This allows many programs that couldn’t be written without loops as well as couldn’t be written without loops as well as making many programs that can be written making many programs that can be written without loops, more simple.without loops, more simple.
Algorithms With LoopsAlgorithms With Loops Before getting into how to write the Before getting into how to write the
loops themselves, let’s look at some loops themselves, let’s look at some problems that require loops.problems that require loops.
Prime Number AlgorithmPrime Number Algorithm Here’s an algorithm we looked at previously to test whether Here’s an algorithm we looked at previously to test whether
a user input number is prime.a user input number is prime.
set divisor to 2set divisor to 2write “Enter an integer greater than 2”write “Enter an integer greater than 2”read userNumberread userNumberrepeat while divisorrepeat while divisor22 < userNumber < userNumber if userNumber % divisor is equal to 0if userNumber % divisor is equal to 0 write “The number is not prime, it is divisible by write “The number is not prime, it is divisible by
:”:” write divisorwrite divisor exit programexit program set divisor to divisor +1set divisor to divisor +1write “The number is prime.”write “The number is prime.”
Prime Number AlgorithmPrime Number Algorithm Notice that we have a section of the Notice that we have a section of the
algorithm we want to repeatalgorithm we want to repeatrepeat while divisorrepeat while divisor22 < userNumber < userNumber if userNumber % divisor is equal to 0if userNumber % divisor is equal to 0 write “The number is not prime, it is divisible by :”write “The number is not prime, it is divisible by :” write divisorwrite divisor exit programexit program set divisor to divisor +1set divisor to divisor +1
The algorithm wants to repeat the The algorithm wants to repeat the indented section of code while (divisorindented section of code while (divisor22 < < userNumber)userNumber)
AlgorithmsAlgorithms A couple simpler algorithms that will need to repeat code.A couple simpler algorithms that will need to repeat code. FactorialFactorial
n! = n * (n-1) * (n-2) *…*2 * 1n! = n * (n-1) * (n-2) *…*2 * 1 5! = 5 * 4 * 3 * 2 * 1 = 1205! = 5 * 4 * 3 * 2 * 1 = 120
AlgorithmAlgorithmwrite “Enter a nonnegative integer:”read nset factorial to 1
do this for i equal to each number from 1 to n:set factorial to factorial * i
write factorial
Notice the code that will be repeated, but this time it is stated Notice the code that will be repeated, but this time it is stated differently. Instead of repeat while this is true, it says do this this differently. Instead of repeat while this is true, it says do this this many times.many times.
A Couple More AlgorithmsA Couple More Algorithms Repeatedly prompting a user until they give Repeatedly prompting a user until they give
proper inputproper inputset number to 0set number to 0repeat while number < 1repeat while number < 1
write “Enter a positive integer: “write “Enter a positive integer: “read numberread number
Printing out the powers of 2Printing out the powers of 2write “How many powers of 2 should be printed?”write “How many powers of 2 should be printed?”read maxread maxset value to 1set value to 1do this max timesdo this max times write valuewrite value
set value to value * 2set value to value * 2
Two Kinds of LoopTwo Kinds of Loop while loopswhile loops
These are called indefinite loops because These are called indefinite loops because they are often used to repeat code without they are often used to repeat code without knowing how many times it will be repeated knowing how many times it will be repeated beforehand.beforehand.
for loopsfor loops These are called definite loops because they These are called definite loops because they
usually will repeat a set number of timesusually will repeat a set number of times
while Loopswhile Loops
while while conditioncondition::code blockcode block
Similar to an if statement, a while loop Similar to an if statement, a while loop is given a condition (boolean is given a condition (boolean expression). The code block associated expression). The code block associated with the while loop will repeat over and with the while loop will repeat over and over again until the condition becomes over again until the condition becomes false.false.
while Loopswhile Loops A simple example that prints the number 1 A simple example that prints the number 1
through 3.through 3.
num = 1num = 1while num <= 3:while num <= 3: print numprint num num = num + 1num = num + 1print “Finished”print “Finished”
When the while statement is reached the first time, num is When the while statement is reached the first time, num is 1 which is less than five. Therefore execution enters the 1 which is less than five. Therefore execution enters the code block and repeats the code block until num is greater code block and repeats the code block until num is greater than 5than 5
while Loopswhile Loops Unwinding the loopUnwinding the loop
To understand what’s going on we can ‘unwind’ the loopTo understand what’s going on we can ‘unwind’ the loopnum = 1num = 1while num <= 3:while num <= 3: print numprint num num = num + 1num = num + 1print “Finished”print “Finished”
num = 1num = 1 Check the condition, is num <=3? Yes, so enter the code blockCheck the condition, is num <=3? Yes, so enter the code block print numprint num num = num + 1 (num is 2)num = num + 1 (num is 2) Check the condition, is num <= 3? Yes, so repeat the code blockCheck the condition, is num <= 3? Yes, so repeat the code block print numprint num num = num + 1 (num is 3)num = num + 1 (num is 3) Check the condition, is num <= 3? Yes, so repeat the code blockCheck the condition, is num <= 3? Yes, so repeat the code block print numprint num num = num + 1 (num is 4)num = num + 1 (num is 4) Check the condition, is num <= 3? No, so skip the code blockCheck the condition, is num <= 3? No, so skip the code block print “Finished”print “Finished”
while Loopswhile Loops Remember that the condition is checked Remember that the condition is checked
before the block of code is executed for before the block of code is executed for the first time.the first time.
Therefore, the code in a while loop may Therefore, the code in a while loop may never be executed.never be executed.
You also need to make sure the condition You also need to make sure the condition eventually becomes false, if not you will eventually becomes false, if not you will have an infinite loop. The program will have an infinite loop. The program will never leave the while loop and never finishnever leave the while loop and never finish
while Loopswhile Loops
while loops are an easy way to while loops are an easy way to wait for proper input from the wait for proper input from the useruser
number = 0number = 0while number < 1:while number < 1:
number = int(raw_input(“Enter a positive number = int(raw_input(“Enter a positive integer: “))integer: “))
print “Your number is “ + str(number)print “Your number is “ + str(number)
for Loopsfor Loops For the time being all of the for loops we For the time being all of the for loops we
look at will look something like thislook at will look something like this
for x in range(5):for x in range(5):print xprint x
We’ll learn more general uses of it, but for We’ll learn more general uses of it, but for now the for statement will be of the formnow the for statement will be of the form
for for varnamevarname in range(..): in range(..): Here we just have the single statement Here we just have the single statement
‘print x’ inside the loop, but you have any ‘print x’ inside the loop, but you have any sized code block you likesized code block you like
range Functionrange Function range is a Python function that returns a list of numbersrange is a Python function that returns a list of numbers If you give range one argument, it returns a list of integers If you give range one argument, it returns a list of integers
starting at 0, ending at one less than the argumentstarting at 0, ending at one less than the argument range(4) = [0, 1, 2, 3]range(4) = [0, 1, 2, 3] range(10) = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]range(10) = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
You can also give range a beginning and ending number. You can also give range a beginning and ending number. The list starts at the first argument and ends at one less The list starts at the first argument and ends at one less than the second argument.than the second argument. range(1,5) = [1, 2, 3, 4]range(1,5) = [1, 2, 3, 4] range(-2,2) = [-2, -1, 0, 1]range(-2,2) = [-2, -1, 0, 1] range(0,4) = range(4)range(0,4) = range(4)
We will learn about the list data type and how to create our We will learn about the list data type and how to create our own lists laterown lists later
for Loopsfor Loops What the for loop does is assign the What the for loop does is assign the
values returned by range to the values returned by range to the variable one by one and executes the variable one by one and executes the code block for each valuecode block for each valuefor x in range(5):for x in range(5):
print xprint x
x will be assigned the 5 values in x will be assigned the 5 values in range, and those values will be printedrange, and those values will be printed
for Loopsfor Loops Unwinding a for loopUnwinding a for loop
for x in range(5):for x in range(5):print xprint x
Remember, range(5) = {0,1,2,3,4}Remember, range(5) = {0,1,2,3,4}
x=0 (first value in range(5))x=0 (first value in range(5)) print xprint x x=1 (second value in range(5))x=1 (second value in range(5)) print xprint x x=2 (third value in range(5))x=2 (third value in range(5)) print xprint x x=3 (fourth value in range(5))x=3 (fourth value in range(5)) print xprint x x=4 (final value in range(5))x=4 (final value in range(5)) print xprint x No more values remain in range(5) so we are finishedNo more values remain in range(5) so we are finished
for Loopsfor Loops You can just use the structure to repeat code a certain You can just use the structure to repeat code a certain
number of times, ignoring the value assigned to the number of times, ignoring the value assigned to the variable in the for statementvariable in the for statement
Printing out the powers of 2Printing out the powers of 2
max = int(raw_input("How many powers of 2 should be printed? max = int(raw_input("How many powers of 2 should be printed? "))"))
num = 1;num = 1;
for i in range(max):for i in range(max): print numprint num num = num * 2num = num * 2
Notice that the values in range(max) will be assigned to i, Notice that the values in range(max) will be assigned to i, but we don’t use i inside the loop. We’re just using the but we don’t use i inside the loop. We’re just using the structure to repeat the code block max times.structure to repeat the code block max times.
for Loopsfor Loops Unwinding a for loopUnwinding a for loop
Assume a user entered 3 in the last exampleAssume a user entered 3 in the last examplenum = 1num = 1for i in range(max): //max previously set to 3for i in range(max): //max previously set to 3
print numprint num num = num * 2num = num * 2
Remember, range(3) = {0,1,2}Remember, range(3) = {0,1,2}
i=0 (first value in range(3))i=0 (first value in range(3)) print num (num is 1)print num (num is 1) num = num * 2 (num is 2)num = num * 2 (num is 2) i=1 (second value in range(3))i=1 (second value in range(3)) print numprint num num = num * 2 (num is 4)num = num * 2 (num is 4) i=2 (third and last value in range(3))i=2 (third and last value in range(3)) print numprint num num = num * 2 (num is 8)num = num * 2 (num is 8) No values remain in range(3) so the loop is completeNo values remain in range(3) so the loop is complete
for Loopsfor Loops Factorial ExampleFactorial Example
n = int( raw_input("Enter a nonnegative integer: ") )n = int( raw_input("Enter a nonnegative integer: ") )factorial = 1factorial = 1for i in range(n):for i in range(n):
factorial = factorial * (i+1)factorial = factorial * (i+1)
print factorialprint factorial
for Loopsfor Loops range(n) returns {0,1,2…,n}, but you may range(n) returns {0,1,2…,n}, but you may
want to use the integers starting at 1want to use the integers starting at 1 Print the first 5 positive integersPrint the first 5 positive integers
for num in range(5):for num in range(5): print num+1print num+1
num is set to 0,1,2… but we offset it by one in num is set to 0,1,2… but we offset it by one in the for loop to get the numbers we desiredthe for loop to get the numbers we desired
We could also have used range(1,6) in this We could also have used range(1,6) in this casecase
for Loopsfor Loops Extending that ideaExtending that idea
Print the first 5 positive even numbersPrint the first 5 positive even numbersfor num in range(5):for num in range(5):
print 2*(num+1)print 2*(num+1)
Print the first 5 positive odd numbersPrint the first 5 positive odd numbersfor num in range(5):for num in range(5):
print 2*num + 1print 2*num + 1
Print the first 5 positive numbers squaredPrint the first 5 positive numbers squaredfor num in range(5):for num in range(5):
print num**2print num**2
Print the first 5 powers of 2Print the first 5 powers of 2for num in range(5):for num in range(5):
print 2**numprint 2**num
NestingNesting The code block inside a loop (or if The code block inside a loop (or if
structure) can contain loops (or if structure) can contain loops (or if structures) itself. This is called structures) itself. This is called nesting loops.nesting loops.
As you get into more complex As you get into more complex programs these nested structures programs these nested structures become commonplacebecome commonplace
NestingNesting Nested for loops to print a block of 0sNested for loops to print a block of 0s
for row in range(4):for row in range(4): for col in range(5):for col in range(5): print 0,print 0, print “”print “”
OutputOutput0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
If you put a comma at the end of a print statement If you put a comma at the end of a print statement ‘print 0,’ it will not go to the next line after printing‘print 0,’ it will not go to the next line after printing
NestingNesting Another nested for loop example that prints out Another nested for loop example that prints out
the coordinates (row,col) of each location in a the coordinates (row,col) of each location in a grid with (0,0) being the upper left-hand corner..grid with (0,0) being the upper left-hand corner..
for row in range(4):for row in range(4): for col in range(6):for col in range(6): print "(" +str(row) + "," + str(col) + ")",print "(" +str(row) + "," + str(col) + ")",
print “”print “”
Output:Output:(0,0) (0,1) (0,2) (0,3) (0,4) (0,5) (0,0) (0,1) (0,2) (0,3) (0,4) (0,5) (1,0) (1,1) (1,2) (1,3) (1,4) (1,5) (1,0) (1,1) (1,2) (1,3) (1,4) (1,5) (2,0) (2,1) (2,2) (2,3) (2,4) (2,5) (2,0) (2,1) (2,2) (2,3) (2,4) (2,5) (3,0) (3,1) (3,2) (3,3) (3,4) (3,5) (3,0) (3,1) (3,2) (3,3) (3,4) (3,5)
NestingNesting Another nested for loop example that prints out Another nested for loop example that prints out
the coordinates (row,col) of each location in a the coordinates (row,col) of each location in a grid.grid.
for row in range(4):for row in range(4): for col in range(6):for col in range(6): print "(" +str(row) + "," + str(col) + ")",print "(" +str(row) + "," + str(col) + ")",
print “”print “”
Remember that the inner for loop is run from Remember that the inner for loop is run from start to end every time the code block for the start to end every time the code block for the outer for loop is runouter for loop is run Each time one of the values in range(4) is assigned to Each time one of the values in range(4) is assigned to
row, every value in range(6) will be assigned to colrow, every value in range(6) will be assigned to col
NestingNesting Nested loops to find the average of different Nested loops to find the average of different
students gradesstudents grades
count = 0count = 0name = raw_input("Enter student's name, enter nothing to quit: ")name = raw_input("Enter student's name, enter nothing to quit: ")
while name!= "":while name!= "": count = count + 1count = count + 1 totalScore=0totalScore=0 for i in range(3):for i in range(3): totalScore=totalScore + int(raw_input("Assignment " + str(i+1) + " score: "))totalScore=totalScore + int(raw_input("Assignment " + str(i+1) + " score: ")) print name + "'s average is " + str(round(totalScore/3.0)) + "."print name + "'s average is " + str(round(totalScore/3.0)) + "." name = raw_input("Enter student's name, enter nothing to quit: ")name = raw_input("Enter student's name, enter nothing to quit: ")
print "You entered the grades of " + str(count) + " student(s)"print "You entered the grades of " + str(count) + " student(s)"
Deciding Which Control Structure Deciding Which Control Structure To UseTo Use
You have code that only needs to run You have code that only needs to run in certain situationsin certain situations
if statementif statement Absolute valueAbsolute value
num = int(raw_input(“Enter number: “))num = int(raw_input(“Enter number: “))if num < 0:if num < 0: num = -numnum = -numprint “Absolute value is “ + str(num)print “Absolute value is “ + str(num)
Deciding Which Control Structure Deciding Which Control Structure To UseTo Use
You have two chunks of code, one or the You have two chunks of code, one or the other of which should run every timeother of which should run every time
if – else structureif – else structurenum = int(raw_input(“Enter a number: “))num = int(raw_input(“Enter a number: “))if (num % 2) == 0:if (num % 2) == 0: print “You entered an even number.”print “You entered an even number.”else:else: print “You entered an odd number.”print “You entered an odd number.”
Deciding Which Control Structure Deciding Which Control Structure To UseTo Use
You have more than two chunks of code, with one You have more than two chunks of code, with one and only one of which that should run each time.and only one of which that should run each time.
if-elif-else structureif-elif-else structuretemp = int(raw_input(“Enter the temperature: “))temp = int(raw_input(“Enter the temperature: “))if temp > 25:if temp > 25: print “It is hot today.”print “It is hot today.”elif temp > 15:elif temp > 15: print “It is warm today.”print “It is warm today.”elif temp > 5:elif temp > 5: print “It is cool today.”print “It is cool today.”else:else: print “It is cold today.”print “It is cold today.”
Deciding Which Control Structure Deciding Which Control Structure To UseTo Use
You have code that needs to be repeatedYou have code that needs to be repeated for or while loopfor or while loop
There are many cases where either type of There are many cases where either type of loop can be used, but there are general loop can be used, but there are general rules.rules.
If you know how many times a loop is going If you know how many times a loop is going to repeat, usually a for loop is best.to repeat, usually a for loop is best.
You may only know the repetitions based on user You may only know the repetitions based on user input or some other variable.input or some other variable.
If you need to keep repeating something If you need to keep repeating something until some process is finished/goal is metuntil some process is finished/goal is met
In Class ExerciseIn Class Exercise Write a short program that reads some user Write a short program that reads some user
entered text, and outputs whether there is a entered text, and outputs whether there is a repeated character in the string. e.g. “aa”, repeated character in the string. e.g. “aa”, “speed”, but not “banana”“speed”, but not “banana” if text is a variable containing a stringif text is a variable containing a string
len(text) tells you how many characters it haslen(text) tells you how many characters it has text[0] gives you the first character, text[1] the second and text[0] gives you the first character, text[1] the second and
text[len(text) – 1] the lasttext[len(text) – 1] the last
Write a short program that prints out an NxN Write a short program that prints out an NxN multiplication table where N is entered by the usermultiplication table where N is entered by the user If the user entered 3 the table should be.If the user entered 3 the table should be.
1 2 31 2 32 4 62 4 63 6 93 6 9
In Class ExerciseIn Class Exercise This could also be done with a while loopThis could also be done with a while loop
#Find a repeated character#Find a repeated character
text = raw_input("Enter text: ")text = raw_input("Enter text: ")found = False #will be set to true if we find a repeated found = False #will be set to true if we find a repeated
charactercharacter
for index in range(len(text)-1):for index in range(len(text)-1): if text[index] == text[index+1]:if text[index] == text[index+1]: print "Repeated character found: "+text[index]print "Repeated character found: "+text[index] found = Truefound = True
if not found:if not found: print "No repeats found"print "No repeats found"
In Class ExerciseIn Class Exercisesize = int(raw_input(“How many rows/colums? “))size = int(raw_input(“How many rows/colums? “))
for row in range(size):for row in range(size): for col in range(size):for col in range(size): print (row+1) * (col+1),print (row+1) * (col+1), printprint
We need to use row+1 and col+1 since we We need to use row+1 and col+1 since we want to start at 0, not 1want to start at 0, not 1
Remember that the comma at the end of Remember that the comma at the end of the print statement prevents it from the print statement prevents it from proceeding to the next lineproceeding to the next line
print without anything after ends the lineprint without anything after ends the line
In Class ExerciseIn Class Exercise What does the code print out?What does the code print out?
count = int(raw_input("Enter the max: "))count = int(raw_input("Enter the max: "))
for row in range(count):for row in range(count):line = ""line = ""for i in range(count-row-1):for i in range(count-row-1):
line = line + " “line = line + " “
for i in range(row+1):for i in range(row+1):line = line + str(i+1)line = line + str(i+1)
for i in range(row):for i in range(row):line = line + str(row-i)line = line + str(row-i)
print lineprint line
In Class ExerciseIn Class Exercise The outer loop is pretty clearly printing out one The outer loop is pretty clearly printing out one
line for each iteration, the inner loops are adding line for each iteration, the inner loops are adding text to that line.text to that line.
Take each inner loop individuallyTake each inner loop individuallyfor i in range(count-row-1):for i in range(count-row-1):
line = line + " “line = line + " “ Assume count is 5. For each value of row, this Assume count is 5. For each value of row, this
will add count-row-1 spaces. row will be assigned will add count-row-1 spaces. row will be assigned the values 0,1,2…count – 1the values 0,1,2…count – 1
Therefore, on the first line this adds count-1 Therefore, on the first line this adds count-1 spaces, count-2 on the second, … , and none on spaces, count-2 on the second, … , and none on the lastthe last
In Class ExerciseIn Class Exercisefor i in range(row+1):for i in range(row+1):line = line + str(i+1)line = line + str(i+1)
For each value of row this will add the For each value of row this will add the numbers 1,2,3…row+1 to the current linenumbers 1,2,3…row+1 to the current linefor i in range(row):for i in range(row):line = line + str(row-i)line = line + str(row-i)
For each value of row this will add the For each value of row this will add the numbers row,row-1,row-2…,1 to the current numbers row,row-1,row-2…,1 to the current lineline
Combining these two, the first line will get 1, Combining these two, the first line will get 1, the second, 121, the third, 12321, and so onthe second, 121, the third, 12321, and so on
In Class ExerciseIn Class Exercise Combining all of this, we see a pyramid of Combining all of this, we see a pyramid of
numbers printed outnumbers printed out The first inner for loop adds the spaces at the The first inner for loop adds the spaces at the
left, the second for loop adds the increasing left, the second for loop adds the increasing number, the last adds the decreasing number, the last adds the decreasing numbersnumbers
11 121121 1232112321 12343211234321123454321123454321