CompSci Blogs

August 2023 to June 2024

View the Project on GitHub sfremy/csablog

12 October 2023

Iteration Student Teaching Lesson

by Advik Garg, Srijan Atti, Akhil Singamneni, Aashray Rajagopalan

Introduction

In this lesson, we will explore the various ways to create loops in Python. Loops are essential for repetitive tasks and are a fundamental concept in programming. We will cover different types of loops, advanced loop techniques, and how to work with lists and dictionaries using loops.

For Loops

# APCSP Pseudo-Code: Iterating Over a List of Fruits
'''
fruits ← ["apple", "banana", "cherry"]

FOR EACH fruit IN fruits:
    DISPLAY fruit
END FOR


'''
# Example 1: Simple for loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
apple
banana
cherry

While Loops

# APCSP Pseudo-Code: Using a While Loop to Count and Display Numbers

'''
i ← 1


WHILE i ≤ 5:
    DISPLAY i
    i ← i + 1
END WHILE

'''
# Example 2: Simple while loop
i = 1
while i <= 5:
    print(i)
    i += 1
1
2
3
4
5

Looping with Lists and Dictionaries

# APCSP Pseudo-Code: Loop Through a List
'''
numbers ← [1, 2, 3, 4]
FOR EACH num IN numbers:
    DISPLAY num
END FOR

# APCSP Pseudo-Code: Loop Through a Dictionary
person ← {"name": "aashray", "age": 15, "city": "San Diego"}
FOR EACH key, value IN person:
    DISPLAY key, ":", value
END FOR

'''
# Example 3: Loop through a list
numbers = [1, 2, 3, 4]
for num in numbers:
    print(num)

# Example 4: Loop through a dictionary
person = {"name": "aashray", "age": 15, "city": "San Diego"}
for key, value in person.items():
    print(key, ":", value)

1
2
3
4
name : aashray
age : 15
city : San Diego

Popcorn Hack 1

sample_dict = {}
n_samples = 5
# Code goes here
for i in range(n_samples):
    u_input = input("Something: ")
    try:
        u_input = float(u_input) 
        sample_dict[i] = u_input
    except:
        sample_dict[i] = u_input
        
for key in sample_dict:
    print(sample_dict[key])
    print(type(sample_dict[key]))
q3ejion
<class 'str'>
fejio
<class 'str'>
23.049
<class 'float'>
74747.0
<class 'float'>
421665.0
<class 'float'>

Looping with Index Variable

You can use the range function to create a loop with an index variable.

# APCSP Pseudo-Code: Loop Through a List Using Index
'''

lst ← [4, 6, 7, 2]
FOR i IN RANGE(LENGTH(lst)):
    DISPLAY "Index: " + STRING(i)
    DISPLAY "Element: " + STRING(GET_ELEMENT(lst, i))
END FOR

'''
# Example 5: Loop with an index variable

lst = [4, 6, 7, 2]

for i in range(len(lst)): # Loop for the number of elements in the list
    print('Index: ' + str(i)) # Print the index
    print('Element: ' + str(lst[i])) # Print the element
Index: 0
Element: 4
Index: 1
Element: 6
Index: 2
Element: 7
Index: 3
Element: 2

Nested If Statements

You can nest conditional statements inside a for loop to execute different code based on conditions.

# APCSP Pseudo-Code: For Loop with Nested If Statements

'''

numbers ← [1, 2, 3, 4, 5]
FOR EACH num IN numbers:
    IF num MOD 2 EQUALS 0:
        DISPLAY num, "is even"
    ELSE:
        DISPLAY num, "is odd"
    END IF
END FOR

'''
# Example 6: For loop with nested if statements
numbers = [1, 2, 3, 4, 5]
for num in numbers:
    if num % 2 == 0:
        print(num, "is even")
    else:
        print(num, "is odd")
1 is odd
2 is even
3 is odd
4 is even
5 is odd

Popcorn Hack 2

nums = []
n_samples = 8
#Code goes here
for i in range(n_samples):
    nums.append(int(input("Enter an integer: ")))
    
for num in nums:
    if num % 3 == 0:
        print(num)
426
6
3
18

Try/Except

# APCSP Pseudo-Code: Handling Errors in a For Loop

'''

numbers ← [1, 2, "three", 4, 0, "five"]
FOR EACH item IN numbers:
    TRY:
        DISPLAY 10 / item
    CATCH ZeroDivisionError:
        DISPLAY "Division by zero"
    CATCH TypeError:
        DISPLAY "Type error"
    END TRY
END FOR


'''
numbers = [1, 2, "three", 4, 0, "five"]

for item in numbers:
    try:
        print(10 / item)
    except ZeroDivisionError: #Type of error: Dividing by Zero
        print("Division by zero")
    except TypeError: #Type of error: Dividing by something that isn't a number
        print("Type error")
10.0
5.0
Type error
2.5
Division by zero
Type error

Popcorn Hack 3

import math
numbers = [2, 824, 3.49, -2338, 1394]

# Code goes here
for number in numbers:
    try:
        print(math.log10(number))
    except:
        print('Invalid input')
0.3010299956639812
2.9159272116971158
0.5428254269591799
Invalid input
3.144262773761991

Continue and Break

# APCSP Pseudo-Code: For Loop with Continue and Break

'''

numbers ← [1, 2, 3, 4, 5]
FOR EACH num IN numbers:
 
    IF num EQUALS 3:
        CONTINUE
    IF num EQUALS 5:
        BREAK 
    DISPLAY num
END FOR


'''
# Example 8: For loop with continue and break
numbers = [1, 2, 3, 4, 5]
for num in numbers:
    if num == 3:
        continue  # Skip the number 3
    if num == 5:
        break  # Exit the loop when 5 is encountered
    print(num)
1
2
4

Nested For Loops

# APCSP Pseudo-Code: Nested Loops for Group Names
'''
groups ← [["advik", "aashray"], ["akhil", "srijan"]]

FOR EACH pair IN groups:
    FOR EACH person IN pair:
        DISPLAY person + " is cool"
    END FOR
    DISPLAY pair[0] + " and " + pair[1] + " love to code code code"
END FOR


'''
groups = [['advik', 'aashray'], ['akhil', 'srijan']]

for pair in groups:
    for person in pair:
        print(person + ' is cool')
    print(pair[0] + ' and ' + pair[1] + ' love to code code code')
advik is cool
aashray is cool
advik and aashray love to code code code
akhil is cool
srijan is cool
akhil and srijan love to code code code

(OPTIONAL) Popcorn Hack 4

people = {
    "Abcde": [182, "E+", 15],
    "Fghij": [-3, "A", 2],
    "Anomalocaris canadensis": [510000000, "Q", 64],
    "qwerty": [24, "D-", 4853],
    "8": [-12390891, "Qf", 3663],
    "zqfmbg": [-1923, 5, 24],
    "E": [157326, "%", 725],
    "Yrrej": [163, "Æ", 6]
}

# Code here
comp_element = 0
for key in people:
    if people[key][0] > comp_element:
        print("greater")
    if type(people[key][1]) != str:
        print("invalid type")
        continue
    if people[key][0] == 157326:
        print("Myxococcus llanfair­pwll­gwyn­gyll­go­gery­chwyrn­drobwll­llan­tysilio­gogo­gochensis is a gram-negative, rod-shaped species of myxobacteria found in soil. It is a predator on other bacteria.")
        break
    comp_element = people[key][0]
    
greater
greater
greater
invalid type
greater
Myxococcus llanfair­pwll­gwyn­gyll­go­gery­chwyrn­drobwll­llan­tysilio­gogo­gochensis is a gram-negative, rod-shaped species of myxobacteria found in soil. It is a predator on other bacteria.

Iteration via Recursion

# APCSP Pseudo-Code: Recursion for Factorial Calculation
'''
FUNCTION factorial(n):
    IF n EQUALS 0:
        RETURN 1
    ELSE IF n LESS THAN 0:
        RETURN "undefined"
    ELSE IF TYPEOF(n) EQUALS "float":
        RETURN "not solvable without gamma function"
    ELSE:
        RETURN n TIMES factorial(n - 1)
    END IF
END FUNCTION

result ← CALL factorial(5)
DISPLAY "Factorial of 5 is", result
'''
# Example 9: Recursion for factorial calculation
def factorial(n):
    if n == 0: #Conditions to stop the recursion
        return 1 # 0! is 1
    elif n < 0:
        return "undefined" # Undefined for negative numbers 
    elif isinstance(n, float):
        return "not solvable without gamma function" # Only accept integers
    else:
        return n * factorial(n - 1) #Function calling itself

result = factorial(5)
print("Factorial of 5 is", result)
Factorial of 5 is 120

Homework

students = {}
#Code goes here
accepting_inputs = True
while accepting_inputs == True:
    name = input("Student name:")
    try:
        score = int(input("Student Score"))
        students[name] = score
    except:
        print("invalid score, please re-enter.")
        continue
    cont_pass = input("continue? y/n")
    if cont_pass != 'y':
        accepting_inputs = False
  
print(students)
passing_score = 1000 
passing_students = []
for student in students:
    if students[student] > passing_score:
        passing_students.append(student)

print(passing_students)
{'cmesdjcidosh': 3837, 'sjioenfhdiuf': 53747, 'nsonuhsfu': 23693529, 'oisiroh': 1}
['cmesdjcidosh', 'sjioenfhdiuf', 'nsonuhsfu']
tags: