in reply to problem in output

Start adding lots of print statements to your code to narrow the problem down a bit. See also Basic debugging checklist.