Rewriting code for python