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
39.5k14 gold badges98 silver badges131 bronze badges
asked Feb 4, 2012 at 7:28
2
  • 2
    replace 'print x' with 'print x + 1', and you'll understand! Commented 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. Commented Feb 4, 2012 at 7:44

3 Answers 3

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
>>>
answered Feb 4, 2012 at 7:33
Sign up to request clarification or add additional context in comments.

Comments

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:.

answered Feb 4, 2012 at 7:30

1 Comment

oh awesome, thanks. I'm a beginner just started to learn python
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?

answered Feb 4, 2012 at 7:33

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.