What really happens in this code | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

What really happens in this code

How each loop works? https://code.sololearn.com/c3UBQ5p302ht/?ref=app

6th Aug 2021, 4:38 AM
alagammai uma
alagammai uma - avatar
10 Answers
+ 6
Hi alagammai! Inorder to understand this code, it's better to divide it into two snippets. 1. Without variable j, output pattern would be like this (for i in range(1,10,2): print(i*'*')), here i = 1,3,5... * *** ***** 2. After you added variable j with i times '*', each line of snippet1 is added with j times space hence, j is decreasing in each iteration. J = 9,8,7, (spaces) ........* ......*** .....*****
6th Aug 2021, 5:04 AM
Python Learner
Python Learner - avatar
6th Aug 2021, 5:15 AM
Abs Sh
Abs Sh - avatar
+ 2
Okay. First line: j = 9 (pretty obvious) Second line: for i in range (1, 10, 2): This for loop will go from 1 through to 9 in increments of 2 i.e 1, 3, 5, 7, 9. Third line: print(' ' * j + i * '*') This is the part that may confuse you. This line prints : "j" spaces, then prints "i" stars. In the first run of the loop, it will print 9 spaces, then 1 star. In the second run, it will print 8 spaces, then 3 stars (j is decremented by 1 after each loop run: j -= 1).... In the last run of the loop it will print 5 spaces and 9 stars.
6th Aug 2021, 4:56 AM
David Akhihiero
David Akhihiero - avatar
6th Aug 2021, 5:07 AM
alagammai uma
alagammai uma - avatar
+ 2
alagammai uma 1st iteration: 9 'space' (j=9 is the multiplier, you see) + 1 'asterisk' (multiplier i) (concatenation) 2nd iteration: #jumps to next line 8 s (j=9-1) + 3 a (i=1+2) ... that's, in 1st row you have a star; in 2nd row, a leftward shift of 1 place + 2 additional stars. so you end up with 1 star supported by a 'base' of 3 stars: 1 straightly down, while other 2 occupy left-down and right-down... you have got an intersting code 😁👍👍
6th Aug 2021, 6:06 AM
Barnik Roy
Barnik Roy - avatar
+ 2
Barnik Roy thank you
6th Aug 2021, 6:08 AM
alagammai uma
alagammai uma - avatar
+ 2
Now check the print function carefully now you can understand j=9 for i in range(1,10,2): print((' '*j) + (i*'*')) j-=1 here print function prints stars and spaces with single print function
7th Aug 2021, 5:44 AM
Kothooru Narendar
Kothooru Narendar - avatar
+ 1
alagammai uma Just analyze the code by yourself. You'll understand it. Try this: j = 9 for i in range(1, 10, 2): print(f"i = {i}, j = {j}\n") print(" " * j + "*" * i, "\n") j -= 1
6th Aug 2021, 4:53 AM
Calvin Thomas
Calvin Thomas - avatar
+ 1
Yes this question is the question In which anyone got confused first time as I am but when you will see it carefully you will got it what is happening in really. alagammai uma JUMP_LINK__&&__Python__&&__JUMP_LINK Learner you have explained very correctly.
8th Aug 2021, 3:07 AM
Anurag Kumar
Anurag Kumar - avatar
7th Aug 2021, 5:47 AM
alagammai uma
alagammai uma - avatar