Python Exercise: Invoke a given function after specific milliseconds
Python Functions: Exercise - 21 with Solution
Write a Python program that invokes a function after a specified period of time.
Sample Solution:
Python Code:
# Import specific functions 'sleep' from the 'time' module and the 'math' module
from time import sleep
import math
# Define a function named 'delay' that delays the execution of a function by the given milliseconds
def delay(fn, ms, *args):
# Sleep for the specified number of milliseconds
sleep(ms / 1000)
# Call the provided function 'fn' with the given arguments '*args' and return the result
return fn(*args)
# Print a message indicating the operation that follows
print("Square root after specific milliseconds:")
# Call the 'delay' function with a lambda function to calculate square roots after specific delays
# Print the square root of 16 after a delay of 100 milliseconds
print(delay(lambda x: math.sqrt(x), 100, 16))
# Print the square root of 100 after a delay of 1000 milliseconds
print(delay(lambda x: math.sqrt(x), 1000, 100))
# Print the square root of 25100 after a delay of 2000 milliseconds
print(delay(lambda x: math.sqrt(x), 2000, 25100))
Sample Output:
Square root after specific miliseconds: 4.0 10.0 158.42979517754858
Explanation:
In the exercise above the code demonstrates the usage of the "delay()" function, which delays the execution of a provided function ('fn') by a specified number of milliseconds ('ms'). It imports the necessary modules, defines the "delay()" function, and then applies the "delay()" function to calculate square roots after specific delays, using lambda functions with different arguments and delays provided in milliseconds.
Flowchart:
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to detect the number of local variables declared in a function.
Next: Date Time Exercise Home
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/python-functions-exercise-21.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics