Reputation: 245
I have this code in python 3,to check for errors on input but i need to determine that the input is an integer and if not to print the error message.
can anyone help me to figure out the code in my while loop. Thanks
price = 110;
ttt = 1;
while price < 0 or price > 100:
price = input('Please enter your marks for Maths:');
ttt =ttt +1;
if ttt >= 2:
print( 'This is an invalid entry, Please enter a number between 0 and 100')
Upvotes: 10
Views: 19194
Reputation: 1
I would say that the simplest thing would be to instead of doing
price=int(price)
do
price=int(110)
Upvotes: 0
Reputation: 9868
You probably want something like this, which will catch both whether the price is a whole number and whether it is between 0 and 100, and break the loop if these conditions are fulfilled.
while True:
price = raw_input('Please enter your marks for Maths:')
try:
price = int(price)
if price < 0 or price > 100:
raise ValueError
break
except ValueError:
print "Please enter a whole number from 0 to 100"
print "The mark entered was", price
Or since you have a manageably small number of possible values you could also do something like:
valid_marks = [str(n) for n in range(101)]
price = None
while price is None:
price = raw_input('Please enter your marks for Maths:')
if not price in valid_marks:
price = None
print "Please enter a whole number from 0 to 100"
Upvotes: 4
Reputation: 43533
Use the int()
function to convert to an integer. This will raise a ValueError when it cannot do the conversion:
try:
price = int(price)
except ValueError as e:
print 'invalid entry:', e
Upvotes: 10
Reputation: 9821
First, use raw_input
instead of input
.
Also, place the ttt
check before your input so errors display correctly:
price = 110;
ttt = 1;
while price < 0 or price > 100:
if ttt >= 2:
print 'This is an invalid entry, Please enter a number between 0 and 100';
price = raw_input('Please enter your marks for Maths:');
ttt = ttt +1;
Upvotes: 2