+ 4

Why only p is printing? Loop is working only for one time why?

#to print '''p py pyt pyth''' s="phyton" j=0 for i in range (0,j+1): print(s[i],end=" ") j=j+1

29th Apr 2019, 5:03 PM
SOUMYA
SOUMYA - avatar
4 Answers
+ 1
The range function returns an iterator object which basically the for loop uses to get values from. This object is only created once in a loop causing your problem. To fix this I would change the loop to: for i in range(len(s) + 1): print(s[:i]) It takes the length of the string to get the indexes and uses array slicing to grab the section of the string from index 0 to i.
29th Apr 2019, 5:16 PM
TurtleShell
TurtleShell - avatar
+ 3
But j value is increasing every time
29th Apr 2019, 5:15 PM
SOUMYA
SOUMYA - avatar
+ 2
Are you trying to simulate a while loop there? Python range() accepts an integer and returns a range object, which is nothing but a sequence of integers. You can’t increment j after!
29th Apr 2019, 5:18 PM
Sergiu Panaite
Sergiu Panaite - avatar
+ 1
range(0, j+1) where j=0 that means range(0,1) thats why its only executed once https://docs.python.org/3/library/functions.html#func-range
29th Apr 2019, 5:14 PM
Taste
Taste - avatar