Lucas DuBois ModuleSevenLessonSixActivity.ipynb - Colaboratory

pdf

School

Smithfield-selma High *

*We aren’t endorsed by this school

Course

10

Subject

Computer Science

Date

Nov 24, 2024

Type

pdf

Pages

9

Uploaded by DukeDanger9183

Report
12/15/23, 3:14 PM Lucas DuBois ModuleSevenLessonSixActivity.ipynb - Colaboratory https://colab.research.google.com/drive/1Y7dObB-Z0QM_70bACO8XJa15FBzVOBlR#scrollTo=Mvqn4ifu4l4J&printMode=true 1/9 I learned about loops with conditional expressions I had trouble with the star part and never quite got it Lucas DuBois 12/15/23 pass while, for: break, continue Nested loops Loops containing compound conditional expressions Students will be able to: Recognize the purpose of a pass statement Differentiate between break and continue statements Control loop iteration using break or continue Use nested loops to iterate over the elements of a table Employ compound conditional expressions in a loop structure Before submission : Remember for max credit, you need to add a complete header comment in a code cell at the very top of this ±le and descriptive comments in each code cell below (examples AND tasks) that explains what your code is doing. ALL functions need a formatted docstring – see the bottom of Mod 3 Lesson 1 Activity for the requirements. Module Seven Lesson Six Activity Concepts View pass statements video The pass statement does nothing; however, it still has useful applications. It is typically used as a placeholder, indicating that it will be replaced by valid functioning code. For example, say you are developing a function but you are not ready to write its code; you can use pass as a placeholder to make your code syntactically correct and avoid any interpreter errors. pass statements Examples These examples do nothing but are syntactically valid - run them and see. def useless_function(): pass for i in range(10): pass if (5 < 6): pass Concepts View Changing Loop Iterations video break statements Changing Loop Iterations
12/15/23, 3:14 PM Lucas DuBois ModuleSevenLessonSixActivity.ipynb - Colaboratory https://colab.research.google.com/drive/1Y7dObB-Z0QM_70bACO8XJa15FBzVOBlR#scrollTo=Mvqn4ifu4l4J&printMode=true 2/9 It is sometimes useful to stop a loop and then resume executing the code that follows. This process is called breaking a loop and can be achieved in Python using a break statement. A break statement can be used with while or for loops and it breaks the innermost loop of nested loops. A break statement is useful for improving the e²ciency of your code. For example, assume you are looping over the elements of an unsorted list looking for the ±rst occurrence of a 0. If a 0 is encountered earlier in the search, there is no need to continue the search and a loop break would be very desirable. break statements can also be used to break out of in±nite loops. continue statements Sometimes you do not need to break out of a loop, but you want to skip an iteration and jump to the next one. This can be done in Python using the continue statement. A continue statement can be used with while or for loops, and it applies to the innermost loop of nested loops. A continue statement is used to improve the e²ciency of code by skipping unnecessary iterations. Examples Breaking loops to improve e²ciency Run the code below - read the comments carefully - check out the difference a break makes break statements # Find the index of the first occurrence of 611 in an arbitrarily long list # Define a long list lst = [976, 618, 812, 898, 804, 689, 611, 630, 467, 411, 648, 931, 618, 425, 328, 196, 56, 615, 458, 166, 115, 118, 22, 585, 213, 855, # Find the index (without break) index = 0 iteration_count = 0 for num in lst: if (num == 611): found_at = index index = index + 1 iteration_count = iteration_count + 1 print("Without using a break, 611 was found at index:", found_at, "using", iteration_count, "iterations") # Find the index (with break) index = 0 iteration_count = 0 for num in lst: if (num == 611): found_at = index break # adding a break to improve efficiency index = index + 1 iteration_count = iteration_count + 1 print("Using a break, 611 was found at index:", found_at, "using", iteration_count, "iterations") Without using a break, 611 was found at index: 6 using 100 iterations Using a break, 611 was found at index: 6 using 6 iterations In±nite loops have some applications, and a break statement would be necessary to break such loops and continue executing the rest of a program. For example, in±nite loops are useful for prompting the user for speci±c input, and should be broken when valid input is entered. Breaking in±nite loops # Prompt the user for a positive number while True: x = int(input("Enter a positive number: ")) if (x > 0): break #x is positive, break the loop continue statements
12/15/23, 3:14 PM Lucas DuBois ModuleSevenLessonSixActivity.ipynb - Colaboratory https://colab.research.google.com/drive/1Y7dObB-Z0QM_70bACO8XJa15FBzVOBlR#scrollTo=Mvqn4ifu4l4J&printMode=true 3/9 Sometimes you do not need to break out of a loop, but you want to skip an iteration and jump to the next one. A continue statement is used to improve the e²ciency of code by skipping unnecessary iterations. # Print the odd elements in a list lst = [14, 6, 5, 10, 6, 9, 33, 103, 21, 55] for num in lst: # Skip all even numbers if (num % 2 == 0): continue print(num) Changing Loop Iterations Task 1 A prime number is a number greater than 1 that is divisible only by 1 and itself. Prime numbers play an important role in several cryptographic algorithms that we use every day, and it is very useful to build a program to test whether a number is prime. The following program tests if num is prime or not Run this program with the following values of num - take note the number of iterations for each num = 45345 num = 11579 num = 948240 Prime numbers num = 45345 #not prim num = 11579 #prime num = 948240 #Not prime prime = True #reponds wether the number is prime or not iteration_count = 0 for i in range(2, num): if num % i == 0: prime = False; iteration_count = iteration_count + 1 if prime: print(num, "is prime") else: print(num, "is NOT prime") print("Total number of iterations:", iteration_count) 948240 is NOT prime Total number of iterations: 948238 Same program is copied below - add a break statement to improve its e²ciency Run the improved program with the same values of num num = 45345 num = 11579 num = 948240 compare the number of iterations for each explain what you noticed about the iterations with and without the break in your comments
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
12/15/23, 3:14 PM Lucas DuBois ModuleSevenLessonSixActivity.ipynb - Colaboratory https://colab.research.google.com/drive/1Y7dObB-Z0QM_70bACO8XJa15FBzVOBlR#scrollTo=Mvqn4ifu4l4J&printMode=true 4/9 prime = True iteration_count = 0 for i in range(2, num): if num % i == 0: prime = False; iteration_count = iteration_count + 1 if prime: print(num, "is prime") else: print(num, "is NOT prime") print("Total number of iterations:", iteration_count) User input Write a program to prompt the user for an odd number; use an in±nite loop and a break statement. Task 2 while True: odd_num = int(input("Enter an odd number: ")) #When entering an odd number it will return true if (odd_num % 2 != 0): print("Thank you") break Enter an odd number: 3 Thank you continue Modify the following program to display numbers that are divisible by 7 along with their square roots. math.sqrt(variable_name) will get you the square root of variable_name, if variable_name is a number HINT: Use a continue statement in the loop Task 3 from math import sqrt #Finds the square roots of numbers for num in range(1, 100): #TODO if num % 7 != 0: continue print(num, "- square root:", sqrt(num)) 7 - square root: 2.6457513110645907 14 - square root: 3.7416573867739413 21 - square root: 4.58257569495584 28 - square root: 5.291502622129181 35 - square root: 5.916079783099616 42 - square root: 6.48074069840786 49 - square root: 7.0 56 - square root: 7.483314773547883 63 - square root: 7.937253933193772 70 - square root: 8.366600265340756 77 - square root: 8.774964387392123 84 - square root: 9.16515138991168 91 - square root: 9.539392014169456 98 - square root: 9.899494936611665 Concepts
12/15/23, 3:14 PM Lucas DuBois ModuleSevenLessonSixActivity.ipynb - Colaboratory https://colab.research.google.com/drive/1Y7dObB-Z0QM_70bACO8XJa15FBzVOBlR#scrollTo=Mvqn4ifu4l4J&printMode=true 5/9 View Nested loops video You can use a loop inside another loop, this concept is known as nested loops. Nested loops have many applications, but they are especially useful for iterating over the elements of a table. A table can be represented in Python as a 2 dimensional list, which is a list containing other lists. You will need two loops to iterate over all the elements of a table, the outer loop iterates over the rows of the table, while the inner loop iterates over the columns in each row. Nested loops Examples In this example, you will print the elements of a 2 dimensional list as a table: | |---|---|---| | 5 | 2 | 6 | | 4 | 6 | 0 | | 9 | 1 | 8 | | 7 | 3 | 8 | NOTE: print statements end with a new line character. You can change this behavior by using an optional argument end . By default end is set to a new line. You can set it to the empty string to suppress the new line behavior. In this example, you will set end to \t , which replaces the new line with a tab. Displaying a table # list of lists table = [[5, 2, 6], [4, 6, 0], [9, 1, 8], [7, 3, 8]] for row in table: for col in row: # print the value col followed by a tab print(col, end = "\t") # Print a new line print() In this example you will see how you can generate an interesting two dimensional character art Character art # Generate a staircase character art # Size controls the number of steps def char_art(steps): for row in range(steps): for col in range(steps): if(col <= row): print("[]", end = "") print() # Generate a staircase with 6 steps char_art(6) [] [][] [][][] [][][][] [][][][][] [][][][][][] Nested Loops Sum of rows Write a program to display the sum of each row in the table Task 4 table = [[5, 2, 6], [4, 6, 0], [9, 1, 8], [7, 3, 8]] #Sums each list for row in table: sum=0
12/15/23, 3:14 PM Lucas DuBois ModuleSevenLessonSixActivity.ipynb - Colaboratory https://colab.research.google.com/drive/1Y7dObB-Z0QM_70bACO8XJa15FBzVOBlR#scrollTo=Mvqn4ifu4l4J&printMode=true 6/9 sum 0 for col in row: sum+=col print("sum = ", sum) print() sum = 13 sum = 10 sum = 18 sum = 18 Nested Loops Character art Complete the function generate_star so it displays a star of variable size using "*" Task 5 # For size = 5 the star should look like: # * * # * * # * # * * # * * def generate_star(size): #I had trouble with this one #TODO for row in range(size): for col in range(size): if(col == row): print("*", end = "") elif (row == size - col -1): print("*", end = "") else: print(" ", end = "") pass # Display star generate_star(5) * * * * * * * * * Concepts View Loops Containing Compound Conditional Expressions video Compound conditional expressions utilizing Boolean logic can be nested within loops. This will allow you to write versatile and ³exible code. You can also use the break and continue statements within nested compound conditionals. Loops Containing Compound Conditional Expressions Examples In the following examples, you will explore the versatility of using compound conditionals inside loops. Finding the largest even number in a list
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
12/15/23, 3:14 PM Lucas DuBois ModuleSevenLessonSixActivity.ipynb - Colaboratory https://colab.research.google.com/drive/1Y7dObB-Z0QM_70bACO8XJa15FBzVOBlR#scrollTo=Mvqn4ifu4l4J&printMode=true 7/9 lst = [102, 34, 55, 166, 20, 67, 305] # Nesting a compound conditional in a for loop largest = 0 for num in lst: # test if num is even and greater than largest if((largest < num) and (num % 2 == 0)): largest = num print("Largest even number in the list is: ", largest) In this example, you are given a list containing ages of 100 people. The code will count the number of children (younger than 13), the number of teenagers (from 13 through 19), the number of young adults (from 20 through 30), and the number of adults (older than 30). Counting within ranges # Ages of 100 people ages = [86, 38, 30, 19, 29, 6, 95, 22, 23, 82, 39, 73, 30, 98, 5, 68, 57, 34, 35, 81, 54, 77, 29, 75, 83, 14, 88, 7, 8, 32, 93, 76, 42, # Initial count children = 0 teens = 0 young_adults = 0 adults = 0 # Nesting compound conditionals within a for loop for age in ages: if(age <= 12): children = children + 1 elif((age >= 13) and (age <= 19)): teens = teens + 1 elif((age >= 20) and (age <= 30)): young_adults = young_adults + 1 elif(age > 30): adults = adults + 1 print("Number of children: ", children) print("Number of teens: ", teens) print("Number of young_adults: ", young_adults) print("Number of adults: ", adults) You can use compound conditionals to test whether user input is valid. The compound conditional statement can be nested within a loop to continuously prompt for input until a valid entry is provided. Prompting for speci±c input # Prompt the user for a number between 50 and 60 # Using infinite loop and break while True: x = int(input("Enter a number between 50 and 60: ")) if ((x >= 50) and (x <= 60)): print("Thank you!") break Loops Containing Compound Conditional Expressions Task 6 Complete the following program to count the number of even positive numbers, odd negative numbers, and zeros in lst Counting speci±c numbers
12/15/23, 3:14 PM Lucas DuBois ModuleSevenLessonSixActivity.ipynb - Colaboratory https://colab.research.google.com/drive/1Y7dObB-Z0QM_70bACO8XJa15FBzVOBlR#scrollTo=Mvqn4ifu4l4J&printMode=true 8/9 print the results lst = [9, 0, -2, -4, -5, 2, -15, 6, -65, -7] #Tells you how many zeroes odd negatives and even positives are in the list even_positives = 0 odd_negatives = 0 zeros = 0 for num in lst: if(num == 0): zeros = zeros + 1 elif((num % 2 == 0) and (num > 0)): even_positives = even_positives + 1 elif((num % 2 != 0) and (num < 0)): odd_negatives = odd_negatives + 1 else: pass print("Number of even positive numbers: ", even_positives) print("Number of odd negative numbers: ", odd_negatives) print("Number of zeros: ", zeros) Number of even positive numbers: 2 Number of odd negative numbers: 4 Number of zeros: 1 Loops Containing Compound Conditional Expressions Counting characters Write a program to count the number of punctuation marks (. , ? ! ' " : ;) in s Task 7 s = "Once you eliminate the impossible, whatever remains, no matter how improbable, must be the truth." # Sherlock Holmes (by Sir Arthu punc_m = 0 #Counts punctuation marks in the given sentence for c in s: if (c == ".") or (c ==',')or (c =='?') or (c =='!') or (c =="'") or (c =='"') or (c ==':') or (c ==';'): punc_m +=1 print("The number of punctuation marks is: ", punc_m) The number of punctuation marks is: 4 Loops Containing Compound Conditional Expressions User Input Write a program to prompt the user for an odd positive number; use an in±nite loop and a break statement. Task 8 while True:#it asks and responds on whether you give an odd positive number odd_pos = int(input("Enter a odd positive number: ")) if (odd_pos % 2 != 0) and (odd_pos > 0): print("Thanks!") break Enter a odd positive number: 4 Enter a odd positive number: 3 Thanks!
12/15/23, 3:14 PM Lucas DuBois ModuleSevenLessonSixActivity.ipynb - Colaboratory https://colab.research.google.com/drive/1Y7dObB-Z0QM_70bACO8XJa15FBzVOBlR#scrollTo=Mvqn4ifu4l4J&printMode=true 9/9
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help