+ 2

Can some please explain me this code step by step how it execute ?

str = "testing for loops" count = 0 for x in str: if(x == 't'): count += 1 print(count)

6th Jan 2021, 3:55 PM
3 Answers
+ 3
for x in str : this cause to copy each character from str into x in each next iterations until no more characters like x='t', next x='e', next...., next ='s' And in loop, if statement check if x=='t' every charecter value of x with t, when matches increments count. So it finding how many 't' s in str. And prints count. as 2.
6th Jan 2021, 4:03 PM
Jayakrishna 🇮🇳
Jayakrishna 🇮🇳 - avatar
+ 2
On line 1 and 2, we set up some basic variables. On line 3, we set up a for loop, that is responsible for going through the characters in str. Inside this for loop, we check if the current character(stored in x) is equal to "t". If so, we add 1 to count. Finally, on line 6 we print the value of count.
6th Jan 2021, 4:05 PM
Jianmin Chen
Jianmin Chen - avatar
This one confuses me... So the for loop is not looking for "t" in the string "testing for loops"? It's looking for "t" in str? Isn't str a variable? So the loop should look for "t" inside that variable no??
23rd Apr 2022, 7:59 PM
Jaime Aguirre
Jaime Aguirre - avatar