Nested loops confusion
Hi, I expect this is very obvious for anyone who knows what they're doing - but I don't understand what's the problem with the following code. I was intending that the program cycle through all i and j (ie. all possible (i,j) coordinates, but the output when I run the program shows me up to "1 99 plot 3 1 100 plot 2 done j" and doesn't perform the print functions for any i > 1. Help much appreciated! :) Matt corna = int(raw_input("CornA? ")) cornb = int(raw_input("CornB? ")) side = int(raw_input("Side? ")) i = 0 j = 0 for i in range(100): for j in range(100): x = corna + i * side / 100 y = cornb + j * side / 100 c = int(x^2 + y^2) if c%3 == 1: print i print j print "plot 1" elif c%3 == 2: print i print j print "plot 2" elif c%3 == 0: print i print j print "plot 3" print "done j" print "Done i" -- http://mail.python.org/mailman/listinfo/python-list
Re: Nested loops confusion
Oops, I forget to reset the j after the inner loop. Always manage to work these things out just after asking for help! ;-) Matthew Graham wrote: > Hi, > > I expect this is very obvious for anyone who knows what they're doing - > but I don't understand what's the problem with the following code. I > was intending that the program cycle through all i and j (ie. all > possible (i,j) coordinates, but the output when I run the program shows > me up to > > "1 > 99 > plot 3 > 1 > 100 > plot 2 > done j" > > and doesn't perform the print functions for any i > 1. > > Help much appreciated! :) > > Matt > > > corna = int(raw_input("CornA? ")) > cornb = int(raw_input("CornB? ")) > side = int(raw_input("Side? ")) > i = 0 > j = 0 > for i in range(100): > for j in range(100): > x = corna + i * side / 100 > y = cornb + j * side / 100 > c = int(x^2 + y^2) > if c%3 == 1: > print i > print j > print "plot 1" > elif c%3 == 2: > print i > print j > print "plot 2" > elif c%3 == 0: > print i > print j > print "plot 3" > print "done j" > print "Done i" > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Nested loops confusion
Thanks very much for the advice, have tidied it up and tested and seems to be working as needed. I'm still not sure what was stopping the inner loop from working earlier - but removing the redundancy in "j=0" and so on seems to have solved it. Matt Dennis Lee Bieber wrote: > If that worked, you've got some weird code -- and it isn't what was > posted... Zeroing "j" does NOTHING, since the for loop assigns all > values to it, from 0..n-1 > > for loop indices do not need to be pre-initialized. -- http://mail.python.org/mailman/listinfo/python-list