August 2023 to June 2024
View the Project on GitHub IshanCornick/new_student
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.
# 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
# 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
# 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
Use a loop to get X amount of inputs. Then use a loop to find the type of each value.
Extra Challenge: If an input is a number, make the corresponding value in the dictionary a number.
value_dict = {}
X = int(input("Enter the number of inputs: "))
for i in range(X):
user_input = input("Enter a value: ")
if user_input.isdigit():
user_input = int(user_input)
value_type = type(user_input).__name__
value_dict[user_input] = value_type
print("Dictionary of values and their types:")
for key, value in value_dict.items():
print(f"{key}: {value}")
Dictionary of values and their types:
: str
fe: str
ef: str
f: str
fw: str
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
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
Use the input() function to append a range of integers from a list
Use a nested if statement to only print numbers in the list that are evenly divisble by 3
integer_list = []
start = int(input("Enter the start of the range: "))
end = int(input("Enter the end of the range: "))
for i in range(start, end + 1):
integer_list.append(i)
for num in integer_list:
if num % 3 == 0:
print(num)
#Code goes here
3
6
9
Using a try
and except
block inside a loop can handle errors gracefully.
Very useful for production code, even in frontend webapps
# 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
math
module for this error# List of values, including some non-integer types
values = [10, "20", 30, None, "forty", 50]
for value in values:
try:
result = value * 2
print(f"Result of the operation: {result}")
except AttributeError as e:
print(f"AttributeError: {e} occurred for value {value}")
except Exception as e:
print(f"An exception occurred: {e} for value {value}")
# Code goes here
Result of the operation: 20
Result of the operation: 2020
Result of the operation: 60
An exception occurred: unsupported operand type(s) for *: 'NoneType' and 'int' for value None
Result of the operation: fortyforty
Result of the operation: 100
Continue
statement skips the current iterationBreak
statement exits the loop prematurely# 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
# 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
people = {}
# Code here
# 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
student_dict = {}
while True:
student_name = input("Enter the student's name (or 'q' to quit): ")
if student_name.lower() == 'q':
break
student_grade = int(input(f"Enter {student_name}'s grade: "))
student_dict[student_name] = student_grade
highest_score = max(student_dict.values())
passing_students = []
for student, grade in student_dict.items():
if grade >= 60:
passing_students.append(student)
for student, grade in student_dict.items():
print(f"{student}: {grade}%")
print(f"The highest score is: {highest_score}%")
for student in passing_students:
print("student passed: " + student)
a: 0%
b: 60%
c: 89%
The highest score is: 89%
student passed: b
student passed: c
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.
# 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
# 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
# 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
Use a loop to get X amount of inputs. Then use a loop to find the type of each value.
Extra Challenge: If an input is a number, make the corresponding value in the dictionary a number.
value_dict = {}
X = int(input("Enter the number of inputs: "))
for i in range(X):
user_input = input("Enter a value: ")
if user_input.isdigit():
user_input = int(user_input)
value_type = type(user_input).__name__
value_dict[user_input] = value_type
print("Dictionary of values and their types:")
for key, value in value_dict.items():
print(f"{key}: {value}")
Dictionary of values and their types:
: str
fe: str
ef: str
f: str
fw: str
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
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
Use the input() function to append a range of integers from a list
Use a nested if statement to only print numbers in the list that are evenly divisble by 3
integer_list = []
start = int(input("Enter the start of the range: "))
end = int(input("Enter the end of the range: "))
for i in range(start, end + 1):
integer_list.append(i)
for num in integer_list:
if num % 3 == 0:
print(num)
#Code goes here
3
6
9
Using a try
and except
block inside a loop can handle errors gracefully.
Very useful for production code, even in frontend webapps
# 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
math
module for this error# List of values, including some non-integer types
values = [10, "20", 30, None, "forty", 50]
for value in values:
try:
result = value * 2
print(f"Result of the operation: {result}")
except AttributeError as e:
print(f"AttributeError: {e} occurred for value {value}")
except Exception as e:
print(f"An exception occurred: {e} for value {value}")
# Code goes here
Result of the operation: 20
Result of the operation: 2020
Result of the operation: 60
An exception occurred: unsupported operand type(s) for *: 'NoneType' and 'int' for value None
Result of the operation: fortyforty
Result of the operation: 100
Continue
statement skips the current iterationBreak
statement exits the loop prematurely# 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
# 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
people = {}
# Code here
# 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
student_dict = {}
while True:
student_name = input("Enter the student's name (or 'q' to quit): ")
if student_name.lower() == 'q':
break
student_grade = int(input(f"Enter {student_name}'s grade: "))
student_dict[student_name] = student_grade
highest_score = max(student_dict.values())
passing_students = []
for student, grade in student_dict.items():
if grade >= 60:
passing_students.append(student)
for student, grade in student_dict.items():
print(f"{student}: {grade}%")
print(f"The highest score is: {highest_score}%")
for student in passing_students:
print("student passed: " + student)
a: 0%
b: 60%
c: 89%
The highest score is: 89%
student passed: b
student passed: c