Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python while loops

Tags:

python

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')
like image 308
miguel Avatar asked Dec 27 '12 22:12

miguel


People also ask

What are while loops in Python?

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.

Are while loops allowed in Python?

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.

Why is my while loop infinite Python?

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.

What is a while 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.


2 Answers

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
like image 102
Roland Smith Avatar answered Oct 23 '22 18:10

Roland Smith


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"
like image 40
Stuart Avatar answered Oct 23 '22 17:10

Stuart