def paper_doll(text):
for i in text:
text1=''
text1 = i*3
return text1
paper_doll('tom')
Here via this particular code I want to print every character in the string 'tom' thrice. but when I ran the code only the last character is getting printed thrice. Why is it so?
CodePudding user response:
On the last iteration of the loop, the program:
performs
text1=''
andperforms
text1 = i*3
.
So, regardless of what happened before the last iteration, it is erased in the first step above.
Consider moving initialization (text1=''
) before the loop.
CodePudding user response:
The variable text1
gets reset every time the code in the for loop runs. So it is set to "ttt"
, then reset and set to "ooo"
, then reset and set to "mmm"
. Only the "mmm"
is returned. In order to not have it reset every time the for loop runs, define it outside of the for lop instead:
def paper_doll(text):
text1=''
for i in text:
text1 = i*3
return text1
paper_doll('tom')
CodePudding user response:
If we rewrite your code using more explicit names, it is equivalent to this:
def paper_doll(text):
for character in text:
text1 = character * 3
return text1
paper_doll('tom')
It does not give the result you want because text1
is overwritten at every loop (therefore giving you only the last character of the string as a triplet).
What you want to do is the following:
def paper_doll(text):
text1 = '' # define text1 outside the loop to avoid overwritting it
for character in text:
text1 = character * 3
return text1
paper_doll('tom')
CodePudding user response:
All the answers so far explain why your code does not work as expected and how to fix it. But I suppose you already knew that, since your question is "Why do we need..."
So, why? The string must already exist since you use an "augmented assignment operator", i.e. =
. And since it must exist and you don't want to reset it at every iteration, you need to create it outside the loop.