Hello list,
I have been trying to trap a string entry by raising an exception. The code follows - but the exception is never raised. What am I doing wrong?
TIA Diana
try:
self.guess = int(self.num_ent.get())
self.num_ent.delete(0,END)
self.num_ent.focus_set()
if self.guess < self.number: message = str(self.guess) + " is too low. You need to guess higher"
if self.guess > self.number: message = str(self.guess) + " is too high. You need to guess lower"
if self.guess == self.number:
message = str(self.guess) + " is the correct number!"
self.message_txt.config(state = NORMAL)
self.message_txt.config(state = DISABLED)
self.message_txt.config(state = NORMAL)
self.message_txt.delete(0.0, END)
self.message_txt.insert(0.0, message)
self.message_txt.config(state = DISABLED)
except(ValueError): message = str(self.guess) + " is not a number. Please try again!"
Hi Dianna,
What are you expecting to raise the ValueError? It looks to me like it must be the line:
self.guess = int(self.num_ent.get())
But, if that is so, then the assignment to message in your except clause won't work, as self.guess won't have been assigned.
I'm no expert, so I may be missing something, but I wouldn't be surprised if your num_ent.get() has details that are pertinent. What does that method return?
And, while I'm writing, I'd suggest rewriting your lines like:
message = str(self.guess) + " is the correct number!"
in this form instead:
message = "%s is the correct number!" %self.guess
The almost irrelevant benefit is that it is faster. The big plus is string formatting is so handy, that I think it helps a lot to get used to using it in most cases, even those that are easy to handle with string concatenation as you have done.
Best,
Brian vdB
_______________________________________________ Tutor maillist - [email protected] http://mail.python.org/mailman/listinfo/tutor
