I created a method which splits a sentence into words and returns the first word of the sentence (you could use NLTK tokenizer
or argparse
for this, but as this is a class project meant for learning Python, I created a simple tokenizer from scratch) The method also has a useful 'help' argument, in which passing -h
or --help
will bring up help text. However I want the function to output the help text then 'break' or 'pass' if the user passes -h or --help. Here's my method:
class example_method(object):
def __init__(self):
self.data = []
def parse(self, message):
if(("-h" or "--help") in message):
print("This is a helpful message")
else:
self.data = [x.strip() for x in message.split(' ')]
return self.data
If the user input a regular message, the method works. Let me illustrate:
example = example_method()
input_message = "Hello there how are you?"
print(example.parse(input_message)[0])
The above works well. However, if the user inputs -h or --help, the method returns an error:
example = example_method()
input_message = "--help"
print(example.parse(input_message)[0])
The above will return: TypeError: 'NoneType' object is not subscriptable
I realize that a possible solution is:
try: print(example.parse(input_message)[0])
except: pass
But is there a way to return pass
from within the method like this?
def parse(self, message):
if(("-h" or "--help") in message):
print("This is a helpful message")
return pass
else:
self.data = [x.strip() for x in message.split(' ')]
return self.data
My aim is that I do not want an error message as this method is part of a bigger program and an error will just make the output look ugly. It would look far more professional if the method outputs help text and then exits without an error.