5 Looping with if
Now we have the basics for conditionals with if
and looping with for
.
Lets try to bring them together!
Real world example¶
Imagine we have read some values from a sensor and want to take action if the value is above a threshold.
In this example, we might be reading from any number of sensors such as a:
- thermometer
- volume control
- light level sensor
- earthquake sensor with an accelerometer
- tilt sensor with a gyroscope
- microphone
In [2]:
Copied!
# these are the values we have read from our sensor
sensorValues = [0, 3, 5, 7, 12, 15, 27, 35, 2, 2, 2, 100]
# we define a threshold where we want to report the value
threshold = 12
for sensorValue in sensorValues:
if sensorValue > threshold:
print('WARNING: sensor value is above threshold', threshold, 'and has value', sensorValue)
# these are the values we have read from our sensor
sensorValues = [0, 3, 5, 7, 12, 15, 27, 35, 2, 2, 2, 100]
# we define a threshold where we want to report the value
threshold = 12
for sensorValue in sensorValues:
if sensorValue > threshold:
print('WARNING: sensor value is above threshold', threshold, 'and has value', sensorValue)
WARNING: sensor value is above threshold 12 and has value 15 WARNING: sensor value is above threshold 12 and has value 27 WARNING: sensor value is above threshold 12 and has value 35 WARNING: sensor value is above threshold 12 and has value 100
In this example, we loop over each item in sensorValues
and if it is greater than our threshold
, we print a warning.
Tutorial¶
- Make a list of integers
- Define a threshold
- Use a for loop to loop over its items and check if each item is less-than (
<
) a threshold.
In [1]:
Copied!
# write your code here (run your code with the run button).
# write your code here (run your code with the run button).