🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

CMSC11_Unit5.pdf

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Transcript

Unit 5: Iteration/Loops Course module by: Prof. Christi Florence Cala-or Prepared by: Keanna Louie Sun Edited by: Joanah Faith Sanz What is Iteration? Iteration is the process of doing something again and again until a condition is met. Python provides us with two statements that easily performs i...

Unit 5: Iteration/Loops Course module by: Prof. Christi Florence Cala-or Prepared by: Keanna Louie Sun Edited by: Joanah Faith Sanz What is Iteration? Iteration is the process of doing something again and again until a condition is met. Python provides us with two statements that easily performs iteration: for and while. Counted Loops: for Loop General Syntax: for in : - can be any variable name - an ordered collection of items you want to iterate (i.e. a string, a list) Python Sequences Example: Write down the indices of the elements in the string “Hello world” elements H e l l o w o r l d index 0 1 2 3 4 5 6 7 8 9 10 Python Sequences elements H e l l o w o r l d index 0 1 2 3 4 5 6 7 8 9 10 “Hello world” length is 11, n=11 n-1 = 11-1 = 10, 10 is the last index is positionally ordered elements are accessed by specifying their indices first element is ar index 0, last element is at index n-1. Python Sequences: Indexing elements H e l l o w o r l d index 0 1 2 3 4 5 6 7 8 9 10 Indexing is accessing an element in a sequence using its index. Use brackets variablename[index] to access an element. s = “Hello world” How do we get the element ‘e’? What is the element at s? Python Sequences: Indexing elements H e l l o w o r l d index 0 1 2 3 4 5 6 7 8 9 10 s = “Hello world” How do we get the element ‘e’? s What is the element at s? o Quick Intro to Lists A list is a data type in Python used to store multiple values in a single variable fruits = [’apple’, ‘orange’, ‘banana’] fruits -> ‘banana’ numbers = [1, 2, 3, 4, 5] numbers -> 5 Counted Loops: For Loop Example: print a list of fruits using a for loop fruits = [’apple’, ‘orange’, ‘banana’] General Syntax: for in : Counted Loops: For Loop Example: print a list of fruits using a for loop 1st iteration: fruit = ‘orange’ Current Output: orange Counted Loops: For Loop Example: print a list of fruits using a for loop 2nd iteration: fruit = ‘apple’ Current Output: orange apple Counted Loops: For Loop Example: print a list of fruits using a for loop 3rd iteration: fruit = ‘banana’ Current Output: orange apple banana Counted Loops: For Loop Example: print a list of fruits using a for loop Final Output: Counted Loops: For Loop Example: print all the letters in the string “hello” range() a function that generates a list of numbers. It will only accept integer arguments. Three ways to call the range() function: range(start, stop) range(start, stop, step) range(stop) range() range(start, stop) This will generate a list of numbers that includes start but excludes stop Example: range(2, 10) -> 2, 3, 4, 5, 6, 7, 8, 9 Note: Use the list() function to show the list of numbers the range() function generates range() range(start, stop, step) This will generate a list of numbers that includes start but excludes stop and has a stepsize step Example: range(2, 10, 2) -> 2, 4, 6, 8 range() range(start, stop, step) step can be negative, but start should be greater than stop Example: range(10, 2, -2) -> 10, 8, 6, 4 range(2, 10, -2) -> (empty) range() range(stop) By default, the range function will start with 0 and will exclude stop Example: range(10) -> 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 Counted Loops: for Loop Using range() in a for loop: This for loop gets the sum of the numbers from 0 to 10 a list from 0 to 10 total = total + i Counted Loops: for Loop Output: Counted Loops: for Loop Example: print the index and their associated element Note: len(fruits) is 3 range(3) is 0, 1, 2 1st iteration: i=0 Current Output: 0 orange Counted Loops: for Loop Example: print the index and their associated element 2nd iteration: i=1 Current Output: 0 orange 1 apple Counted Loops: for Loop Example: print the index and their associated element 3rd iteration: i=2 Current Output: 0 orange 1 apple 2 banana enumerate() The enumerate() function returns a list of pairs: the index and its associated element. The pair of values it returns is called a tuple, which is one of Python's built-in data types. enumerate() Example: print the indices and their associated elements using enumerate() Output: enumerate() To get only either the index or the element, modify the variable portion of the for statement: Output: enumerate() To get only either the index or the element, modify the variable portion of the for statement: Output: Multivalued Assignment assign multiple variables at once as long as there are an equal number of values to match with the storage variables This also works if the value on the right side is a sequence while loop General Syntax: an expression that returns either True or False while : while loop The while loop will only iterate if the condition returns True. First, evaluate condition while : evaluate condition, if True, execute body then repeat process Once the condition returns False, the while loop will terminate. while loop Example Note that condition is evaluated first before starting an iteration. while loop Example: Output: while loop for loop while loop use when you know exactly use when you don't know in how many iterations you advance how many times need you need to iterate Controlling Loops: break The break statement allows you to exit a loop. You can use break if you want to terminate the loop based on a certain condition. Example: Controlling Loops: break Test case 1: if num > 3 Test case 2: if num = 3 Test case 3: if num < 3 Controlling Loops: continue The continue statement allows you to skip the current iteration and run the next one. Use continue if you want to skip an iteration based on certain conditions. Example: Controlling Loops: continue Test case 1: if num > 3 Test case 2: if num = 3 Test case 3: if num < 3 Nested Loops Loops can be nested in other loops. nested loop -> inner loop outside loop -> outer loop for in : for in : Nested Loops Example: Print this using nested loops Nested Loops Example: Print this using nested loops Nested Loops Example: Print this using nested loops Infinite Loops An infinte loop occurs if a loop never terminates. Commonly happens if the condition of a while loop never returns false or if the counter variable never changes. Example: Output: Tip: Exit the infinite loop by pressing ctrl+c Infinite Loops Example: If line 4 is removed, the program will hang User Input Loops You can use a while loop to continuously ask input from the user. User Input Loops Summary (for Units 4 and 5) In unit 4, we discussed the importance of return values and how it can make our functions more useful. In unit 5, we learned how to use the for and while loops and how to control their execution. Assignment/Reminders Practice Exercise involving loops to be posted at LMS First Long Exam Options: 1. October 2 (5:30PM-8PM) CL2 & CL3, names Your list of names will be posted on the cork board outside the rooms. Next Meeting Unit 6: Strings

Tags

python programming iteration loops computer science
Use Quizgecko on...
Browser
Browser