![]() |
Am i doing something wrong with this piece of code - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Am i doing something wrong with this piece of code (/thread-8660.html) |
Am i doing something wrong with this piece of code - pythoneer - Mar-02-2018 i am trying to get an output as follows: Quote:1 1 1with the following code for i in range(1, 4): for j in range(i, i + 3): if (j > 3): jdisplay = j % 3 else: jdisplay = j for k in range(j,j+3): if(k>3): kdisplay=k%3 else: kdisplay=k print(i,jdisplay,kdisplay)but i am getting output as below Quote:1 1 1 The difference is the 0 being printed instead of 3 (in bold) in the 3rd column, in the piece of code i have written i have asked it to do a modulo division only if the number is greater than 3, but is it doing even if it is equal to 3? or am i missing something RE: Am i doing something wrong with this piece of code - JustaNoOb - Mar-02-2018 I'm guessing because theres no remainder. for k in range(j,j+3):Starts at index 3 and ends on 6. 6%3 = 0 You could try checking it first and assign 3 if it has no remainder. There's probably a better way of doing it but this should work. kdisplay= k%3 if (k%3) else 3 for i in range(1, 4): for j in range(i, i + 3): if (j > 3): jdisplay = j % 3 else: jdisplay = j for k in range(j,j+3): kdisplay= k%3 if (k%3) else 3 print(i,jdisplay,kdisplay) RE: Am i doing something wrong with this piece of code - pythoneer - Mar-02-2018 wow, this works well, and oh my god your first post is the reply to my question...awesome .. but this seems to be hard coded approach, is there a better way of doing it? RE: Am i doing something wrong with this piece of code - JustaNoOb - Mar-02-2018 I've been hanging around the forum for a few weeks reading different posts but forgot to register ha. |