Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with loop
#11
you should use string formatting

for nr in range(0, 100):
    print('{: >2}'.format(nr), end=" ")
    if nr % 10 == 9:
        print()
Reply
#12
(Nov-26-2017, 09:30 PM)buran Wrote: you should use string formatting

for nr in range(0, 100):
    print('{: >2}'.format(nr), end=" ")
    if nr % 10 == 9:
        print()

Thank you buran !
Reply
#13
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!
Reply
#14
(Nov-26-2017, 09:30 PM)buran Wrote: you should use string formatting
for nr in range(0, 100):
    print('{: >2}'.format(nr), end=" ")
    if nr % 10 == 9:
        print()
Way too readable.
for nr in range(100):
    print("{:02}".format(nr), end="\n" if nr % 10 == 9 else " ")
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020