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')
4 Answers 4
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
Comments
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"
2 Comments
valid_marks = [str(n) for n in range(101)] can this be written in updated format today?['0', '1', '2', ... '100']. This is still valid and commonplace in modern python.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;
Comments
I would say that the simplest thing would be to instead of doing
price=int(price)
do
price=int(110)
raw_input, notinput.if ttt >= 2will always evaluate to true the first time in the loop, is this really the behaviour you want?printstatement would be a SyntaxError.