0

I am trying to prevent this simple sort program to accept only 1 argument when printing in reverse. this is what I type and it still goes thru:

python sort.py  alpha -r

here is my whole program:

example: python sort.py able spencer delta to reverse: python sort.py -r able spencer delta python sort.py --reverse able spencer delta

import argparse
import sys

def wordsorter():
    argparser = argparse.ArgumentParser()
    argparser.add_argument('user_string', nargs='*')
    argparser.add_argument("-r","-- 
reverse",action="store_true",default="False",dest="z_to_a")
args = argparser.parse_args()
if (len(sys.argv)==1 or len(sys.argv)==2):
    print("Invalid command line arguments to program. Please, supply two or more strings to sort.")
    sys.exit(1)

if args.z_to_a == True and len(sys.argv)>1:
    words_to_sort= sorted(args.user_string, reverse = True)
    print(*words_to_sort)
    print("if 1")
else:

    words_to_sort = sorted(args.user_string)
    print(*words_to_sort)
    print("if 2")
if __name__ == '__main__':
    wordsorter ()

When I enter one Argument without sorting in reverse it works If I try to use reverse with one argument it should not work. What am I doing wrong?

1 Answers1

1

Your problem is caused by the fact that you tell argparse to expect any number of arguments for user_string instead of at least two, and then check that len(sys.argv) >= 2 (by the way, this is a better way to write that if condition), but it can be equal to 2 if you pass -r and only one argument for user_string.

You can check that len(args.user_string) >= 2 and that should work.

If you want to do it through argparse: Unfortunately, while it is possible to tell it to expect at least one argument, it is not possible to directly tell it to expect at least two. A possible workaround is described in this answer.

alon-k
  • 330
  • 2
  • 11