Advertisement
Guest User

daily programmer challenge 1

a guest
Feb 15th, 2012
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.28 KB | None | 0 0
  1. import sqlite3 as sql
  2.  
  3. """
  4. create a program that will ask the users name, age, and reddit username. have it tell them the information back, in the format:
  5. your name is (blank), you are (blank) years old, and your username is (blank)
  6. for extra credit, have the program log this information in a file to be accessed later.
  7. """
  8.  
  9. db_path = "c1.db"
  10. con = sql.connect(db_path)
  11. cur = con.cursor()
  12.  
  13. def get_info():
  14.     print "What is your name, friend?"
  15.     name = raw_input("> ")
  16.    
  17.     print "How old are you?"
  18.     age = raw_input("> ")
  19.    
  20.     print "What is your reddit username?"
  21.     username = raw_input("> ")
  22.     print "\n","="*72
  23.     return (name,age,username)
  24.    
  25. def record(info,write=True):
  26.     cur.execute("create table if not exists challenge1( name text, age text, username text)") #Creates database table if it doesn't already exist.
  27.     if write:
  28.         cur.execute("insert into challenge1 values(?,?,?)",info)
  29.    
  30. def read_data():
  31.     try:
  32.         raw_data = cur.execute("select * from challenge1")
  33.     except sql.OperationalError:
  34.         record(info=None,write=False)
  35.         raw_data = cur.execute("select * from challenge1")
  36.     data = []
  37.     for row in raw_data:
  38.         data.append(row)
  39.        
  40.     return data
  41.    
  42.  
  43. def main():
  44.     while True:
  45.         print "1: Add entry"
  46.         print "2: List entries"
  47.         print "3: Drop table"
  48.         print "4: Exit"
  49.         next = raw_input("> ")
  50.         print "="*72
  51.         if next == '1':
  52.             info = get_info()
  53.             record(info)
  54.         if next == '2':
  55.             data = read_data()
  56.             for listing in data:
  57.                 name = listing[0]
  58.                 age = listing[1]
  59.                 username = listing[2]
  60.                 print "your name is '%s', you are '%s' years old, and your username is '%s'." % (name,age,username)
  61.                 if listing != data[-1]:
  62.                     print ""
  63.             print "="*72
  64.            
  65.         if next == '3':
  66.             cur.execute("drop table if exists challenge1")
  67.             print "Dropped the table!"
  68.             print "="*72
  69.            
  70.         if next == 'end' or next == 'break' or next == 'exit' or next == '4':
  71.             break
  72.     con.commit()
  73.     con.close()
  74.  
  75.  
  76. if __name__ == "__main__":
  77.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement