Basic Overview
Condition is always true if the condition is true you have seen it in math have you? 🙃 An example is x<8 or X>y or x>8
In inside the code you can run any code you want anything you want but it has to be true to statement
What happens inside the code
If you run the code it will run for infinate times unless, the statement is false then it will stop and continue to next line or stop oif it is last code
an example can be s`een down here The counter which is number set is = 0 and 0<10 and then it prints each number by +1
counter = 0
while counter <= 10:
print("Counter is:", counter)
counter += 1
print("Counter after incrementing:", counter)
Counter is: 0
Counter after incrementing: 1
Counter is: 1
Counter after incrementing: 2
Counter is: 2
Counter after incrementing: 3
Counter is: 3
Counter after incrementing: 4
Counter is: 4
Counter after incrementing: 5
Counter is: 5
Counter after incrementing: 6
Counter is: 6
Counter after incrementing: 7
Counter is: 7
Counter after incrementing: 8
Counter is: 8
Counter after incrementing: 9
Counter is: 9
Counter after incrementing: 10
Counter is: 10
Counter after incrementing: 11
%%js
// Initialize a variable
let counter = 0;
// While loop starts
while (counter <= 10) {
console.log("Counter is: " + counter);
counter++;
}
<IPython.core.display.Javascript object>
Popcorn Hack 3
For this one you have to find an error in the code to demonstrate the knowlege and correct the mistake in new code cell.
%%js
// Initialize the counter
let counter = 1;
// Loop while counter is less than 5
while (counter < 5) {
console.log("Counter is: " + counter); // Print the current counter value
// Increment the counter
counter++;
}
Popcorn Hack 4
Create the Outer Loop: Use a while loop that runs while outerFactor is less than or equal to 10. Initialize the Inner Loop Variable:
Inside the outer loop, create another variable called innerFactor and set it to 1. Create the Inner Loop: Inside the outer loop, use another while loop that runs while innerFactor is less than or equal to 10. Calculate the Product:
Inside the inner loop, calculate the product of outerFactor and innerFactor. Print the Product: Print the product using console.log(), formatting the output neatly. Increment the Inner Loop Variable:
After printing the product, increment innerFactor by 1. Move to the Next Line: After the inner loop finishes, print a new line to separate rows. Increment the Outer Loop Variable:
Increment outerFactor by 1 to move to the next row in the table.
%%html
<div id="multiplicationTable"></div>
<script>
function printMultiplicationTable() {
const tableSize = 10; // 10x10 table for multiplication from 1 to 10
let row = 1; // Initialize row counter
let tableContent = "<pre>"; // Using <pre> for preformatted text
// Outer loop: Runs while row is less than or equal to 10
while (row <= tableSize) {
let col = 1; // Initialize column counter
let rowString = ''; // String to hold the row
// Inner loop: Runs while col is less than or equal to 10
while (col <= tableSize) {
const product = row * col; // Calculate the product
rowString += product.toString().padStart(4, ' ') + ' '; // Add product to row string
col++; // Increment column counter
}
tableContent += rowString + "\n"; // Add the row string to the table content
row++; // Increment row counter
}
tableContent += "</pre>"; // Close the <pre> tag
document.getElementById("multiplicationTable").innerHTML = tableContent; // Print to the page
}
// Call the function to print the table
printMultiplicationTable();
</script>
Here is some code for extra credit: (asks questions regarging the multiplication table)
%%html
<div id="multiplicationTable"></div>
<div id="questionContainer"></div>
<input type="text" id="userAnswer" placeholder="Type your answer here" />
<button onclick="checkAnswer()">Submit Answer</button>
<div id="responseMessage"></div>
<script>
// Function to print the multiplication table in the notebook
function printMultiplicationTable() {
const tableSize = 10; // 10x10 table for multiplication from 1 to 10
let row = 1; // Initialize row counter
let tableContent = "<pre>"; // Using <pre> for preformatted text
// Outer loop: Runs while row is less than or equal to 10
while (row <= tableSize) {
let col = 1; // Initialize column counter
let rowString = ''; // String to hold the row
// Inner loop: Runs while col is less than or equal to 10
while (col <= tableSize) {
const product = row * col; // Calculate the product
rowString += product.toString().padStart(4, ' ') + ' '; // Add product to row string
col++; // Increment column counter
}
tableContent += rowString + "\n"; // Add the row string to the table content
row++; // Increment row counter
}
tableContent += "</pre>"; // Close the <pre> tag
document.getElementById("multiplicationTable").innerHTML = tableContent; // Print to the page
}
// Function to generate a random multiplication question and display it
function askMultiplicationQuestion() {
const num1 = Math.floor(Math.random() * 10) + 1; // Random number between 1 and 10
const num2 = Math.floor(Math.random() * 10) + 1; // Random number between 1 and 10
// Display the question in the notebook
document.getElementById("questionContainer").innerHTML = `What is ${num1} x ${num2}?`;
// Store the correct answer in a global variable for checking later
window.correctAnswer = num1 * num2;
}
// Function to check the user's answer
function checkAnswer() {
const userAnswer = parseInt(document.getElementById("userAnswer").value); // Get the user's input
// Check if the answer is correct
if (userAnswer === window.correctAnswer) {
document.getElementById("responseMessage").innerHTML = "Congratulations! Your answer is correct.";
document.getElementById("responseMessage").style.color = "green";
} else {
document.getElementById("responseMessage").innerHTML = "Oops! That's not correct. Try again.";
document.getElementById("responseMessage").style.color = "red";
// Generate a new question
askMultiplicationQuestion();
}
}
// Call the function to print the multiplication table
printMultiplicationTable();
// Call the function to ask the first multiplication question
askMultiplicationQuestion();
</script>
Here is popcorn hack 2
%%html
<canvas id="ticTacToeCanvas" width="300" height="300"></canvas>
<div id="status" style="font-size: 18px; margin-top: 10px; font-weight: bold;"></div>
<script>
// Avoid redeclaring variables if they already exist
if (!window.canvas) {
const canvas = document.getElementById("ticTacToeCanvas");
const ctx = canvas.getContext("2d");
const statusElement = document.getElementById("status");
const boardSize = 3;
const cellSize = canvas.width / boardSize;
let board = [
[null, null, null],
[null, null, null],
[null, null, null]
];
let currentPlayer = "X"; // X starts first
function drawBoard() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas before drawing
ctx.strokeStyle = "#000000"; // Black color for grid lines
ctx.lineWidth = 2;
// Draw the grid
for (let i = 1; i < boardSize; i++) {
ctx.beginPath();
ctx.moveTo(i * cellSize, 0);
ctx.lineTo(i * cellSize, canvas.height);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(0, i * cellSize);
ctx.lineTo(canvas.width, i * cellSize);
ctx.stroke();
}
}
function drawMarks() {
ctx.font = "60px Arial";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
// Draw the X's and O's
for (let row = 0; row < boardSize; row++) {
for (let col = 0; col < boardSize; col++) {
if (board[row][col]) {
ctx.fillStyle = board[row][col] === "X" ? "#2980B9" : "#27AE60"; // Blue for X, Green for O
ctx.fillText(board[row][col], col * cellSize + cellSize / 2, row * cellSize + cellSize / 2);
}
}
}
}
// Handle click event
canvas.addEventListener("click", (event) => {
const x = event.offsetX;
const y = event.offsetY;
const row = Math.floor(y / cellSize);
const col = Math.floor(x / cellSize);
if (board[row][col] === null) {
board[row][col] = currentPlayer;
currentPlayer = currentPlayer === "X" ? "O" : "X"; // Switch player
drawBoard();
drawMarks();
checkGameStatus();
}
});
// Check if a player has won or if it's a draw
function checkGameStatus() {
if (checkWinner()) {
updateStatus(`${currentPlayer === "X" ? "O" : "X"} wins!`);
resetGame();
} else if (isBoardFull()) {
updateStatus("It's a draw!");
resetGame();
} else {
updateStatus(`It's Player ${currentPlayer}'s turn.`);
}
}
// Update the status message
function updateStatus(message) {
statusElement.textContent = message;
}
// Check if a player has won
function checkWinner() {
// Check rows, columns, and diagonals
for (let i = 0; i < boardSize; i++) {
// Check rows
if (board[i][0] && board[i][0] === board[i][1] && board[i][1] === board[i][2]) {
return true;
}
// Check columns
if (board[0][i] && board[0][i] === board[1][i] && board[1][i] === board[2][i]) {
return true;
}
}
// Check diagonals
if (board[0][0] && board[0][0] === board[1][1] && board[1][1] === board[2][2]) {
return true;
}
if (board[0][2] && board[0][2] === board[1][1] && board[1][1] === board[2][0]) {
return true;
}
return false;
}
// Check if the board is full (draw)
function isBoardFull() {
for (let row = 0; row < boardSize; row++) {
for (let col = 0; col < boardSize; col++) {
if (board[row][col] === null) {
return false;
}
}
}
return true;
}
// Reset the game
function resetGame() {
setTimeout(() => {
board = [
[null, null, null],
[null, null, null],
[null, null, null]
];
drawBoard();
drawMarks();
updateStatus(`It's Player ${currentPlayer}'s turn.`);
}, 1000); // Delay reset for 1 second
}
// Initialize the game board
drawBoard();
drawMarks();
updateStatus(`It's Player ${currentPlayer}'s turn.`);
}
</script>