Hi everybody,

Can you please help me to fix this error:

For exit press 'q'
Please enter name :Jack London
For exit press 'q'
Please enter name :C.S. Lewis
For exit press 'q'
Please enter name :q
Traceback (most recent call last):
  File "/home/serg/python/First/start/Q1.py", line 28, in <module>
    print row[0], row[1]
TypeError: 'NoneType' object is not subscriptable

And this is the code:

import MySQLdb as mdb
import sys

con = mdb.connect('localhost',
                  'root',
                  '',
                  'cartapp')
with con:
    cur = con.cursor()
    cur.execute('DROP TABLE IF EXISTS Writers')
    cur.execute("""
                CREATE TABLE Writers
                (
                    Id INT PRIMARY KEY AUTO_INCREMENT,
                    Names VARCHAR(25)
                 )
                 """)
    while True:
        print "For exit press 'q'"
        name = raw_input("Please enter name :")
        if name == 'q': break
        cur.execute('INSERT INTO Writers(Names) VALUES("%s")' % name)

    numrows = int(cur.rowcount)

    for i in range(numrows):
        row = cur.fetchone()
        print row[0], row[1]

row is None, how about changing the loop to

for row in cur:
    print row

or at least on line 26 the range should be range(1, numrows)

What is the meaning of

with con:

It does not make sense to me, here seems to be class to make mysql library to support with statement: http://stackoverflow.com/questions/8067690/context-manager-for-pythons-mysqldb

You get the error, because in line 21 you exit the loop, and not the whole with clause.
Either you make a sys.exit at this line, or make a check before line 26: if numrows>0.

Is your usage of with related to this rule in PEP8:

Context managers should be invoked through separate functions or methods whenever they do something other than acquire and release resources. For example:

Yes:

with conn.begin_transaction():
     do_stuff_in_transaction(conn)

No:

with conn:
     do_stuff_in_transaction(conn)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.