Reputation: 47
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-
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.
Upvotes: 1
Views: 209
Reputation: 231
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.
Upvotes: 2
Reputation: 4129
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!"
Upvotes: 0