3.8 Popcorn Hacks

3.8.1 For Loops

Popcorn Hack #1

%%javascript
for (let i = 10; i < 20; i++) {
    console.log(i);
}
<IPython.core.display.Javascript object>

Popcorn Hack #2

fruits = ['🥥', '🍓', '🍉', '🥭', '🍑']

for fruit in fruits:
    print(fruit)
🥥
🍓
🍉
🥭
🍑

3.8.2 While, Do-While

While Loop Popcorn Hack #1 (Uses Javascript)

number = 1

while number <= 20:
    if number % 2 == 1:
        print(number)
    number += 1
1
3
5
7
9
11
13
15
17
19

Do-While Popcorn Hack #2 (Uses Python)

import random

flip = ""

while flip != "heads":
    flip = random.choice(["heads", "tails"])
    print(f"Flipped: {flip}")

print("Landed on tails!")
Flipped: tails
Flipped: tails
Flipped: tails
Flipped: heads
Landed on tails!

3.8.3 Index Loops

Python Popcorn Hack

# List of tasks
tasks = [
    "Wake Up",
    "Brush my teeth",
    "Take a shower",
    "Put on my clothes",
    "Go downstarirs and eat breakfast",
    "Leave for school"
]

# Function to display tasks with indices
def display_tasks():
    print("Your To-Do List:")
    for index in range(len(tasks)):
        print(f"{index + 1}. {tasks[index]}")  # Display task with its index

# Call the function
display_tasks()

Your To-Do List:
1. Wake Up
2. Brush my teeth
3. Take a shower
4. Put on my clothes
5. Go downstarirs and eat breakfast
6. Leave for school

Javascript Popcorn Hack

%%javascript
// List of tasks
const tasks = [
    "Wake Up",
    "Brush my teeth",
    "Take a shower",
    "Put on my clothes",
    "Go downstarirs and eat breakfast",
    "Leave for school"
];

// Function to display tasks with indices
function displayTasks() {
    console.log("Your To-Do List:");
    for (let index = 0; index < tasks.length; index++) {
        console.log(`${index + 1}. ${tasks[index]}`); // Display task with its index
    }
}

// Call the function
displayTasks();
<IPython.core.display.Javascript object>

3.8.4 Continue and Break

JavaScript with Continue Commands, Popcorn Hack #1

%%javascript

for (let i = 10; i < 20; i++) {
  if (i === 5) {
    continue; 
  }
  console.log(i); 
}

//pretty much the same exact thing as the break commands!
<IPython.core.display.Javascript object>

Popcorn Hack #2

for i in range(1, 11):
    if i % 2 == 0:
        continue
    print(i)
1
3
5
7
9