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.

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61

1 Answers1

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
zedfoxus
  • 35,121
  • 5
  • 64
  • 63
  • 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. – Aman Vinayak Jul 19 '18 at 06:12