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')
What is while loop in Python? The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true. We generally use this loop when we don't know the number of times to iterate beforehand.
Python doesn't have do-while loop. But we can create a program like this. The do while loop is used to check condition after executing the statement. It is like while loop but it is executed at least once.
A loop becomes infinite loop if a condition never becomes FALSE. You must use caution when using while loops because of the possibility that this condition never resolves to a FALSE value. This results in a loop that never ends. Such a loop is called an infinite loop.
A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.
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
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With