Consider this Python code snippet that reads a soil moisture sensor value and decides whether to water the plant.
moisture = 350
if moisture < 300:
print("Watering plant")
else:
print("Soil is moist enough")What will this code print?
moisture = 350 if moisture < 300: print("Watering plant") else: print("Soil is moist enough")
Think about the condition: is 350 less than 300?
The moisture value is 350, which is not less than 300, so the else block runs, printing "Soil is moist enough".
This code controls a water pump based on a boolean variable pump_on. What is the output?
pump_on = False
if pump_on:
print("Pump is running")
else:
print("Pump is off")pump_on = False if pump_on: print("Pump is running") else: print("Pump is off")
Remember that False means the condition is not true.
Since pump_on is False, the else block runs and prints "Pump is off".
Look at this code snippet that should water the plant once when soil is dry, but it keeps watering endlessly. What is the cause?
while True:
moisture = 250
if moisture < 300:
print("Watering plant")
else:
print("Soil is moist enough")while True: moisture = 250 if moisture < 300: print("Watering plant") else: print("Soil is moist enough")
Think about what happens to the moisture value each time the loop runs.
The moisture value is always set to 250 inside the loop, so the condition moisture < 300 is always true, causing infinite watering.
Choose the code snippet that correctly reads a moisture sensor and waters the plant if dry.
Remember Python needs a colon and indentation for blocks.
Option A has the correct colon after the if statement and indented block for water_plant().
This code runs a watering pump based on sensor readings in a list. How many times will it print "Pump running"?
moisture_readings = [320, 280, 290, 310, 270]
pump_runs = 0
for moisture in moisture_readings:
if moisture < 300:
print("Pump running")
pump_runs += 1
print(pump_runs)moisture_readings = [320, 280, 290, 310, 270] pump_runs = 0 for moisture in moisture_readings: if moisture < 300: print("Pump running") pump_runs += 1 print(pump_runs)
Count how many values in the list are less than 300.
The values 280, 290, and 270 are less than 300, so the pump runs 3 times.