0

I am having some difficulty figuring this out. The question in my assignment asks that we:

Print the elements in the nmrls list that have more than or equal to 7 letters and has either the letter 'o' or the letter 'g'.

and the results should be three (eighteen, fourteen and twenty-one) but I only get twenty-one.

What am I doing wrong?

Also unrelated question, do we always have to run the entire code every time we open Jupyter notebook (for a sophisticated language it seems very cumbersome)?

nmrls = inflect.engine()
x=[]
for i in range (0,22):
    x.append(nmrls.number_to_words(i))   
for nmrls in x:
    count=0
    for letter in nmrls:
        count+=1
        if count>=7 and "o"  or "g" :   
            print(nmrls)
1
  • 1
    First, there is no such thing as an "if loop". Second, you haven't compared anything to those two letters. Your posted code does not run as given, so it's hard for us to handle your problem. Commented Oct 16, 2020 at 22:58

2 Answers 2

2

I suspect that what you need is a loop body that actually checks the word in question:

for word in x:
    if len(word) >= 7 and ('o' in word or 'g' in word):
        ...
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the corrections: hand-typing my code from the IDLE window.
2

This occurs because your if statement doesn't actually check if 'o' or 'g' is in the string, but whether 'o' or 'g' exists, due to the inherent true boolean value of non-zero length strings in Python.

I would recommend reimplementing this using len():

for nmrls in x:
    if len(nmrls) >= 7 and ('o' in nmrls or 'g' in nmrls):
        print(nmrls)

Something similar could also be achieved using list comprehension:

x = [word for word in x if len(word) >= 7 and ('o' in word or 'g' in word)]

2 Comments

Thank you it makes sense, but why not use the count.
@datagalz I suggest not using a count simply because it adds unnecessary code complexity. len() is generally the pythonic way to find the length of an iterable. Defining an additional, unneeded variable, especially when it can be summarized with a function, is not usually pythonic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.