Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to start logging sensor data to a file.
Raspberry Pi
with open('sensor_data.txt', '[1]') as file: file.write('Temperature: 22C\n')
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w' erases existing data.
Using 'r' opens file for reading only.
✗ Incorrect
Using 'a' opens the file in append mode, so new data is added without erasing existing data.
2fill in blank
mediumComplete the code to read the last line of the log file.
Raspberry Pi
with open('sensor_data.txt', 'r') as file: lines = file.readlines() last_line = lines[1]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using [0] gets the first line, not the last.
Using [:1] returns a list with the first line.
✗ Incorrect
Using [-1] gets the last item from the list of lines.
3fill in blank
hardFix the error in the code to log data with a timestamp.
Raspberry Pi
import datetime now = datetime.datetime.now() with open('log.txt', 'a') as file: file.write(f"[1] - Sensor reading\n")
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using datetime.now() without import or formatting causes error.
Using now.time() gives only time, missing date.
✗ Incorrect
Using now.strftime formats the datetime object into a readable string for logging.
4fill in blank
hardFill both blanks to create a dictionary logging temperature readings above 25 degrees.
Raspberry Pi
log = {sensor[1]: reading for sensor, reading in readings.items() if reading [2] 25} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' filters wrong readings.
Not converting sensor names to uppercase.
✗ Incorrect
We convert sensor names to uppercase and filter readings greater than 25.
5fill in blank
hardFill all three blanks to filter and log sensors with readings below 20 and convert sensor names to lowercase.
Raspberry Pi
filtered_log = [1]: [2] for [3], value in sensor_data.items() if value < 20}
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'reading' instead of 'sensor' as loop variable.
Not converting sensor names to lowercase.
✗ Incorrect
We use sensor.lower() as keys, value as values, and sensor as the loop variable.