How do I implement this function in Python?

I’m trying to implement the monitor function in Python.

This function must display at regular interval the date followed by the return of the “measure” function. It stops after cycles executions and the interval will never be less than 1.

The function’s execution time must be less than (cycles + 1) * interval

def monitor(interval=1.0, cycles=42):

def measure():

time.sleep(random.random())

return random.randint(123, 456)

pass

1 Like

Could you put your code in a Markdown code block? There’s not formatting to it and so all indentation is missing.

1 Like

Maybe something like this?

from random import randint
from time import sleep
from datetime import datetime


# Time between measurements in seconds
DEFAULT_INTERVAL = 1
# How many times the measurements are executed.
DEFAULT_CYCLES = 42

def monitor(interval, cycles):
    """Display measurements."""
    for cycle in range(1, cycles+1):
        print("Date: {}, Reading: {}".format(datetime.today(), measure()))
        sleep(interval)


def measure():
    """Take measurements."""
    return randint(123, 456)


def main():
    monitor(DEFAULT_INTERVAL, DEFAULT_CYCLES)


main()

I took sleep away from the measure function, because I thought maybe that one should do just one thing.