3) What is the value of second after executing the following lines?
first = "kaleidoscope"
second =
for i in range (len(first)-1,-1,-2):
second = first[i]+second
Answers
The value of the variable second after executing the lines will be aedsoe
Let's correct the question
3) What is the value of second after executing the following lines?
first = "kaleidoscope"
second = ""
for i in range (len(first) - 1, -1, -2):
second = first[i] + second
The code will be like this
first = "kaleidoscope"
second = ""
for i in range (len(first) - 1, -1, -2):
second = first[i] + second
print(second)
Output
aedsoe
Explanation
In this variable first is assigned with a string which is a kaleidoscope and the variable second is assigned with an empty string.
len(first) => This stores the length or characters count of string present in the variable first.
for loop starts with the length of string present in variable first which is 12 and -1 is used so, it runs from 11 and it runs till -1 and it also skips 2 values.
Now, in the loop it is given
second = first[i] + second
This means that value present at ith place in the string is added to the variable second along with the value of the variable second in the previous loop.
plus(+) operator is used to join the strings.
For a better understanding value of the variable second after each loop will be:
1. for i in range(11, -1, -2)
second = first[11] + second
second = "e" + ""
second = "e"
2. for i in range(9, -1, -2)
second = first[9] + second
second = "o" + "e"
second = "oe"
3. for i in range(7, -1, -2)
second = first[7] + second
second = "s" + "oe"
second = "soe"
4. for i in range(5, -1, -2)
second = first[5] + second
second = "d" + "soe"
second = "dsoe"
4. for i in range(3, -1, -2)
second = first[3] + second
second = "e" + "dsoe"
second = "edsoe"
5. for i in range(3, -1, -2)
second = first[1] + second
second = "a" + "edsoe"
second = "aedsoe"
The value of the variable second is aedsoe
The above explanation is how the loop works internally.
Extra Information
range() function is used to return a sequence of numbers in the order that we have set in the function.
Syntax of range() function
range(start, stop, step)
start is where we mention from which position the loop has to start. If not mentioned it starts from 0 by which we can say it is optional to mention it.
stop is where we want our loop to end. It is required to be mentioned.
step is used to increment so, that loop goes on. If not mentioned it has a default value of 1 by which we can say it is optional to mention it.
Python was created by Guido van Rossum and came into existence in 1991. It is a high-level and general programming language. It is a very lucid programming language as it has a good language construct and object-oriented approach. It is dynamically typed and garbage-collected.