Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit python program when argument is less than 0

Tags:

python

I'd like the program to exit if the input number is less than 0, but sys.exit() isn't doing 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()
like image 643
Sam Avatar asked Aug 23 '26 19:08

Sam


1 Answers

Your test is failing because number is a string.

>>> '-1' <= 0
False

You need to convert number to an integer:

number = int(sys.argv[1])

Note that in Python 3.0 your code would have given an error, allowing you to find your mistake more easily:

>>> '-1' <= 0
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    '-1' <= 0
TypeError: unorderable types: str() <= int()
like image 58
Mark Byers Avatar answered Aug 25 '26 09:08

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!