In the previous levels, our code ran once and then stopped. But imagine if you had to print "I LOVE PYTHON" 1,000 times—you wouldn't want to type it out manually! In Level 9, we introduce the WHILE LOOP. At FLORA WORLD CODING, we use loops to keep a program running as long as a certain condition is true.
A WHILE loop works very similarly to an IF statement, but with a twist: it repeats. The computer checks the condition; if it's true, it runs the code inside and then jumps back to the top to check again.
IF YOUR CONDITION IS ALWAYS TRUE (LIKE WHILE 1 == 1:), YOUR COMPUTER WILL GET STUCK. ALWAYS ENSURE YOUR LOOP HAS A WAY TO STOP!
TRY THIS: CREATE A VARIABLE ENERGY = 10. WRITE A WHILE LOOP THAT PRINTS "PLANTING SEEDS..." WHILE ENERGY IS GREATER THAN 0. INSIDE THE LOOP, SUBTRACT 1 FROM ENERGY EACH TIME.