Optional argument not recognized

I'm trying to learn how to use argparse and and am running into an issue when trying to implement an optional argument. Here's what I have:

import argparse

def main(num1, num2=None):
    if num1 and num2:
        print(num1 + num2)
    else:
        print(num1)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Add some numbers')
    parser.add_argument('num1', help='The first number')
    parser.add_argument('-num2', help='The second number', action='store_true')

    args = parser.parse_args()
    main(args.num1, args.num2)

I'm sure it's a very simple issue, but I am getting this error when I pass in arguments 2 and 3 on the command line:

usage: argparse_test.py [-h] [-num2] num1
argparse_test.py: error: unrecognized arguments: 3

Why is the argument "unrecognized"?



Read more here: https://stackoverflow.com/questions/68459960/optional-argument-not-recognized

Content Attribution

This content was originally published by PaulD at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: