This can be done two ways :
scripted expression : which should be one line of code and it may get complicated
driver function : this will make it a lot easier to control and create complex driver, we define a function then use it in the scripted expression
scripted expression :
floor(b/(2*pi))*pi/2 + (cos(b)>0 and sin(b)<0)*(b-1.5*pi) + (b< 0)*2*pi
where b is the angle of the red cube

driver function:
we define a new function calc_angle() and add it to the driver namespace, this function calculates the angle the same as the scripted expression but its easier to read, update and reuse in multiple drivers .
run the script in blender's text editor
import bpy
from math import *
two_pi = 2*pi
pi_two = pi/2
#create new function
def calc_angle(angle):
new_angle = floor(angle/two_pi)*pi_two
if cos(angle) > 0 and sin(angle) < 0 :
if angle > 0 :
new_angle += angle-1.5*pi
else :
new_angle += two_pi + angle-1.5*pi
return new_angle
#add the function to the driver namespace
bpy.app.driver_namespace['calc_angle'] = calc_angle
and setup the driver as follows :
