I know this is basic but I cannot get this to work. It does not seem to understand greater than 60 and constantly goes round in the loop.
Python 2.7.3
rackNo = 0
while (rackNo > 60) or (rackNo < 1) :
rackNo = raw_input("Enter the Rack number you are using: ")
if (rackNo > 60) or (rackNo < 1) :
print "Rack number must be between 1 and 60"
1 Answer 1
You're comparing a string (from raw_input) to an integer.
Ultimately, you want something like:
rackNo = int(raw_input("Enter the Rack number you are using: "))
In python2.x, comparison (>, <) between builtin types is implementation dependent. In python3.x, these comparisons are explicitly disallowed.
The operators <,>, ==,>=, <=, and != compare the values of two objects. The objects need not have the same type. If both are numbers, they are converted to a common type. Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily. You can control comparison behavior of objects of non-built-in types by defining a
__cmp__method or rich comparison methods like__gt__, described in section Special method names.
The operators <,>, ==,>=, <=, and != compare the values of two objects. The objects need not have the same type. If both are numbers, they are converted to a common type. Otherwise, the == and != operators always consider objects of different types to be unequal, while the <,>,>= and <= operators raise a TypeError when comparing objects of different types that do not implement these operators for the given pair of types. You can control comparison behavior of objects of non-built-in types by defining rich comparison methods like
__gt__(), described in section Basic customization.
2 Comments
input() (which will automatically convert valid input into integers/doubles) to int(raw_input()) because it avoids the possibility of a ValueError.input, I respectfully disagree. If you want to avoid the ValueError and any number will do, then you can just use float(raw_input()). I would never recommend the use of input without knowing first what it will be used for. Consider the "input": __import__('os').remove('some_important_file'). input will happily run that code. It's better to be explicit about what you want (throwing exceptions when you don't get it). You can always handle the exception if you know how.