Nov-26-2017, 09:30 PM
you should use string formatting
for nr in range(0, 100): print('{: >2}'.format(nr), end=" ") if nr % 10 == 9: print()
Help with loop
|
Nov-26-2017, 09:30 PM
you should use string formatting
for nr in range(0, 100): print('{: >2}'.format(nr), end=" ") if nr % 10 == 9: print()
Nov-27-2017, 09:56 AM
(Nov-26-2017, 09:30 PM)buran Wrote: you should use string formatting Thank you buran !
Nov-27-2017, 10:48 AM
The use of modulo is clever. Here a solution with a nested loop, which is the naive way:
for j in range(0, 100, 10): for i in range(j, j + 10): print('{:>2}'.format(i), end=' ') print()The outer loop counts from 0 to 90 with a step size of 10. So we get in the outer loop: 0, 10, 20, 30, 40, 50, 60, 70, 80, 90 The inner loop counts from j to j + 10. The inner loop is iterating with following range objects: [range(0, 10), range(10, 20), range(20, 30), range(30, 40), range(40, 50), range(50, 60), range(60, 70), range(70, 80), range(80, 90), range(90, 100)]In other words: The outer loop is representing the rows and the inner loop is representing the columns. The modulo operator in the other examples is using the fact, that 9 % 10 == 9, 19 % 10 == 9, 29 % 10 == 9...
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Nov-27-2017, 11:32 AM
(Nov-26-2017, 09:30 PM)buran Wrote: you should use string formattingWay too readable.for nr in range(0, 100): print('{: >2}'.format(nr), end=" ") if nr % 10 == 9: print() for nr in range(100): print("{:02}".format(nr), end="\n" if nr % 10 == 9 else " ") |
|