0

Please explain me this code and btw output also

student_name = "iteration" count= 0 for letter in student_name : if letter .lower() == "e" print(count) count += 1

22nd Jun 2018, 4:55 AM
Teddy's Codes
Teddy's Codes - avatar
3 odpowiedzi
+ 4
(The code needs a colon at the end of line 4) The for loop makes the code iterate (= "go through one at a time") through the letters of the string variable called student_name and increase the value of the integer variable called count (count += 1 is the same as count = count + 1) by 1 each time through the loop, checking to see if the lowercase value of the letter in question is the letter "e", in which case, the value of count is printed. So running the code: First time: count is 0, letter is "i" since "i" is not "e", nothing is printed count becomes 1 (i.e. 0+1) Second time: count is 1, letter is "t" since "t" is not "e", nothing is printed count becomes 2 (i.e. 1+1) Third time: count is 2, letter is "e" since "e" is "e", count (i.e. 2) is printed count becomes 3 (i.e. 2+1) Fourth time: count is 3, letter is "r" since "r" is not "e", nothing is printed count becomes 4 (i.e. 3+1) and so on through the word. Since there isn't another letter "e" in the word, nothing more is printed.
22nd Jun 2018, 5:53 AM
David Ashton
David Ashton - avatar
+ 2
it'll output 2. the count += 1 behaves like an else condition. the first two letters aren't 'e' so the if condition is not executed but count is incremented to 1 when letter == 'i' and to 2 when letter == 't'. the third loop makes the if condition true thus it print the current value of count which is 2. count is still incremented for the remaining letters but not printed
22nd Jun 2018, 5:42 AM
E_E Mopho
E_E Mopho - avatar
+ 1
also add colon after if expression.. else will not work
22nd Jun 2018, 5:46 AM
Abhishek Rawat
Abhishek Rawat - avatar