Python Forum

Full Version: ThinkPython Exercise 9.2
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Help please!

I am starting to learn python using the ThinkPython book. For exercise 9.2, I wrote the below code (which is the same as the answer code posted online). However, the conditional statement only recognizes the first letter. For example, if the word starts with the letter 'e' or 'E' (such as "elephant"), the statement returns False and for all others, including words containing the letter 'e' or 'E' but not at the beginning (such as "love"), the statement will return True. Can someone please point it out to me what I am doing wrong? Thank you very much!!

fin=open('words.txt')
def has_no_e(word):
    char=""
    for char in word:
        if char == 'E' or char == 'e':
            return False
        return True
I can't tell much since there is no indentation. Add a print(char) after "for char in word" and see if that helps you understand.
I probably shouldn't be answering, but I think I see the problem here. You should as an "else" to the conditional.

...
if char == 'E' or char == 'e':
    return False
else:
    return True
Oh, and I think it's good form to use code tags--it's the Python symbol towards the right of the format bar.
the problem with your original code is the indentation level of the last line - it should be out of the for loop. This should work
fin=open('words.txt')
def has_no_e(word):
    char=""
    for char in word:
        if char == 'E' or char == 'e':
            return False
    return True
but it's better like this
def has_no_e(word):
    return not 'e' in word.lower()
(May-23-2018, 12:49 AM)malonn Wrote: [ -> ]I probably shouldn't be answering, but I think I see the problem here. You should as an "else" to the conditional.

...
if char == 'E' or char == 'e':
    return False
else:
    return True
Oh, and I think it's good form to use code tags--it's the Python symbol towards the right of the format bar.

Just saying - since that was anyway wrong answer - that expression already produces boolean
not (char == 'E' or char == 'e')
but that one will be shorter
char not in 'eE'
Okay, good to know. My fault, @sangurocactus--like I said, I probably shouldn't answer.
Hi Buran - thank you very much. The problem is indeed in the indention.

Thanks everyone else for their input!