Reputation: 27
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.
Upvotes: 1
Views: 1696
Reputation: 37029
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:
yo = input("Enter your string here")
and formatted the text string a bitmy_first_test
methodself
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
Upvotes: 2