Python Forum

Full Version: for loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
As part of a quiz in Python, we were asked to create a for loop that would then print all elements of the string that begin with or end with the letter "z". I can only get the first [0] or last [-1] o print but not both.

latest attempt prints only pizazz

words = ["pizazz", "python", "zebra", "pizza"]
for word in words:
    if word[0] and word [-1] in "z":
        print word
Do I need another if statement or what is the correct syntax?
Thanks.

Never mind. Figured out I needed the second "if"
(Oct-05-2017, 11:43 AM)kekulpac Wrote: [ -> ]Never mind. Figured out I needed the second "if"

No, you don't need second if. your current condition word[0] and word [-1] in "z" is incorrect because word[0] is always evaluated to True, so it is in fact True and word [-1] in "z"

Also, you should use == instead of in given that you compare with single char 'z'
You need to test for either condition using an OR, or check if z is within a concatenated string:

Output:
>>> word="abcdefghj" >>> word[0] == "z" or word[-1] == "z" False >>> "z" in word[0]+word[-1] False >>> >>> word="abcdefghjz" >>> word[0] == "z" or word[-1] == "z" True >>> "z" in word[0]+word[-1] True >>> >>> word="zabcdefghj" >>> word[0] == "z" or word[-1] == "z" True >>> "z" in word[0]+word[-1] True