I am not getting expected output in below code. It should print up to 7 but it is not printing.
n=5
for i in range(1,n+2):
for j in range(1,i):
print(j, end='')
print("\n")
I am not getting expected output in below code. It should print up to 7 but it is not printing.
n=5
for i in range(1,n+2):
for j in range(1,i):
print(j, end='')
print("\n")
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.
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")
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.