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
39.5k14 gold badges98 silver badges131 bronze badges
-
2replace 'print x' with 'print x + 1', and you'll understand!jimifiki– jimifiki2012年02月04日 07:37:22 +00:00Commented Feb 4, 2012 at 7:37
-
5@Nitesh: Welcome to SO. Please "accept" one of the correct answers by clicking the "check mark" at the left of the answer.Jim Garrison– Jim Garrison2012年02月04日 07:44:36 +00:00Commented Feb 4, 2012 at 7:44
3 Answers 3
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
>>>
answered Feb 4, 2012 at 7:33
RanRag
49.8k39 gold badges120 silver badges172 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
x is a string but 1 is an integer, so the comparison is of mismatched types. You need something like if int(x) > 1:.
answered Feb 4, 2012 at 7:30
Gabe
87.1k13 gold badges144 silver badges239 bronze badges
1 Comment
jaysun
oh awesome, thanks. I'm a beginner just started to learn python
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:
answered Feb 4, 2012 at 7:33
Niall Byrne
2,4701 gold badge18 silver badges20 bronze badges
Comments
lang-py