![]() |
Home | Accounts | Setup | Verify | Play | Hacks |
3.8 ForLoops all Hacks
All Hacks for ForLoops
- Popcorn Hack 1 For Loops
- Popcorn Hack 2 While Loops
- Popcorn hack for index loop
- Popcorn Hack for 3.8.4 Continue and Break
- Homework Hack 1
- Objective
- Step 1: Define Your Tasks
Popcorn Hack 1 For Loops
fruits = ['🍎', '🍌', '🍒']
for fruit in fruits:
print(fruit)
🍎
🍌
🍒
Popcorn Hack 2 While Loops
number = 1
while number <= 20:
if number % 2 == 1:
print(number)
number += 1
1
3
5
7
9
11
13
15
17
19
import random
flip = ""
while flip != "tails":
flip = random.choice(["tails"])
print(f"Flipped: {flip}")
print("Landed on tails!")
Flipped: tails
Landed on tails!
Popcorn hack for index loop
tasks = [
"Brush Teeth",
"Shower",
"Play sports with friends",
"Do homework",
"Go to sleep"
]
# 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. Brush Teeth
2. Shower
3. Play sports with friends
4. Do homework
5. Go to sleep
%%javascript
// List of tasks
const tasks = [
"Brush Teeth",
"Shower",
"Play sports with friends",
"Do homework",
"Go to sleep"
];
// 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>
%%javascript
for (let i = 5; i < 15; i++) {
if (i == 10) {
continue;
}
console.log(i);
}
<IPython.core.display.Javascript object>
Popcorn Hack for 3.8.4 Continue and Break
%%js
// Grading System in JavaScript
function gradeHomework(score) {
if (score >= 90 && score <= 100) {
return "A - Exceptional (90-100%): Surpasses all expectations with notable creativity or extensive effort.";
} else if (score >= 80 && score < 90) {
return "B - Very Good (80-89%): Meets all requirements with only a few minor inaccuracies.";
} else if (score >= 70 && score < 80) {
return "C - Acceptable (70-79%): Contains some missing elements; demonstrates a basic grasp of concepts.";
} else if (score >= 60 && score < 70) {
return "D - Needs Attention (60-69%): Lacks several key components; significant errors present.";
} else {
return "F - Unsatisfactory (0-59%): Shows minimal effort or misunderstanding of the material.";
}
}
function calculateGrade(popcornHacks, homeworkAssignments, submissionQuality) {
const totalScore = (popcornHacks * 0.4) + (homeworkAssignments * 0.5) + (submissionQuality * 0.1);
return totalScore;
}
// Example Usage
const popcornHacksScore = 80; // Score out of 100 for popcorn hacks
const homeworkScore = 85; // Score out of 100 for homework assignments
const submissionQualityScore = 90; // Score out of 100 for submission quality
const finalScore = calculateGrade(popcornHacksScore, homeworkScore, submissionQualityScore);
console.log(`Final Score: ${finalScore.toFixed(2)}`);
console.log(gradeHomework(finalScore));
<IPython.core.display.Javascript object>
Homework Hack 1
Try to add in two of the loops into your code, one in python and one in javascript.
This will help build your understanding on loops in both javascript and python
Additionally, try looping through a dictionary in order to be more creative with your code and personalize it
data_list = ["glowing unicorn", "singing cactus", 1234567, "spinning pizza", "mystical owl", 2.71828, "robot llama", "giant marshmallow"]
print("List:", data_list)
try:
index = int(input("Enter the index to remove: "))
if 0 <= index < len(data_list):
print("Removed:", data_list.pop(index))
else:
print("Invalid index.")
except ValueError:
print("Please enter a valid number.")
print("Updated list:", data_list)
%%js
let data_list = ["glowing unicorn", "singing cactus", 1234567, "spinning pizza", "mystical owl", 2.71828, "robot llama", "giant marshmallow"];
let person = { name: 'Arshia', age: 16, favorite_animal: 'penguin' };
// Loop through and print each item in data_list
console.log("Items in data_list:");
for (let item of data_list) {
console.log(item);
}
// Loop through person dictionary (keys and values)
console.log("\nPerson details:");
for (let key in person) {
console.log(`${key}: ${person[key]}`);
}
Homework Hack #2
Objective
In this task, you will create a modified version of the classic FizzBuzz game using a while loop. The program should print numbers from 1 to 50 with the following conditions:
- For multiples of 3, print “Fizz” instead of the number.
- For multiples of 5, print “Buzz” instead of the number.
- For numbers divisible by both 3 and 5, print “FizzBuzz”.
- For multiples of 7, print “Boom”.
Challenge
Modify the range to numbers between 50 and 100 and change the conditions accordingly (e.g., for multiples of 4 instead of 3).
Implementation
# FizzBuzz with a Twist Implementation
number = 1
while number <= 50:
output = ""
if number % 3 == 0:
output += "Fizz"
if number % 5 == 0:
output += "Buzz"
if number % 7 == 0:
output += "Boom"
# If output is still empty, it's just the number
if output == "":
output = str(number)
print(output)
number += 1
```python
# Challenge: Modified FizzBuzz for numbers 50 to 100
number = 50
while number <= 100:
output = ""
if number % 4 == 0:
output += "Fizz"
if number % 5 == 0:
output += "Buzz"
if number % 7 == 0:
output += "Boom"
if output == "":
output = str(number)
print(output)
number += 1
# User Authentication System Implementation
correct_username = "admin"
correct_password = "password123"
attempts_left = 3
authenticated = False
while attempts_left > 0:
username = input("Enter your username: ")
password = input("Enter your password: ")
if username == correct_username and password == correct_password:
authenticated = True
print("Login successful!")
break
else:
attempts_left -= 1
print(f"Incorrect credentials. Attempts left: {attempts_left}")
if not authenticated:
print("Account locked due to too many failed attempts.")
# Enhanced User Authentication System with Password Reset
correct_username = "admin"
correct_password = "password123"
attempts_left = 3
authenticated = False
while attempts_left > 0:
username = input("Enter your username: ")
password = input("Enter your password: ")
if username == correct_username and password == correct_password:
authenticated = True
print("Login successful!")
break
else:
attempts_left -= 1
print(f"Incorrect credentials. Attempts left: {attempts_left}")
if not authenticated:
print("Account locked due to too many failed attempts.")
reset = input("Would you like to reset your password? (yes/no): ").lower()
if reset == "yes":
security_answer = input("What is your favorite color? ")
if security_answer == "blue": # Example security question
new_password = input("Enter a new password: ")
print("Your password has been reset successfully.")
else:
print("Incorrect answer. Password reset failed.")
Homework Hack #3
Objective
In this assignment, we will create a simple task management program. The program will allow us to define a list of tasks, display them with their indices, and understand how to use functions and lists in Python.
Step 1: Define Your Tasks
We will start by creating a list of tasks that we want to manage.
Task List
# Define a list of tasks
tasks = [
"Complete the math homework",
"Read chapter 5 of the science book",
"Practice Python coding",
"Prepare for the history presentation",
"Go grocery shopping"
]
```python
def display_tasks(task_list):
print("Tasks:")
for index, task in enumerate(task_list):
print(f"{index + 1}: {task}")
# Call the function to display tasks
display_tasks(tasks)
Homework Hack #4
In this notebook, we will demonstrate two types of loops: a break loop in JavaScript and a continue loop in Python.
Objective
Create a break loop in JavaScript that increments numbers by 2 and stops when a certain condition is met.
Implementation
// JavaScript: Break Loop
for (let i = 0; i <= 20; i += 2) {
console.log(i);
if (i === 10) { // Change this condition as needed to break at a specific number
break; // Break the loop when i equals 10
}
}
```python
// JavaScript: Break Loop
for (let i = 0; i <= 20; i += 2) {
console.log(i);
if (i === 10) { // Change this condition as needed to break at a specific number
break; // Break the loop when i equals 10
}
}
# Python: Continue Loop
for i in range(11):
if i == 5:
continue # Skip the number 5
print(f"This number is {i}")