# Noemi Cabrera
# 2 December 2021
# In this lesson, I learned how to use and differentiate the pass, break, and continue statements.
# These are efficient for when you're not ready to write code under certain places, continue with
# code in the next line, or want to break a forever loop. The break and continue statements are
# also useful to control loop iteration. Also, I learned how to use nested loops to iterate over the
# elements of a table and how to employ compound conditional expressions in a loop structure.
# All of these features allow the code to be more efficient and smooth.
# I didn't have any major difficulties in this lesson.
# In this code, the pass statement is used inside the defined useless_function as its code so that an error is not displayed. It's
# used as a placeholder for the actual code that can be put into the function. It displays nothing.
# Does nothing, but syntactically valid
def useless_function():
pass
# In this code, the pass statement is used inside a for loop to replace any code so that an error is not displayed. It's
# used as a placeholder for the actual code that can be put into the loop. It displays nothing.
# Does nothing, but syntactically valid
for i in range(10):
pass
# In this code, the pass statement is used inside an if statement to replace any code so that an error is not displayed. It's
# used as a placeholder for the actual code that can be put into the statement. It displays nothing.
# Does nothing, but syntactically valid
if (5 < 6):
pass
# In this code, a break statement is used in the same code defined first to iterate throughthe items in the 'lst' list until the the if statement evaluates
# true. This is more efficient since you do not have to iterate through every single item in the list like the first code in this cell does.
# 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, 615, 478, 234, 360, 981, 174, 993, 627, 911, 385, 219, 577, 540, 49, 164, 109, 893, 727, 687, 709, 971, 781, 802, 701, 789, 421, 863, 44, 573, 91, 140, 338, 36, 102, 502, 723, 134, 336, 940, 969, 649, 598, 413, 307, 929, 951, 993, 436, 149, 280, 907, 733, 713, 268, 29, 946, 102, 277, 352, 449, 527, 201, 566, 643, 118, 587, 717, 358, 542, 223, 846, 244, 83, 268]
# 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")
# In this code, a break statement is used under the if statement to break the infinite while loop that asks for user input. WHen
# the user enters the correct answer, the loop breaks.
# 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
# In this code, a continue statement is used in a for loop that iterates through 'lst'. The continue statement indicates that when
# the iteration is finished, the next line of code would be executed. All the odd numbers in 'lst' are displayed.
# 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)
# In this program, a break statement is used in the for loop that iterates through num. The break is placed in
# the if statement after the code in it has executed so that the number of iterations is reduced.
# [ ] The following program tests if `num` is prime or not, use a `break` statement to improve its efficiency
# and reduce the number of necessary iterations
# Compare the number of necessary iterations with and without the `break` statement
# Use the following numbers for the comparison:
num = 45345
#num = 11579
#num = 948240
#num = 128093
#num = 519937
#num = 694394
prime = True # assume num is prime unless proven otherwise
iteration_count = 0
for i in range(2, num):
if num % i == 0:
prime = False;
break
iteration_count = iteration_count + 1
# Display results
if prime:
print(num, "is prime")
else:
print(num, "is NOT prime")
print("Total number of iterations:", iteration_count)
# In this code, the user is asked to enter an odd number. A while loop is used to ask for an odd number
# until the user enters a correct answer. I f the number is odd, "Thank you" displays and the loop breaks.
# [ ] Write a program to prompt the user for an odd number; use an infinite loop and a `break` statement.
while True:
odd_num = int(input("Enter an odd number: "))
if (odd_num % 2 != 0):
print("Thank you")
break
# In this code, the sqrt function is first imported from the math module. Then, with a for loop, numbers
# 1 through 100 are iterated through. Then using a continue statement in the if statement, we check if the
# number is not divisible by 7 and continue moving on until all the numbers have been iterated through.
# The new line of code that prints the numbers divisible by 7 and their squate roots is executed because of the continue
# statement.
# [ ] Modify the following program to display numbers that are divisible by 7 along with their square roots.
# HINT: Use a `continue` statement in the loop
from math import sqrt
for num in range(1, 100):
#TODO
if num % 7 != 0:
continue
print(num, "- square root:", sqrt(num))
# In this code, a nested for loop is used to iterate through each list found in the 'table' list.
# The initial for loop iterates through table. Then, the nested loop iterates through each of the items in
# table. A tab/space is added at the end of each item in each list. The items are displayed.
# 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 code, a char_art function is defined and designed to display a staircase generated with []
# The initial for loop terates through the range specified when calling the function. Then, the second for loop
# does the same thing, but an if statatement is added to compare the two numbers and when they match, a
# [] is displayed.
# 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)
# In this code, a nested for loop is used. First the initial for loop iterates through each list in the
# "table" list. Then a nested for loop is used to iterate through each item in the lists in "table".
# Each item found in one list is added together and then the final sum is displayed. This is done for
# each of the list in "table".
# [ ] Write a program to display the sum of each row in the table
table = [[5, 2, 6], [4, 6, 0], [9, 1, 8], [7, 3, 8]]
for row in table:
sum=0
for col in row:
sum+=col
print("sum = ", sum)
print()
# In this code, the generate_star function is defined. This function takes in 1 argument, size.
# Then with an initial for loop, each number in the range, which is defined by the argument value entered.
# Then a nested for loop and an if/else statement are used to display an asterick when the numbers
# equal each other or when the numbers of the range equals the substraction of the size, a number in the range, and 1.
# The final star is printed.
# [ ] Complete the function `generate_star` so it displays a star of variable `size` using "*"
# For size = 5 the star should look like:
# * *
# * *
# *
# * *
# * *
def generate_star(size):
#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)
# In this code, the for loop iterates through each item in the lst list. Then, an if statement is used with
# the and operator to check if the number is the largest and even in the list.
# The largest even number is displayed.
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 code, a for loop is used to iterate through the 'ages' list and then an if/else statement is
# used to place the ages of 100 peolple into categories (children, teens, young adults, and adults)
# This is done by using an and operator in the elif statements.
# The final number of people in each category is printed.
# 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, 1, 32, 70, 70, 3, 34, 52, 44, 41, 7, 77, 73, 97, 34, 13, 33, 54, 8, 82, 21, 55, 72, 41, 34, 98, 72, 73, 24, 55, 50, 63, 38, 92, 43, 68, 52, 68, 69, 51, 19, 24, 35, 55, 74, 47, 8, 19, 69, 12, 96, 96, 11, 30, 97, 73, 22, 25, 19, 85, 37, 68, 39, 76, 73, 18, 45, 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)
# In this code, a while loop is created. Then, the user is asked to enter a number between 50 and 60
# until the number entered is valid. This is done with an 'and' operator and comparisons statements in the
# loop.
# 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
# In this code, a for loop is used to iterate through the 'lst' list. Then an if/else statement is used to
# to check if any number in the list is an even positive, an odd negative, or a zero. The and operator
# is used in the elif statements to check if a number is both even and positive, or odd and negative.
# The count of times each category is in 'lst' list is displayed.
# [ ] Complete the following program to count the number of even positive numbers, odd negative numbers, and zeros in `lst`
# then print the results
lst = [9, 0, -2, -4, -5, 2, -15, 6, -65, -7]
even_positives = 0
odd_negatives = 0
zeros = 0
#TODO: Count even_positives, odd_negatives, and zeros
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)
# In this code, a for loop is used to iterate through the "s" list. The variable punc_m is set to
# zero before the loop. Then using an if statement and the or operator, we check if any of the specified
# punctuation marks are in s. If this evaluates to true, then the punc_m variable is added 1.
# The total number of punctuation marks in 's' is displayed.
# [ ] Write a program to count the number of punctuation marks (. , ? ! ' " : ;) in `s`
s = "Once you eliminate the impossible, whatever remains, no matter how improbable, must be the truth." # Sherlock Holmes (by Sir Arthur Conan Doyle, 1859-1930)
punc_m = 0
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)
# In this code, a infinite while loop with the True keyword is used. Then, the user is asked to
# enter a odd positive number until the entered answer is correct, and the loop breaks.
# [ ] Write a program to prompt the user for an odd positive number; use an infinite loop and a `break` statement.
while True:
odd_pos = int(input("Enter a odd positive number: "))
if (odd_pos % 2 != 0) and (odd_pos > 0):
print("Thanks!")
break