Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Loops and Conditionals

Flow Control

Flow control statements allow us to change the execution path of our code. Instead of running every line from top to bottom, we can make decisions (Conditionals) or repeat tasks (Loops).

Conditionals (if, elif, else)

Execute a block of code if a certain condition is true, otherwise execute another block.

Conditional statements check if a logical condition is True.

  • if: If the condition is true, execute the code.

  • elif: “Else If” - Checked only if the previous if failed.

  • else: Executed if none of the above were true.

Output
Low Yield

for loop

Repeats a block of code a specific number of times or for each item in an iterable.

Output
--- Surveyed Crops ---
Inspecting: Palay
Inspecting: Corn
Inspecting: Coconut
Inspecting: Mango

Using range(): To loop a specific number of times (e.g., simulating 5 plots).

Output
Surveying Plot #1
Surveying Plot #2
Surveying Plot #3
Surveying Plot #4
Surveying Plot #5

while loop

Repeats a block of code as long as a specified condition is true.

Output
--- Loading Truck ---
Current Load: 100 kg
Current Load: 200 kg
Current Load: 300 kg
Current Load: 400 kg
Current Load: 500 kg
Current Load: 600 kg
Current Load: 700 kg
Current Load: 800 kg
Current Load: 900 kg
Current Load: 1000 kg
Truck is full!

if-else + for

Output
Not mango!
Not mango!
Not mango!
Mango!

Loop Controls (break, continue)

  • break: Exits the loop immediately.

  • continue: Skips the current turn and goes to the next one.

Output
--- Irrigation Report ---
Surveying Farm A...
Skipping Farm B (Rainfed)
Surveying Farm C...