1
class StringHandling:
    def __init__(self,yo):
        self.yo = yo


def my_first_test():  
yo = input("Enter your string here")  
    ya = (yo.split())  
    even = 0  
    odd = 0  
    for i in ya:    
        if len(i) % 2 == 0:  
            even = even + 1  
        else:  
            odd = odd + 1  
    print("The number of odd words are ", odd)
    print("The number of even words are", even)


if __name__ == '__main__':
    c = StringHandling(yo="My name is here ")
    c.my_first_test()

What is the problem here? Have tried everything! I have tried indenting and the object is created but the method my_first_test is not called/used by object c.

1 Answer 1

2

You are pretty close. Try this:

class StringHandling(object):
    def __init__(self,yo):
        self.yo = yo


    def my_first_test(self):  
        yo = input("Enter your string here: ")
        ya = (yo.split())  
        even = 0  
        odd = 0  
        for i in ya:    
            if len(i) % 2 == 0:  
                even = even + 1  
            else:  
                odd = odd + 1  
        print("The number of odd words are ", odd)
        print("The number of even words are", even)


if __name__ == '__main__':
    c = StringHandling(yo="My name is here ")
    c.my_first_test()

Look at this for inspiration: https://jeffknupp.com/blog/2014/06/18/improve-your-python-python-classes-and-object-oriented-programming/

Notice the changes I've made:

  • Indented yo = input("Enter your string here") and formatted the text string a bit
  • Indented the entire my_first_test method
  • Added self to the method - read about why that's the case here: What is the purpose of self?

Results

python3 untitled.py 
Enter your string here: a ab a
The number of odd words are  2
The number of even words are 1
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for taking out the time. I fixed it as I had realized it was an indentation issue. Thank you for sharing the resources as well. I will surely look into them.

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.