Python requires a colon ':' after except RateLimitError to start the block.
Step 2: Verify other parts
time.sleep() is valid, retrying call_api() is allowed, print syntax is correct.
Final Answer:
Missing colon after except RateLimitError -> Option C
Quick Check:
except needs colon ':' [OK]
Hint: except lines always end with a colon ':' [OK]
Common Mistakes:
Forgetting colon after except
Thinking sleep() is invalid in except
Believing retry is not allowed
5. You want to build an AI app that calls an API but respects rate limits by retrying after waiting. Which code snippet correctly implements this with error handling and exponential backoff?
hard
A. import time
wait = 1
for _ in range(3):
try:
response = call_api()
break
except RateLimitError:
time.sleep(wait)
wait *= 2
B. import time
wait = 1
while True:
try:
response = call_api()
break
except RateLimitError:
time.sleep(wait)
wait *= 2
C. import time
wait = 1
for _ in range(3):
try:
response = call_api()
except RateLimitError:
wait *= 2
time.sleep(wait)
else:
break
D. import time
wait = 1
while True:
try:
response = call_api()
except RateLimitError:
time.sleep(wait)
wait += 1
else:
break
Solution
Step 1: Understand exponential backoff with retries
We want to retry after waiting, doubling wait time each failure, and stop on success.
Step 2: Analyze options for correct loop and break
import time
wait = 1
while True:
try:
response = call_api()
break
except RateLimitError:
time.sleep(wait)
wait *= 2 uses while True loop, tries call_api(), breaks on success, and doubles wait after RateLimitError.
Step 3: Check other options
import time
wait = 1
for _ in range(3):
try:
response = call_api()
break
except RateLimitError:
time.sleep(wait)
wait *= 2 breaks on success but uses for loop with fixed tries (less flexible). import time
wait = 1
while True:
try:
response = call_api()
except RateLimitError:
time.sleep(wait)
wait += 1
else:
break increments wait linearly, not exponential. import time
wait = 1
for _ in range(3):
try:
response = call_api()
except RateLimitError:
wait *= 2
time.sleep(wait)
else:
break doubles wait before sleep, but order is less clear.
Final Answer:
import time
wait = 1
while True:
try:
response = call_api()
break
except RateLimitError:
time.sleep(wait)
wait *= 2 -> Option B
Quick Check:
Retry loop with exponential backoff = import time
wait = 1
while True:
try:
response = call_api()
break
except RateLimitError:
time.sleep(wait)
wait *= 2 [OK]
Hint: Use while True with break and double wait after error [OK]