1

how do you manipulate the for loop to display an output just like

5
54
543
5432
54321

I tried coding like

n=6
for i in range(0,n):
    for j in range (n,0):
        print(j,end="")
print(i)

but it would print this

0
1
2
3
4
5

Shouldn't it print first the 5 in loop j first

2 Answers 2

3

Almost good, but to go down from n, range requires the third parameter - step - to be -1:

for i in range(n,0,-1):
    for j in range (n,i-1,-1):
        print(j,end="")
    print()
Sign up to request clarification or add additional context in comments.

2 Comments

so i should replace the range in j to be (n,-1)?
i just tried it and its good.Can you explain it how it works? I'm kind off confused on how it performs the code.
2

A bunch of ways to solve this... here's one:

n = 5

for i in range(0, n):
    # Think of this range as "how many numbers to print on this line"
    for j in range(i + 1):
        # First number should be n, second n - 1, etc.
        print(n - j, end="")
    print() # newline before next i

(Note that I changed n to 5.)

2 Comments

I noticed you didn't put a second number in the j range. Why is it possible?
@CzarLuc Because the default value for the first argument is a zero.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.