[Tutor] If loop conditions

Dimitar Ivanov dimitarxivanov at gmail.com
Tue Mar 1 11:28:49 EST 2016


Hello everyone!

First time using this mailing list so please excuse me in advance if this
mail is not structured properly.

I'm going through a Python course by Google, so far I've gotten to the
lists chapter and I've been trying to wrap my head around an exercise all
afternoon long, eventually was forced to look up the answer.

In the following exercise, Google requires you to look up words from a list
and count how many of the words are longer or equal to 2 characters where
the first and last letter match.

I've been trying to assign string slices to variables and then use those
variables inside the following if statement:

def match_ends(words):
+  for word in words:
+    length=len(word)
+      newList=[]
+      firstChar=word[0:]
+      lastChar=word[:-1]
+    if [ length >= 2 and firstChar == lastChar ]:
+        newList.append(word)
+    else:
+      break
+  newListCount=len(newList)
+  return newListCount

This was returning quite funky results such as counting each letter within
a word as a different word, not picking up the start/end of string etc.

Eventually I looked up the solution since I tracked down my problem to how
I made my if statement and, of course, it turned out to be much simpler
than usual.

+  if len(word) >= 2 and word[0] == word[-1]:

I tried putting brackets around the conditions and that broke the result
again so I came to wonder what's the difference between statements written
without brackets and those within brackets (such as my original code block)?

I'm sorry if I didn't make it completely clear, please let me know if you
need any further information.

Thank you!

Dimitar



-- 
Thanks,
Dimitar

*Twitter:* @winterchillz
*Facebook: */dimitarxivanov


More information about the Tutor mailing list