0

Python question

x=1 word="python" for i in word: i=x x +=2 print(i) "output" is 11 but i could not get how we obtain this value

26th Aug 2018, 12:13 PM
Bourdon Vaillant
Bourdon Vaillant - avatar
7 Answers
+ 5
#By changing the code as follow it explains itself. x=1 word="python" for i in word: print(i,end=' ') i=x x +=2 print(i,x,word) print(i)
26th Aug 2018, 12:21 PM
Louis
Louis - avatar
+ 3
You can't use a for each loop to assign new values to a string. i = x doesn't change the string. All you do is count the characters of the string, starting with 1 and increasing by 2 for every character but the last one. (I edited my answer because I thought the last line said print(x) instead of print(i). Sorry)
26th Aug 2018, 1:06 PM
Anna
Anna - avatar
+ 3
x is increased 6 times, but its value is assigned to i before the increment, so i is 1, 3, 5, 7, 9, 11.
26th Aug 2018, 1:25 PM
HonFu
HonFu - avatar
+ 3
Kishalaya Saha I edited my answer because I thought the last line was print(x) instead of print(i). 11 is correct. It's still a weird use of a for each clause though
26th Aug 2018, 1:45 PM
Anna
Anna - avatar
+ 3
Anna Agree 100%. This is the type of weird questions that are only seen on Sololearn PvP challenges (I haven't seen this one though). No one in their right mind ever does that. But sometimes these things do help us understand how things work in the background.
26th Aug 2018, 1:50 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 3
I feel this sort of somewhat nonsensical problems help learning to find your own mistakes: Sometimes we accidentally write a wrong name and strange stuff happens. ;-)
26th Aug 2018, 2:16 PM
HonFu
HonFu - avatar
0
Anna I don't think you're right. Try what Louis says. The variable "word" does not change. But i does.
26th Aug 2018, 1:41 PM
Kishalaya Saha
Kishalaya Saha - avatar