Question

I was just trying to understand Try and except statements better.I am stuck. So I was hoping if you guys could clarify. This program purely for learning.

Appreciate your input.

while True:
    x=int(input('enter no.->'))

    try:
        x/2
    except ValueError:
        print('try again')
    else:
        if (x/2)==1:
            break
print('program end')

So i wrote this program with the intention-

  1. loop if x is a number
  2. if it is not. then 'except' comes into play and starts again
  3. if quotient is 1. STOP.

Even if I change it to

    x=input('enter no.->')

    try:
        int(x)/2

'except' works but I get 'unsupported operand type(s)' if i put in a number.

Was it helpful?

Solution

You're trying to convert it to an int immediately. The try-except statement will check for errors, but only in the code that is contained in the try-except thingy. If you enter something wrong, the int conversion will immediately fail because the input is not an integer. Instead, put the int conversion (int(string)) into the try-except statement:

while True:
    x=input('enter no.->')


    try:
        x=int(x)
    except ValueError:
        print('try again')
    else:
        if (x/2)==1:
            break
print('program end')

The second one failed because you have to set x to the converted value, so you're basically trying to divide a string by 2.

As a note, I'm not sure how applicable this is, but my OOP professor has told me using an infinite loop and breaking/returning out of it is very bad programming practice, so you should just use a boolean value (while foo: ... ... ... foo = false). I'm not entirely sure why, as I haven't looked it up yet.

EDIT: Is it a bad practice to use break in a for loop?

In general, it's just how readable or error-prone you're willing to let it be.

OTHER TIPS

To loop while x is a number, you could do something like this (using Try and Except):

num = True
while num:
   x = raw_input("Enter a number: ")
   try:
       y = int(x)/2
       num = True
   except:
       num = False

print "Done!"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top