Print the Number series in Pyhon

Question:

Help me to solve this number series question:

input : 5

Output:

2 
3 4 
4 5 6
5 6 7 8
6 7 8 9 10

My program :

rows = 6  # number of rows in the pattern
start_num = 2  # starting number for the first row

for i in range(1,rows):
    for j in range(i):
        print(start_num, end=' ')
        start_num += 1
    print()
Asked By: Exclusive

||

Answers:

You can do this with a single loop and the range() function:

rows = 6  # number of rows in the pattern
start_num = 2  # starting number for the first row

for i in range(rows):
    print(*range(start_num+i, start_num+1+i+i))

The * before the range() function will expand each iteration of the range() function into a separate parameter to print().

Answered By: Michael M.

Recognize that

  • the first number in the ith row is 1 + i.
  • the first number in each row increases by 1 every row (so our outer loop just needs to be for i in range(1, n_rows+1)
  • the ith row has i elements
  • the rest of the row just increments from that first number (so the inner loop will be for j in range(first_num, first_num+i)
for i in range(1, n_rows+1):
    first_number = 1 + i
    for j in range(first_number, first_number + i):
        print(j, end=" ")

    print()

which prints:

2 
3 4 
4 5 6 
5 6 7 8 
6 7 8 9 10
Answered By: Pranav Hosangadi
rows = 5
for i in range(rows+1):
    for j in range(i):
        print(i + j + 1, end=" ")
    print()

You can try this..

Answered By: Soham