24  While loop

Author

Andres Patrignani

Published

January 8, 2024

A while loop is used to repeatedly execute a block of code as long as a certain condition remains true. Unlike for loops, the while loop is particularly useful when the number of iterations isn’t predetermined, and you need to keep running the code until a specific condition is met or changes.

Syntax

while condition:
    # Code to execute repeatedly

condition: A Boolean expression that determines whether the loop continues.

Let’s look at a trivial example:

A = 0
while A < 3:
    print(A)
    A += 1
    
0
1
2

This example will only print values 0, 1, and 2. As soon as the third iteration ends, the value of A becomes 3, the condition that A<3 is no longer true, and the while loop breaks before starting the fourth iteration.

Example 1: Irrigation decision

In this example we simulate a simple irrigation system that adjusts water application based on the soil moisture level, ensuring that the crop receives adequate water. The system checks the soil moisture level every day and decides whether to irrigate based on the soil moisture level. We assume that evapotranspiration reduces the moisture level daily, and that irrigation increases the soil moisture.

soil_moisture = 90 # initial soil moisture (mm)
moisture_threshold = 70 # moisture  below which irrigation is needed (mm)
irrigation_amount = 20 # irrigation amount (mm)
daily_et = 5 # daily evapotranspiration (mm)

# Simulate daily check over a 10-day period
day = 0
while day < 10:
    print(f"Day {day + 1}: Soil moisture is {soil_moisture}%.")
    
    # Check if irrigation is needed
    if soil_moisture < moisture_threshold:
        print("Irrigating...")
        soil_moisture += irrigation_amount
        print(f"Soil moisture after irrigation is {soil_moisture}%.")
    else:
        print("No irrigation needed today.")
    
    # Update soil moisture for next day
    soil_moisture -= daily_et
    day += 1
Day 1: Soil moisture is 90%.
No irrigation needed today.
Day 2: Soil moisture is 85%.
No irrigation needed today.
Day 3: Soil moisture is 80%.
No irrigation needed today.
Day 4: Soil moisture is 75%.
No irrigation needed today.
Day 5: Soil moisture is 70%.
No irrigation needed today.
Day 6: Soil moisture is 65%.
Irrigating...
Soil moisture after irrigation is 85%.
Day 7: Soil moisture is 80%.
No irrigation needed today.
Day 8: Soil moisture is 75%.
No irrigation needed today.
Day 9: Soil moisture is 70%.
No irrigation needed today.
Day 10: Soil moisture is 65%.
Irrigating...
Soil moisture after irrigation is 85%.

Example 2: Guess the soil taxonomic order

The soil taxonomic orders form the highest category in the soil classification system, each order representing distinct characteristics and soil formation processes. The twelve orders provide a framework for understanding soil properties and their implications for agriculture, environmental management, and land use. This website has great pictures of real soil profiles and additional useful information.

It’s always fun to play games, but crafting your own is even better. This exercise was written so that you can change the information contained in the database dictionary with some other data that sparks your interest. For soil scientists, this is an excellent opportunity to review your knowledge about the soil taxonomy.

import random

# Dictionary of soil orders with a hint
database = {
    "Alfisols": ["Fertile, with subsurface clay accumulation.", "Starts with 'A'"],
    "Andisols": ["Formed from volcanic materials, high in organic matter.", "Starts with 'A'"],
    "Aridisols": ["Dry soils, often found in deserts.", "Starts with 'A'"],
    "Entisols": ["Young soils with minimal horizon development.", "Starts with 'E'"],
    "Gelisols": ["Contain permafrost, found in cold regions.", "Starts with 'G'"],
    "Histosols": ["Organic, often water-saturated soils like peat.", "Starts with 'H'"],
    "Inceptisols": ["Young, with weak horizon development.", "Starts with 'I'"],
    "Mollisols": ["Dark, rich in organic matter, found under grasslands.", "Starts with 'M'"],
    "Oxisols": ["Highly weathered, tropical soils.", "Starts with 'O'"],
    "Spodosols": ["Acidic, with organic and mineral layers.", "Starts with 'S'"],
    "Ultisols": ["Weathered, acidic soils with subsurface clay.", "Starts with 'U'"],
    "Vertisols": ["Rich in clay, expand and contract with moisture.", "Starts with 'V'"]
}


# Select a random soil taxonomic order and its hints
# Each item is a list of tuples
selection, hints = random.choice(list(database.items()))
hints_iter = iter(hints)

print("Guess the soil taxonomic order! Type 'hint' for a hint.")

# Initial hint
print("First Hint:", next(hints_iter))

# While loop for guessing game
while True:
    guess = input("Your guess: ").strip().lower()

    if guess == selection.lower():
        print(f"Correct! It was {selection}.")
        break
        
    elif guess == "hint":
        try:
            print("Hint:", next(hints_iter))
        except StopIteration:
            print("No more hints. Please make a guess.")
    else:
        print("Incorrect, try again or type 'hint' for another hint.")
Guess the soil taxonomic order! Type 'hint' for a hint.
First Hint: Highly weathered, tropical soils.
Your guess:  Oxisols
Correct! It was Oxisols.

Explanation

The iter() function is used to create an iterator from an iterable object, like a list or a dictionary. Once you have an iterator, you can use the next() function to sequentially access elements from the iterator. Each call to next() retrieves the next element in the sequence. When next() reaches the end of the sequence and there are no more elements to return, it raises a StopIteration exception. This combination of a loop and iter() allows for a controlled iteration process, especially useful in situations where you need to process elements one at a time.

The strip() method removes any leading and trailing whitespace (like spaces, tabs, or new lines) from the input string. This is helpful to ensure that extra spaces do not affect the comparison of the user’s guess to the correct answer.

The lower() method then converts the string to lowercase. This ensures that the comparison is case-insensitive, meaning that “Oxisols”, “oxisols”, and “OXISOLS” are all treated as the same guess.

References

  • The twelve orders of soil taxonomy. United States Department of Agriculture website: https://www.nrcs.usda.gov/resources/education-and-teaching-materials/the-twelve-orders-of-soil-taxonomy. Accessed on 8 January 2024