Postgresql While Loop Exit In Python A Function