Search code examples
pythonpython-3.xcommand-line-argumentsisnumeric

trouble with str.isnumeric()


Im trying to test whether a command line argument is a number or not by using the isnumeric string method. It is to my understanding that it returns True if all characters are numeric and false if otherwise however when running it I seem to be getting True regardless of whether it is a number or not.

def get_data():
    sys.argv[1].isnumeric()
    if True:
        print('argument is number')
    else:
        print("Usage: python3 WnnnnnnnnAssg3.py number file1 file2 . . . filen")
        quit()

    if len(sys.argv) < 3 :
        print("Usage: python3 WnnnnnnnnAssg3.py number file1 file2 . . . filen")
        quit()
get_data()

Solution

  • You need to assign the result of isnumeric() to a variable and check it's value:

    value = sys.argv[1].isnumeric()
    if value:
        print('argument is number')
    else:
        print("Usage: python3 WnnnnnnnnAssg3.py number file1 file2 . . . filen")
        quit()
    

    Besides, using argparse built-in package would make the command-line parameter parsing and validation a lot cleaner and readable (tutorial link).