indiaash524
indiaash524

Reputation: 167

Boolean is Giving Unexpected Answer for Python code?

I am not sure what I am doing that is causing this python code to give me a weight answer. Here is my code:

x = raw_input("Find Cube Root of A Perfect Cube: ")
root = 3
foo = root * root * root
bar = x
print root * root * root
print x
print (root * root * root) < x

print (foo < bar)

These are the print statements given:

27 12 True True

I understand the first two, of course, but why do I get such an odd answer? 27 is obviously greater than 12.

Upvotes: 0

Views: 64

Answers (4)

hanleyhansen
hanleyhansen

Reputation: 6437

Cast x to an int like this:

int(x)

That'll give you an integer since raw_input returns a string.

Upvotes: 0

BrenBarn
BrenBarn

Reputation: 251608

raw_input returns a string. You are comparing a string and a number. Convert x to a number with x = int(x).

Upvotes: 1

chepner
chepner

Reputation: 532428

x is a str object, so bar is, too. foo, however, is an int, and in Python 2.x, any int is less than any str, because values of unequal types are compared lexicographically by their type name. In Python 3, the comparison would raise an error instead.

Upvotes: 1

Christian Tapia
Christian Tapia

Reputation: 34186

Try printing the types of foo and bar:

print type(foo), type(bar)

you will get

>>> <type 'int'> <type 'str'>

Why you get a string? Because raw_input() returns a string. In Python 2.x, a string will always be greater than an integer, that's why you get that result.

In Python 3.x you will get a TypeError:

TypeError: unorderable types: int() < str()

How to solve this? You can convert that string to an integer:

x = int(raw_input("Find Cube Root of A Perfect Cube: "))

Upvotes: 2

Related Questions