On 2015-03-18 02:41, Chris Kavanagh wrote:
I have a simple script that takes user input (for an Employee) such as
name, age, etc then puts in an sqlite3 database. The script worked fine
until I realized one problem. The age input field is defined in
SQLAlchemy as an Integer, so if a user inputs a string instead of a
number in that field, an error will occur (in IDLE). . .

So, I put a try: except clause in the code for the age field in the
add_data method. . .
try:
             age = self.age_var.get()
         except ValueError:
             showinfo("Error:", "Please Enter A Number In Age Field.")

If the user inputs a string (instead of an Int) the showinfo dialogue
box opens as it should, but when the user clicks "ok" in the box, I get
the error "UnboundLocalError: local variable 'age' referenced before
assignment". I tried using a default value above the try: except clause
(age=0), which corrects the error, but causes "0" to be saved in the
database instead of letting the user choose another value. I want to
figure why I get the error (with the try: except clause) and what
exactly to do about it. Thanks in advance for any help!

Here's the original code (without the try: except clause above). . .Just
put the try: except clause in the age variable in the add_data method as
shown above to get the error.

[snip]


     def add_data(self):
         name = self.name_var.get()
         age = self.age_var.get()
         addr = self.address_var.get()
         city = self.city_var.get()
         state = self.state_var.get()
         zip = self.zip_var.get()
         ssn = self.ssn_var.get()
         phone = self.phone_var.get()
         cell = self.cell_var.get()
         # create new Employee in .db
         new_person = Employee(name=name, age=age, address=addr,
city=city, state=state, zip=zip, ssn=ssn, phone=phone, cell=cell)
         session.add(new_person)
         session.commit()
         session.close()
         self.callback()
         return

Try stepping through the method in your head.

What happens if the user enters a non-number? A ValueError exception
occurs. You catch that, show a dialog, but then continue on with the
remainder of the method.

Because of the exception, you haven't assigned to 'age', hence the
UnboundLocalError exception.

If you assign a default value to age, it'll continue on to where you
put it into the database.

Why not just return from the method after showing the dialog?

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to