Importance of Loops in Programming
Loops in programming allow a programmer to repeat actions in a controlled manner for various tasks such as iterating through lists, computing averages, or reading files. They enable efficient repetition of code blocks and provide flexibility in handling different scenarios. Understanding loops is essential for effectively managing program flow and optimizing code execution. Learn about different types of loops, loop control variables, and the usage of break and continue statements for loop control.
Download Presentation

Please find below an Image/Link to download the presentation.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.
You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.
E N D
Presentation Transcript
Loops Loops allow a programmer to repeat actions, i.e. lines of code, in a controlled fashion Why would we want to do this? Repeat the same computation with different input Work through a list of items (ex: compute an average) Read information from a file ??? Professor John Carelli Kutztown University Computer Science Department
Simple example Suppose we want to print out the numbers 1 through 5 print(1) print(2) print(3) print(4) print(5) We could just use 5 print statements, suppose we wanted to print 1 to 100 - yikes! Or, we could use a loop Professor John Carelli Kutztown University Computer Science Department
while loop As long as the (Boolean) condition evaluates to True, the statements in the block get executed It keeps repeating the block until the condition becomes False Each time though the loop is called an iteration Looks like an if statement, except it evaluates more than once! Professor John Carelli Kutztown University Computer Science Department
Simple example revisited Print out the numbers 1 through 5 x=1 while x <= 5: print(x) x= x+1 Initially, x equals 1, which is less than 5. So, the block will be executed. x (1) will get printed x will be updated (to 2) The condition will be re-evalued (2 is still less than 5). So, the block will be executed again (2 gets printed) The process repeats until x equals 6, at which point it stops Suppose we change 5 to 10 ? Professor John Carelli Kutztown University Computer Science Department
Loops usage A loop control variable is used to control when the loop ends. The programmer must: Initialize the loop control variable Test the loop control variable Update the loop control variable What happens if we skip one of these? Professor John Carelli Kutztown University Computer Science Department
break and continue Both interrupt the normal flow of loop execution x=0 while True: x=x+1 if x == 10: break elif x == 5: continue elif x % 2 == 1: print(x) break Causes the loop to exit immediately continue The current iteration terminates immediately Only that iteration is affected!!! The loop then moves on to the loop iteration condition and proceeds normally from there What does this do ? Professor John Carelli Kutztown University Computer Science Department
Definite vs. Indefinite Sometimes, we don t know how many times a loop will iterate. Definite Loop: The number of iterations is pre- determined (this is what we ve seen so far) num=0 while num != 3: val= input("Guess the secret number: ") num=int(val) # why do we need this? print("You got it!") Indefinite Loop: The number of iterations is unknown An exit strategy is needed Indefinite loop example Professor John Carelli Kutztown University Computer Science Department
for loop Alternative looping construct Iterates over a pre-determined sequence of items Often used for definite loops Professor John Carelli Kutztown University Computer Science Department
for loop syntax Where items is a sequence of things of things to loop over variable gets set to each item in the sequence, one per iteration Syntax: forvariableinitems: block statements Note: there is no need to initialize or update the loop variable! It happens automatically! Example: for state in PA , NJ , NY : print(state) Professor John Carelli Kutztown University Computer Science Department
range() function range(begin, end) function generates a sequence of numbers Starting with the begin Ending with end-1 Example in a forloop: for num in range(1,5): print(num) Example: range(1,5) Produces the sequence: 1, 2, 3, 4 Can be used to make a counter loop Professor John Carelli Kutztown University Computer Science Department
tuple A tuple is, basically, a list of items Syntax: a comma separated list of items enclosed in parenthesis Examples: ( Pennsylvania , New Jersey , New York ) (10, 20, 30, 40, 50) Professor John Carelli Kutztown University Computer Science Department
More on tuples Access items in a tuple using an index number: Use [] start at zero and end at size-1 >>> states=("PA","NJ","NY") >>> states ('PA', 'NJ', 'NY') >>> states[0] 'PA' >>> states[2] 'NY' >>> len(states) 3 Also: len() function will return the size Can t change the values in a tuple states[3]= FL # wrong!!! tuples can be used in for loops: Example: forTuple.py Professor John Carelli Kutztown University Computer Science Department
try except statement Errors in a computer program are called exceptions try except statement Used to catch exceptions in other words, detect an error and respond to it by taking a specific action if/when it occurs Some example of error types: ValueError ZeroDivisionError (ex: incorrect type conversion) (ex: divide by zero) Professor John Carelli Kutztown University Computer Science Department
Examples: try except x= input("Enter the dividend: ") y= input("Enter the divisor: ") x= input("Enter the dividend: ") y= input("Enter the divisor: ") try: num= float(x) denom= float(y) try: num= float(x) denom= float(y) result= num / denom print("Answer: ", result) except ZeroDivisionError: print("Can't divide by zero!") result= num / denom print("Answer: ", result) except: # any error print( Something went wrong!") Professor John Carelli Kutztown University Computer Science Department