Reputation: 3
I'm a noobie, learning to code and i stumbled upon an incorrect output while practicing a code in python, please help me with this. I tried my best to find the problem in the code but i could not find it.
Code:
def compare(x,y):
if x>y:
return 1
elif x==y:
return 0
else:
return -1
i=raw_input("enter x\n")
j=raw_input("enter y\n")
print compare(i,j)
Output:
-> python python.py
enter x
10
enter y
5
-1
The output that i had to receive is 1 but the output that i receive is -1. Please help me with the unseen error in my code.
Thank you.
Upvotes: 0
Views: 79
Reputation: 3491
Use the inbuilt cmp builtin function.
>>> help(cmp)
Help on built-in function cmp in module __builtin__:
cmp(...)
cmp(x, y) -> integer
Return negative if x<y, zero if x==y, positive if x>y.
So your function will look like this.
>>> def compare(x,y):
... return cmp(x,y)
...
>>>
Then get two variables using raw_input() which returns string, So If you are typing two numbers with a blankspace in the middle, splitting based on blank space will save two numbers in these x and y, and then apply map function which takes two parameters, one int function and the sequence which is nothing but a list created out of split().
>>> x,y = map(int, raw_input().split())
3 2
Now Comparing the x and y, Since x = 3 and y =2, Now since as per the documentation of cmp(), It Return negative if xy.
>>> compare(x,y)
1
>>> compare(y,x)
-1
>>> compare(x-1,y)
0
>>>
Upvotes: 0
Reputation: 677
Your issue is that raw_input()
returns a string, not an integer.
Therefore, what your function is actually doing is checking "10" > "5", which is False
, therefore it falls through your if
block and reaches the else
clause.
To fix this, you'll need to cast your input strings to integers by wrapping the values in int()
.
i.e.
i = int(raw_input("enter x\n"))
.
Upvotes: 0
Reputation: 1207
raw_input
returns a string always.
so you have to convert the input values into numbers.
i=raw_input("enter x\n")
j=raw_input("enter y\n")
print compare(i,j)
should be
i=int(raw_input("enter x\n"))
j=int(raw_input("enter y\n"))
print compare(i,j)
Upvotes: 1