0

I executed the following code:

import sys

x=sys.argv[1]

print x;

if x > 1:
    print "It's greater than 1"

and here is the output:

C:\Python27>python abc.py 0
0
It's greater than 1

How the hell it's greater than 1? in fact the if condition should fail, is there any fault with my code?

Owen
  • 38,836
  • 14
  • 95
  • 125
jaysun
  • 159
  • 1
  • 1
  • 10

3 Answers3

5

Because type of x in x=sys.argv[1] is str.

import sys
x = sys.argv[1]
print type(x)

Output =<type 'str'>

So in python,

>>> '0'>1
True

Therefore you need

>>> int('0')>1
False
>>>
RanRag
  • 48,359
  • 38
  • 114
  • 167
3

x is a string but 1 is an integer, so the comparison is of mismatched types. You need something like if int(x) > 1:.

Gabe
  • 84,912
  • 12
  • 139
  • 238
3

This is testing x (a string). try using:

if int(x) > 1: 
     print "It's greater than 1"

I got curious about this and found:

How does Python compare string and int?

Community
  • 1
  • 1
Niall Byrne
  • 2,448
  • 1
  • 17
  • 18