Exit python program when argument is less than 0

I want the program to exit if the input number is less than 0, but sys.exit () does not do the trick. This is what I have now:

if len( sys.argv ) > 1:
    number = sys.argv[1]

if number <= 0:
    print "Invalid number! Must be greater than 0"
    sys.exit()
+3
source share
1 answer

Your test does not work because the number is a string.

>>> '-1' <= 0
False

You need to convert numberto an integer:

number = int(sys.argv[1])

Note that in Python 3.0, your code would give an error, making it easier to find your error:

>>> '-1' <= 0
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    '-1' <= 0
TypeError: unorderable types: str() <= int()
+10
source

Source: https://habr.com/ru/post/1739224/


All Articles