Iteration

For Loops: Used when you know how many times you want to repeat something. While Loops: Used when you don't know the number of repeats, but you have a condition to check. Do-While Loops: Like a while loop, but it will run at least once. Index Loops: Used to go through items in an array or list using their position (index). continue: Skips to the next repeat, ignoring the rest of the code in the loop. break: Stops the loop completely and doesn't continue further repeats.

%%javascript
for (let i = 3; i < 7; i++) {
    console.log(i);
}

The loop starts with i = 3. It runs as long as i is less than 7 (i < 7 is the condition). After each iteration, i is incremented by 1 (i++).

number = 14

while number <=100:
    if number % 3 == 0:
        print(number)
    number += 1

The variable number is set to 14, the while loop continues as long as number is less than or equal to 100, inside the loop, it checks if number % 3 == 0 (if the number is divisible by 3). If true, the number is printed. After each round, number is increased by 1.

person = {'name': 'Shriya', 'age': 15}

# Looping through keys
for key in person:
    print(key, person[key])

# Looping through values
for value in person.values():
    print(value)

# Looping through keys and values
for key, value in person.items():
    print(key, value)

The first loop prints both the keys and their corresponding values. The second loop prints just the values. The third loop prints both keys and values.

import random

flip = ""

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

print("Landed on heads!")

The loop will continue flipping until it randomly picks “heads”. Each flip is independently random, so the number of flips required to land on “heads” will vary each time the program runs.

# Part 1: FizzBuzz from 1 to 50
i = 1
while i <= 50:
    if i % 3 == 0 and i % 5 == 0:
        print("FizzBuzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    elif i % 7 == 0:
        print("Boom")
    else:
        print(i)
    i += 1

# Challenge: FizzBuzz from 50 to 100, but for multiples of 4 and 6
print("Challenge: Range from 50 to 100 with new rules")
i = 50
while i <= 100:
    if i % 4 == 0 and i % 6 == 0:
        print("FizzBuzz")
    elif i % 4 == 0:
        print("Fizz")
    elif i % 6 == 0:
        print("Buzz")
    elif i % 7 == 0:
        print("Boom")
    else:
        print(i)
    i += 1

If a number is divisible by both 3 and 5, it prints “FizzBuzz”. If it’s divisible only by 3, it prints “Fizz”. If it’s divisible only by 5, it prints “Buzz”. If it’s divisible by 7, it prints “Boom”. If none of the above conditions are met, it prints the number itself.

# Simulate a user login system with 3 attempts using a while loop (do-while behavior)

correct_username = "admin"
correct_password = "password123"
security_answer = "blue"  # Security question answer

attempts = 3
login_successful = False

while attempts > 0:
    # Prompt for username and password
    input_username = input("Enter username: ")
    input_password = input("Enter password: ")

    if input_username == correct_username and input_password == correct_password:
        print("Login successful!")
        login_successful = True
        break
    else:
        attempts -= 1
        if attempts > 0:
            print(f"Incorrect login. You have {attempts} attempt(s) left.")
        else:
            print("Account locked. You have used all attempts.")
            # Prompt for security question to reset the password
            answer = input("To reset your password, answer the security question: What is your favorite color? ")
            if answer.lower() == security_answer.lower():
                new_password = input("Password reset successful. Please set a new password: ")
                correct_password = new_password
                print("New password set successfully.")
                attempts = 3  # Reset attempts after password reset
            else:
                print("Security question failed. Account remains locked.")

if not login_successful and attempts == 0:
    print("Login failed. Please try again later.")

A user login system with 3 attempts and includes a password reset feature using a security question. The user has three attempts to enter the correct username and password. If the username and password are correct, the login is successful, and the program exits. Each incorrect login reduces the remaining attempts by 1. If the user uses all attempts, the account is locked, unless they answer a security question correctly of ‘What is your favorite color?’.

# List of tasks
tasks = [
    "Finish homework",
    "Practice basketball",
    "Eat dinner",
    "Watch tv",
    "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()

Makes a to-do list of tasks with numbered indices. The display_tasks function iterates through the tasks list and prints each task along with its index.

%%js
// List of tasks
const tasks = [
    "Finish homework",
    "Practice basketball",
    "Eat dinner",
    "Watch tv",
    "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();

This is a python version of the previous part preforming the same function of : Makes a to-do list of tasks with numbered indices. The display_tasks function iterates through the tasks list and prints each task along with its index.



%%javascript

for (let i = 2; i < 14; i++) {
  if (i === 6) {
    continue; 
  }
  console.log(i); 
}

<IPython.core.display.Javascript object>

The loop runs from i = 2 to i = 13, when i equals 6, the continue statement is executed, which skips the current iteration and jumps to the next number without executing console.log(i) for i = 6. For all other values of i, it prints the value to the console.

for i in range(1, 10):
    if i % 2 == 0:
        continue  # Skip the rest of the loop if i is even
    print(i)

The loop iterates over numbers from 1 to 9, when the number i is even (i % 2 == 0), the continue statement is triggered, causing the loop to skip the print(i) statement for that iteration, for odd numbers, it prints the value of i.

for (let i = 0; i <= 10; i += 2) {
    if (i > 8) {
        break; // Exit the loop when the number exceeds 8
    }
    console.log(i);
}

The JavaScript code runs through even numbers from 0 to 10, but it stops when i exceeds 8 due to the break statement.

for i in range(1, 10):
    if i % 2 == 0:
        continue  # Skip even numbers
    print(f"This number is {i}")

Your Python code iterates through numbers from 1 to 9 and prints only the odd numbers by skipping the even ones using the continue statement.