Computer Science, asked by suvarahul9502, 6 months ago

The retry function tries to execute an operation that might fail, it retries the operation for a number of attempts. Currently the code will keep executing the function even if it succeeds. Fill in the blank so the code stops trying after the operation succeeded

Answers

Answered by ppetros001
1

Answer:

def retry(operation, attempts):

 for n in range(attempts):

   if operation():

     print("Attempt " + str(n) + " succeeded")

     break

   else:

     print("Attempt " + str(n) + " failed")

retry(create_user, 3)

retry(stop_service, 5)

Explanation:

Answered by syed2020ashaels
0

Answer:

To make the retry function stop executing after a successful attempt, we can add a check to see if the operation was successful and break out of the loop if it was.

Explanation:

Here's an example implementation:

import time

def retry(operation, max_attempts):

   for i in range(max_attempts):

       result = operation()

       if result:

           return result

       time.sleep(1)

   raise Exception("Operation failed after {} attempts".format(max_attempts))

  • In this implementation, the operation parameter is a function that performs the operation we want to retry. The max_attempts parameter specifies how many times we want to retry the operation.
  • Inside the loop, we call operation() and store the result in result. If result is truthy (i.e., not None or False), we return it immediately. Otherwise, we wait for 1 second using time.sleep(1) before trying again.
  • If none of the attempts are successful, we raise an exception indicating that the operation failed after the maximum number of attempts.
  • With this implementation, if the operation succeeds on any attempt, the function will return immediately without further retries.

Learn more about function :

https://brainly.in/question/39142612

#SPJ3

Similar questions