I have the following code:
word = ""
if (letter=="a" for letter in word):
print("a found!")
which prints a found! even though word variable is empty. Why is this happening? And what is the right way to do what I want?
The condition you used in if returns a generator expression <generator object <genexpr> at 0xefd89660> which is always True.
To verify what your condition returns,
print(letter=="a" for letter in word)
# <generator object <genexpr> at 0xefd89660>
Hence you get what you got.
Right way:
word = ""
for x in word:
if x == 'a':
print('a found!')
Iterate through word, compare if it equals 'a' and do whatever if condition is satisfied.
Or even better:
if 'a' in word:
print('a found!')
That is happening because the statement (letter=="a" for letter in word) is a generator. Your if statement checks if that generator is a "truthy" object (lots of things in python evaluate to true for convenience -- nonempty lists, nonempty strings, etc...) and then prints "a found!" since the generator evaluates to True.
Instead, you probably want something like the following.
word = ""
letter = "a"
if letter in word:
print(f"{letter} found!")