Numbers passed as command line arguments in python not interpreted as integers

前端 未结 6 1093
有刺的猬
有刺的猬 2020-12-10 10:42

I am familiar with C, and have started experimenting in python. My question is regarding the sys.argv command. I\'ve read it is used for a command line interpre

6条回答
  •  醉酒成梦
    2020-12-10 10:52

    You also should validate the user input:

    import sys
    
    def is_intstring(s):
        try:
            int(s)
            return True
        except ValueError:
            return False
    
    for arg in sys.argv[1:]:
        if not is_intstring(arg):
            sys.exit("All arguments must be integers. Exit.")
    
    numbers = [int(arg) for arg in sys.argv[1:]]
    sum = sum(numbers)
    
    print "The sum of arguments is %s" % sum
    

提交回复
热议问题