You have a series of elif statements yet you are doing a return inside each one. How about changing all of the return x to ret = x and then at the end of the function do return ret. It should make the code easier to read