3.8.1/3.8.2 While loops/Nested loops
Basic concept for while loops
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 1
For this one ou have to find an error in the code to demonstrate the knowlege and correct the mistake ion new code cell here is code to find mistake and pls run it in console.log to check if it is right.
// Initialize the counter
let counter = 0;
// Loop while counter is less than 5
while (counter <= 5) { // Mistake: should be < 5
console.log("Counter is: " + counter); // Print the current counter value
// Increment the counter
counter = counter + 1; // This is correct but could be simplified to counter++
}
%%js
// Initialize the counter
let counter = 0;
// Loop while counter is less than 5
while (counter < 5) { // Corrected: < 5
console.log("Counter is: " + counter); // Print the current counter value
// Increment the counter
counter++; // Simplified increment
}
<IPython.core.display.Javascript object>