Shivanshu Singh
Shivanshu Singh

Reputation: 21

why "num = 1" inside the loop is not incrementing?

I was debugging the code and I don't understand why the num variable inside the for-loop is not incrementing and only (1) is incrementing ?

def numpat(n):

    num = 1                            ----- (1)


    for i in range(n):

        num = 1                        ------ (2)

        for j in range(i + 1):
            print(num, end=" ")
            num = num + 1               ----- (3)

        print("\r")

Upvotes: 0

Views: 78

Answers (2)

Kent Shikama
Kent Shikama

Reputation: 4060

Is the below output not what you expected?

In [1]: n = 5                                                                                 

In [2]: for i in range(n): 
   ...:  
   ...:     num = 1 
   ...:  
   ...:     for j in range(i + 1): 
   ...:         print(num, end=" ") 
   ...:         num = num + 1 
   ...:  
   ...:     print("\r") 
   ...:                                                                                       
1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5

Edit: Counterfactual output if n=1 wasn't in the inner loop.

In [1]: n = 5                                                                   

In [2]: num = 1                                                                 

In [3]: for i in range(n): 
   ...:     for j in range(i + 1): 
   ...:         print(num, end=" ") 
   ...:         num = num + 1 
   ...:     print("\r") 
   ...:                                                                         
1 
2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15

Upvotes: 3

codekls
codekls

Reputation: 189

Because you're setting the value of num to 1 everytime after the first loop i.e for i in range(n):. You can ignore that step and it'll work just fine.

Upvotes: 1

Related Questions