-1

I am not getting expected output in below code. It should print up to 7 but it is not printing.

Here is the output screenshot

n=5
for i in range(1,n+2):
    for j in range(1,i):
        print(j, end='')
    print("\n")
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
subhanshu kumar
  • 372
  • 3
  • 10
  • 1
    *" it should print till 7"*.. so `n = 7` ? Any reason why you used `n=5` ? – Austin Jun 25 '19 at 17:01
  • 4
    Range's stopping point is *ex*clusive - `i` is at most `6`, `j` is at most `5`. If you want to print up to `7`... `n = 7`? – jonrsharpe Jun 25 '19 at 17:04
  • 3
    Possible duplicate of [Why does range(start, end) not include end?](https://stackoverflow.com/questions/4504662/why-does-rangestart-end-not-include-end) – pault Jun 25 '19 at 17:07

3 Answers3

2

So, I didn't understand why you used n=5, when n=7 do the work, exactly like you wanted. I saw that you already have the answer using n=5 so I'm putting here a a solution with n=7 with some prints that will help you to understand what is happening inside these two nested loops.

n = 7
for i in range(1, n+2):
    for j in range(1, i):
        print("j:", j, end =" ")
    print("i:", i)
    print("***")

The output will be:

i: 1
***
j: 1 i: 2
***
j: 1 j: 2 i: 3
***
j: 1 j: 2 j: 3 i: 4
***
j: 1 j: 2 j: 3 j: 4 i: 5
***
j: 1 j: 2 j: 3 j: 4 j: 5 i: 6
***
j: 1 j: 2 j: 3 j: 4 j: 5 j: 6 i: 7
***
j: 1 j: 2 j: 3 j: 4 j: 5 j: 6 j: 7 i: 8

Did you notice what happens when for j in range(1, 1) ? no j is printed, so for j in range(1, 2), prints 1 for j and i is 2.

That's why your code with n = 5 was not working. When i is 6, j is 5 and for i in range(1, 7) only goes till i=6.

n = 5
for i in range(1, n+2):
    for j in range(1, i):
        print("j:", j, end =" ")
    print("i:", i)
    print("***")

The output:

i: 1
***
j: 1 i: 2
***
j: 1 j: 2 i: 3
***
j: 1 j: 2 j: 3 i: 4
***
j: 1 j: 2 j: 3 j: 4 i: 5
***
j: 1 j: 2 j: 3 j: 4 j: 5 i: 6
***

But, I really think you should get used to work with 0 based ranges.

Andressa Cabistani
  • 463
  • 1
  • 5
  • 14
0

The second parameter in the range() function is a stop value. It will not be included in the loop. So, your loops need to add 1 to the second parameter of both ranges:

n=5
for i in range(1,n+2 + 1):
    for j in range(1,i + 1):
        print(j, end='')
    print("\n")

You should get used to using zero based ranges however:

n=5
for i in range(n+2):
    for j in range(i+1):
        print(j+1, end='')
    print("\n")
Alain T.
  • 40,517
  • 4
  • 31
  • 51
-1

for i in range(1,n+2) n+2 is incorrect syntax so make a new variable called x and assine it n+2 EG.:

x = n + 2

To get numbers up to 7, x must equal n + 4 EG.:

n=5
x = n + 4
for i in range(1,x):
    for j in range(1,i):
        print(j, end='')
        print("\n")

Also indentations are imprtant in python.