0
How to print this? Using for loop
Print the given pattern: 12345 1234 123 12 1
23 Respostas
+ 7
You can see that from top to bottom, there are 5 rows
So first we have to make it using for loop
for i in range(6,0,-1):
Here You might be wondering why I set the range as above....
The reason is simple... I am thinking about the next loop within it.
For the first row, the digits are from 1 to 5
This means range has to be from 1 to 6 i.e, range(1,6) because last digit is not taken.
For next line range(1,5)
next line range(1,4)
.
.
.
Can you see a pattern here?
The stop argument is decreasing by 1. Now the question is, how to control the stop argument in loop...
The answer is simple, let it take input from previous loop.
for i in range(6,0,-1):
will assign values to i as
6
5
4
3
2
1 (0 is not taken as it is in the stop argument)
See a similarity here?
We now have everything we need, especially the logic.
The code should something be
for i in range(6,0,-1):
for j in range(1,i):
print(j)
BUT, we are not finished here.
This code will NOT print the numbers as shown in your output.
+ 4
Utkarsh Sharma, we should help people to find a solution themselves, not just give it to them.
This may have been school homework, which you have now done for the student.
+ 3
You can simply use several print() functions
+ 3
To do that all we have to do is convert it into a string. You can see the final code below
for i in range(6,0,-1):
op = ""
for j in range(1,i):
op = op + str(j)
print(op)
Try this if it gives the same output.
+ 2
HonFu Okay!
I also thought that first that is why I gave some explanation so that s*he doesn't ask a similar question even if for a homework.
+ 2
Utkarsh Sharma, if you had stopped there, s*he would have at least had to do *something* themselves. š
I understand you just wanted to help.
But please keep this in mind for the future. Don't let this become a place (even more) where people just make accounts to get their homework done for them.
+ 2
HonFu I'll keep that in mind!
+ 1
It is a loop that prints array's lenght - 1 each iteration.
+ 1
I have seen many useless question today so I was thinking if any moderator can delete them...
+ 1
Utkarsh Sharma, it is done, but (luckily) mostly not with a snap of the fingers.
You can read an outline of how the system works here:
https://www.sololearn.com/Moderator-Guidelines/
+ 1
Sapthameeksha I have fully explained this... But the words limit reached so half of it is in another comment/answer...
+ 1
for i in range(1,7):
for j in range(1,7-i):
print(j,end='')
print()
0
HonFu Can a moderator delete a question?
0
Yes, Utkarsh Sharma, why do you ask?
0
Whatever please give full explanations as half answers can confuse us ...š
0
MULUKUTLA. JYOTSNA MANASA That's a nice code...
Does the end="" argument prints everything in same line?
0
Yes . Otherwise by default print() prints every thing in new line
0
j = 7
for a in range(5):
j -= 1
print()
for i in range(1,j):
print(i,end='')
0
suleiman akin