Fall 2024 - P2
Big Idea 3 | .1 | .2 | .3 | .4 | .5 | .6 | .7 | .8 | .10 |
3.8-P2 Iteration
Student led teaching on Iteration. Learn how to do loops with Java and Python.
Iterations!
Introduction
The purpose of Loops or Iterations in Python is to code repetitive tasks, which is fundamental in programming. We’ll go over:
- For Loops
- While Loops/Do-While Loops
- Index Loops
- Continue and Break
For Loops
- Used when you know how many times you need to run an algorithm
- Runs through a specific set of instructions, and then stops
While Loops/ Do-While Loops
- Similar to For loop, but it runs a set amount of time and has a condition at the end.
- For ex: Do something 3 times, but IF it failes on 3rd, re-do instructions again.
- Do-whiles are similar to whiles, but instead of a conditions, it stops defpending on a true or false statement at the end.
Index Loops
- This is used to control the number of iterations in a single loop
Continue and Break
- This command helps to terminate certain loops, or to move on to the next loop.
Extra Help
Click the following button to get extra help on loops in coding
Other Fun Loops
- Even though we will mainly cover the loops above, here are some other loops that you can also add to your page
Endless/Infinite Loops
- Endless and infinite loops are created when a loop continues infinitely because the terminating condition is never met.
- Here are examples in python and javascript.
while True:
print("This will run forever!")
%%javascript
let count = 0;
while (true) {
console.log("Running...");
count++;
if (count > 5) { // Change this condition as needed
break;
}
}
<IPython.core.display.Javascript object>
Try/Except with Loops
- Try/Except Loops are helpful in code through helping you handle errors and exceptions in try/except blocks and try/catch blocks.
- Here are some examples in python and javascript
try:
# Code that may raise an exception
result = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("You can't divide by zero!")
except Exception as e:
print(f"An error occurred: {e}")
else:
# This block runs if no exception is raised
print(f"Result: {result}")
finally:
# This block runs no matter what
print("Execution finished.")
You can't divide by zero!
Execution finished.
%%javascript
try {
// Code that may throw an error
let result = 10 / 0; // This will not throw an error, but for demo purposes
if (!isFinite(result)) throw new Error("Division by zero"); // Manually throw error
} catch (error) {
console.log("An error occurred: " + error.message);
} finally {
// This block runs no matter what
console.log("Execution finished.");
}
<IPython.core.display.Javascript object>
Nested For Loops
- You can put loops within loops using code. Nested loops can be helpful to iterate over multiple dimensions.
- Here are examples in python and javascript.
# Example: Nested loops to print a multiplication table
for i in range(1, 4): # Outer loop
for j in range(1, 4): # Inner loop
product = i * j
print(f"{i} * {j} = {product}")
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
%%javascript
// Example: Nested loops to print a multiplication table
for (let i = 1; i < 4; i++) { // Outer loop
for (let j = 1; j < 4; j++) { // Inner loop
let product = i * j;
console.log(`${i} * ${j} = ${product}`);
}
}
<IPython.core.display.Javascript object>
Creative Ways to use Loops
- Below is a series of code you can include in your code to create a text banner.
- It uses multiple types of loops to create an aesthetic banner
import time
import os
# Clear the console (works on most systems)
def clear_console():
os.system('cls' if os.name == 'nt' else 'clear')
# Function to create a banner
def create_banner(text, width=50):
# Center the text
centered_text = text.center(width)
# Create a decorative border
border = '*' * width
# Print the banner
print(border)
print(centered_text)
print(border)
# Function to create a colorful effect
def colorful_banner(text):
colors = ["\033[91m", "\033[92m", "\033[93m", "\033[94m", "\033[95m", "\033[96m", "\033[0m"]
# Loop through each character in the text
for i, char in enumerate(text):
color = colors[i % len(colors)] # Cycle through colors
print(f"{color}{char}", end='', flush=True)
time.sleep(0.1) # Add a small delay for effect
print("\033[0m") # Reset color
# Main function to run the presentation
def main():
clear_console()
title = "Welcome to the Python Loop Showcase!"
# Create the banner
create_banner(title)
# Add a pause
time.sleep(1)
# Colorful text presentation
print("\nLet's create a colorful display:\n")
colorful_banner("Hello, World!")
# Add a pause
time.sleep(1)
# String looping example
print("\nLooping through a string:\n")
text = "Python is fun!"
for char in text:
print(char, end=' ', flush=True)
time.sleep(0.3) # Add a small delay
print() # New line at the end
# Nested loop example
print("\nCreating a pattern using nested loops:\n")
for i in range(5):
for j in range(i + 1):
print('*', end=' ')
print() # New line after each row
# Run the presentation
if __name__ == "__main__":
main()
[H[2J**************************************************
Welcome to the Python Loop Showcase!
**************************************************
Let's create a colorful display:
[91mH[92me[93ml[94ml[95mo[96m,[0m [91mW[92mo[93mr[94ml[95md[96m![0m
Looping through a string:
P y t h o n i s f u n !
Creating a pattern using nested loops:
*
* *
* * *
* * * *
* * * * *
- Here is a creative use of infinite and endless loops to create a cool set of patterns
- There is also a use of nested loops and emojis to create a cool visual presentation
import os
import time
import itertools
# Clear the console
def clear_console():
os.system('cls' if os.name == 'nt' else 'clear')
# Function to display a moving pattern
def moving_pattern():
clear_console()
pattern = "*-*-*--*--*-*-*"
while True:
for i in range(len(pattern)):
clear_console()
print(pattern[i:] + pattern[:i]) # Create a shifting effect
time.sleep(0.2) # Delay for effect
# Function to display a colorful message
def colorful_message():
clear_console()
colors = ["\033[91m", "\033[92m", "\033[93m", "\033[94m", "\033[95m", "\033[96m"]
message = "Welcome to the Aesthetic Presentation!"
while True:
for color in itertools.cycle(colors):
clear_console()
print(f"{color}{message}\033[0m") # Print in color
time.sleep(0.5) # Change color every half a second
# Main function to run the presentation
def main():
try:
# You can uncomment one of the following lines to run different presentations
# moving_pattern()
colorful_message()
except KeyboardInterrupt:
clear_console()
print("Presentation ended. Thank you!")
# Run the presentation
if __name__ == "__main__":
main()
[H[2J[H[2J[91mWelcome to the Aesthetic Presentation![0m
[H[2J[92mWelcome to the Aesthetic Presentation![0m
[H[2J[93mWelcome to the Aesthetic Presentation![0m
[H[2J[94mWelcome to the Aesthetic Presentation![0m
[H[2J[95mWelcome to the Aesthetic Presentation![0m
[H[2J[96mWelcome to the Aesthetic Presentation![0m
[H[2J[91mWelcome to the Aesthetic Presentation![0m
[H[2J[92mWelcome to the Aesthetic Presentation![0m
[H[2J[93mWelcome to the Aesthetic Presentation![0m
[H[2J[94mWelcome to the Aesthetic Presentation![0m
[H[2J[95mWelcome to the Aesthetic Presentation![0m
[H[2J[96mWelcome to the Aesthetic Presentation![0m
[H[2J[91mWelcome to the Aesthetic Presentation![0m
[H[2J[92mWelcome to the Aesthetic Presentation![0m
[H[2J[93mWelcome to the Aesthetic Presentation![0m
[H[2J[94mWelcome to the Aesthetic Presentation![0m
[H[2J[95mWelcome to the Aesthetic Presentation![0m
[H[2J[96mWelcome to the Aesthetic Presentation![0m
[H[2J[91mWelcome to the Aesthetic Presentation![0m
[H[2J[92mWelcome to the Aesthetic Presentation![0m
[H[2J[93mWelcome to the Aesthetic Presentation![0m
[H[2J[94mWelcome to the Aesthetic Presentation![0m
[H[2J[95mWelcome to the Aesthetic Presentation![0m
[H[2J[96mWelcome to the Aesthetic Presentation![0m
[H[2J[91mWelcome to the Aesthetic Presentation![0m
[H[2J[92mWelcome to the Aesthetic Presentation![0m
[H[2J[93mWelcome to the Aesthetic Presentation![0m
[H[2J[94mWelcome to the Aesthetic Presentation![0m
[H[2J[95mWelcome to the Aesthetic Presentation![0m
[H[2J[96mWelcome to the Aesthetic Presentation![0m
[H[2J[91mWelcome to the Aesthetic Presentation![0m
[H[2JPresentation ended. Thank you!
import os
import time
# Clear the console
def clear_console():
os.system('cls' if os.name == 'nt' else 'clear')
# Function to create an emoji pattern
def emoji_pattern(rows, cols):
emojis = ["😀", "🎉", "🌟", "💖", "🌈"]
clear_console()
for i in range(rows):
for j in range(cols):
print(emojis[(i + j) % len(emojis)], end=' ')
print() # New line after each row
time.sleep(0.5) # Delay for effect
# Function to display a colorful message with emojis
def colorful_message():
emojis = ["✨", "🚀", "🌼", "🌊", "🔥"]
message = "Welcome to the Emoji Presentation!"
while True:
clear_console()
for emoji in emojis:
print(f"{emoji} {message} {emoji}")
time.sleep(0.5) # Delay for effect
# Main function to run the presentation
def main():
try:
# Set the number of rows and columns for the emoji pattern
emoji_pattern(5, 5)
# Uncomment to display a colorful message
# colorful_message()
except KeyboardInterrupt:
clear_console()
print("Presentation ended. Thank you!")
# Run the presentation
if __name__ == "__main__":
main()
[H[2J😀 🎉 🌟 💖 🌈
🎉 🌟 💖 🌈 😀
🌟 💖 🌈 😀 🎉
💖 🌈 😀 🎉 🌟
🌈 😀 🎉 🌟 💖