Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
for loop
#1
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?
Reply
#2
see https://python-forum.io/Thread-Multiple-...or-keyword
Reply
#3
Thanks.

Never mind. Figured out I needed the second "if"
Reply
#4
(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'
Reply
#5
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
I am trying to help you, really, even if it doesn't always seem that way
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020