Reputation: 7
Im working on a for where the user enters their weight and it is displayed later in the program. Their weight has to be between 0 and 500, for some reason I can't seem to get the program to accept any weight in the correct range.
weight = raw_input("Enter your Weight: ")
while not weight.isdigit() or weight >500 or weight<=0:
if not weight.isdigit():
print "Invalid Number. Try Again."
weight = raw_input("Enter your Weight: ")
if weight > 500:
print "Invalid Number. Try Again."
weight = raw_input("Enter your Weight: ")
if weight < 1:
print "Invalid Number. Try Again."
weight = raw_input("Enter your Weight: ")
I've also tried using range(0, 500) but nothing seems to be working. I'm sure its a simple solution and I feel like an idiot not being able to get it.
Upvotes: 0
Views: 85
Reputation: 5659
The variable 'weight' is a str, and you're running into cross-type comparison issues. For, say, 300, weight > 500 evaluates to True. If you cast it to an integer before the '>' it should work, i.e. change
weight > 500
to
int(weight) > 500
Upvotes: 1
Reputation: 36161
You need to convert your input as an integer before comparing it to 0 and 500.
Here is an updated version of your code, which tries to cast the input as an integer and break the infinite loop only if the weight is between 0 and 500 (exclusive).
while True:
try:
weight = int(raw_input("Enter your Weight: "))
except ValueError:
print "Please enter a valid number. Try Again."
else:
if 0 < weight < 500:
break
print "Invalid Number (should be between 0 and 500). Try Again."
Upvotes: 3
Reputation: 3791
Convert to an integer first.
weight = int(raw_input("Enter your Weight: "))
while not weight.isdigit() or weight >500 or weight<=0:
if not weight.isdigit():
print "Invalid Number. Try Again."
if weight > 500:
print "Invalid Number. Try Again."
if weight < 1:
print "Invalid Number. Try Again."
weight = int(raw_input("Enter your Weight: "))
Upvotes: 0