Python question: s = "pizzapizza" count = 0 i = 1 while i < len(s): if s[i] > "m": count = count + 1 i = i + 1 print count Why is the result 5? I don't get the fifth line, specifically what the "m" refers to and how it can be compared with s[i].. can someone please explain this for me?
Python compares strings according to their order in the alphabet or something; it is detailed here: http://docs.python.org/release/2.5.2/ref/comparisons.html So in your case, the test in line 5 is checking for characters in the string "pizzapizza" that come after the letter 'm' in the alphabet. So, it evaluates to true whenever s[i] is equal to either 'p' or 'z'
since i is set to 1 before the loop, the first s[i] is the letter 'i' (second letter in 'pizzapizza', so 'count' won't include the first 'p'), and consequently, at the end of the loop, 'count' will be equal to 5
Oh I see, thanks so much for your help! :)
Join our real-time social learning platform and learn together with your friends!