Python Forum

Full Version: Error with simple "or" statement?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm trying to count the number of words in a sentence that include "o" or "e." Why does this count every word?

player_str = "the best player in the world was nomar garciappara" #Enter your code below num_o_or_e = 0 s = player_str.split() print(player_str) print(s) for word in s: if 'o' or 'e' in word: print(word) num_o_or_e = num_o_or_e + 1 print('The number of words with an o or e in specified sentence is',num_o_or_e)
(Nov-15-2019, 03:16 PM)buran Wrote: [ -> ]https://python-forum.io/Thread-Multiple-...or-keyword

That makes sense.

I changed it to this:

player_str = "the best player in the world was nomar garciappara" #Enter your code below num_o_or_e = 0 s = player_str.split() print(player_str) print(s) for word in s: if 'o' in word: print(word) num_o_or_e = num_o_or_e + 1 elif 'e' in word: print(word) num_o_or_e = num_o_or_e + 1 else: continue print('The number of words with an o or e in specified sentence is',num_o_or_e)
This works, but is there an easier way that would involve restructuring only the "if 'o' or 'e'" line?
well, the example from the link I posted:
if 'o' in word or 'e' in word:
or
if any(char in word for char in 'oe'):
or more exotic
if set('oe') & set(word):
(Nov-15-2019, 04:45 PM)buran Wrote: [ -> ]well, the example from the link I posted:
if 'o' in word or 'e' in word:

Oops... I added a second if.

Thanks!