[Tutor] If loop conditions

Alan Gauld alan.gauld at btinternet.com
Tue Mar 1 11:52:59 EST 2016


On 01/03/16 16:28, Dimitar Ivanov wrote:
> First time using this mailing list so please excuse me in advance if this
> mail is not structured properly.

No worries, you've done a pretty good job of telling us
what we need to know.

> 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:

You probably don't need slices here. They are cool features
but not always the right thing to use.

> def match_ends(words):
> +  for word in words:
> +    length=len(word)
> +      newList=[]
> +      firstChar=word[0:]
> +      lastChar=word[:-1]

You only want the first and last character, not a slice.
So just use indexes.

      firstChar=word[0]
      lastChar=word[-1]

> +    if [ length >= 2 and firstChar == lastChar ]:

You don;t need the brackets. And in fact in this case
you are creating a list containing the bollean result
of your test. A  non empty list (regardless of the
value inside) is always going to be "true"...

Just write it as:

if length >= 2 and (firstChar == lastChar):

The () just make it clear that its

a and (b == c)

rather than

(a and b) == c

> +        newList.append(word)
> +    else:
> +      break

break exits the loop, you don't want that, instead you want
to go back to the start of the loop to process the next word.
The command for that is

	continue

> +  newListCount=len(newList)
> +  return newListCount

> 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)?

It all depends on the type of brackets.
Using square brackets as you did creates a list with a single value

like: [42]  or in your case, either [True] or [False]

The if statement(not loop) then treats any non empty list as True.

But if you had used () instead of [] then it would probably
work as you expected.

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

But you don;t really need them in Python (unlike C or Java)

You can however make the intention clearer for your readers
by grouping sub tests with params like:

if (length >= 2) and (firstChar == lastChar):

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list