Reputation: 161
Here is the code that I'm running, basically it just ask the user to type in numbers and then after I type in "done", calculate the average of them:
average = 0
total = 0.0
count = 0
while True:
num = raw_input()
if num == "done":
break
try:
int(num)
total = total + num
count = count + 1
except:
print "bad data"
average = total / count
print total, count, average
My problem is even if I type in an integer number, the except block still get executed (i.e. I get "bad data" as the output), could you tell me why is that?
Upvotes: 2
Views: 130
Reputation: 59601
int(num)
This returns an integer, but you aren't re-assigning num to this integer. You need to do
num = int(num)
for that line to have effect.
Also note that you should just print the exception, to find out more information:
try:
num_int = int(num)
total = total + num_int
count = count + 1
except ValueError as e:
print e
The reason we specifically catch ValueError
is because it's very good practice to catch the exceptions you are expecting (and handle that particular exception's scenario), instead of catching everything blindly.
Upvotes: 4
Reputation: 224903
int(num)
doesn’t change num
; it returns a new value. You could assign that new value back to num
if you wanted to change it.
num = int(num)
It’s also a good idea to catch specific errors and move as much out of the try
block as possible to avoid hiding useful exception information.
average = 0
total = 0.0
count = 0
while True:
num = raw_input()
if num == "done":
break
try:
num = int(num)
except ValueError:
print "bad data"
continue
total += num
count += 1
average = total / count
print total, count, average
Upvotes: 1
Reputation: 155363
int(num)
doesn't convert num
in place, you have to assign the result. Change the line to:
num = int(num)
and you should be golden.
Upvotes: 2