Page 3 of 4 FirstFirst 1234 LastLast
Results 21 to 30 of 32

Thread: [Beginner] Programming Challenge: 7

  1. #21
    Join Date
    Oct 2006
    Location
    Philadelphia, Penn.
    Beans
    137
    Distro
    Ubuntu 12.04 Precise Pangolin

    Re: [Beginner] Programming Challenge: 7

    Hi all, here is my entry, it is not complete. I am going out tonight, working tomorrow, and going to the Eagles game on Sunday. So I'll be a little busy. Anyways, once I get back I'll add the error checking and the displaying of the data in a nice neat fashion.

    Well for the database part I used buzhug. I am very new to programming so don't bust... Looks like my code is the simplest though...

    You have to install buzhug for this to work, http://buzhug.sourceforge.net/

    Code:
    from buzhug import Base
    
    db = Base('pyProgChal').create(('name',str),('age',int),mode='open')
    
    def inputData():
    	global db
    	name = str(raw_input('Please enter name: '))
    	age = int(raw_input('Please enter age: '))
    	db.insert(name,age)
    	menu()
    
    def retrData():
    	global db
    	nameData = db.select(['name'])
    	ageData = db.select(['age'])
    	print nameData
    	print ageData
    	menu()
    
    def menu():
    	menu = """
    	Please make a selection:
    		1) Input Data
    		2) Retreive Data
    
    		0) Exit
    	"""
    
    	start = int(raw_input(menu))
    	# try statement to capture incorrect entries
    
    	if start == 1:
    		inputData()
    	elif start == 2:
    		retrData()
    	elif start == 0:
    		import sys
    		sys.exit
    	else:
    		print 'Please select 1, 2, or 3'
    		
    
    if __name__ == "__main__":
    	menu()
    Last edited by nuclearj; October 11th, 2008 at 07:38 AM.
    Every one should belive in something... I believe I'll have another drink!

  2. #22
    Join Date
    Jun 2008
    Location
    California, USA
    Beans
    1,030
    Distro
    Ubuntu 9.04 Jaunty Jackalope

    Re: [Beginner] Programming Challenge: 7

    Quote Originally Posted by ghostdog74 View Post
    why are you putting your database statements inside the class?
    For no reason at all really.

    Blog | I'm available for programming contributions. C & Python.
    Intel Core i7 920 | EVGA x58 SLI | NVidia GeForce 8600 GT | WD 500GB HDD | Corsair XMS3 3GB | Ubuntu 9.04

  3. #23
    Join Date
    Apr 2007
    Beans
    14,781

    Re: [Beginner] Programming Challenge: 7

    Quote Originally Posted by OutOfReach View Post
    For no reason at all really.
    Shame on your for not having world class code in a beginner challenge!

    Yes, SQLite is very easy and handy

  4. #24
    Join Date
    Oct 2007
    Beans
    67
    Distro
    Ubuntu 7.04 Feisty Fawn

    Re: [Beginner] Programming Challenge: 7

    I am trying to use SQLite in Perl and I am having trouble installing the necessary modules from CPAN. Any help?
    Help raise community spirit! Contribute to the BUMP Thread at http://ubuntuforums.org/showthread.php?t=520091
    Assimilate! http://ubuntuforums.org/group.php?groupid=265!

  5. #25
    Join Date
    Oct 2007
    Beans
    67
    Distro
    Ubuntu 7.04 Feisty Fawn

    Re: [Beginner] Programming Challenge: 7

    Is there a new challenge or has everyone just become bored? Anyway, here is my submission (run it from wherever; it will put the SQLite database in your home directory).

    BE SURE TO INSTALL DBI AND DBD::SQLite VIA CPAN!

    challenge.pl:

    Code:
    #!/usr/bin/perl
    
    use diagnostics;
    
    use DBI;
    
    sub ask_command()
    {
    	print "(store/get/exit/new):\t";
    	$response=<STDIN>;
    	chomp($response);
    	$response;
    }
    
    sub is_new()
    {
    	$dbh->do("CREATE TABLE people (name, age);");
    }
    
    sub store_entry()
    {
    	print "NAME:\t";
    	chomp($name=<STDIN>);
    	print "AGE:\t";
    	chomp($age=<STDIN>);
    	$dbh->do("INSERT INTO people VALUES ('$name',$age)");
    }
    
    sub get_entry()
    {
    	print "(name/age/all):\t";
    	chomp ($name_age=<STDIN>);
    	
    	if ($name_age eq 'name')
    	{
    		print "NAME:\t";
    		chomp($name=<STDIN>);
    		my $all=$dbh->selectall_arrayref("SELECT age FROM people WHERE name = '$name'");
    		foreach my $row (@$all)
    		{
    			($age)=@$row;
    			print "AGE:\t$age\n";
    		}
    	}
    	if ($name_age eq 'age')
    	{
    		print "AGE:\t";
    		chomp($age=<STDIN>);
    		my $all=$dbh->selectall_arrayref("SELECT name FROM people WHERE age = $age");
    		foreach my $row (@$all)
    		{
    			($name)=@$row;
    			print "NAME:\t$name\n";
    		}
    	}
    	if ($name_age eq 'all')
    	{
    		my $all=$dbh->selectall_arrayref("SELECT name, age FROM people");
    		foreach my $row (@$all)
    		{
    			($name,$age)=@$row;
    			print "NAME:\t$name\nAGE:\t$age\n";
    		}
    	}
    }
    
    $dbh=DBI->connect("dbi:SQLite:dbname=/home/$ENV{LOGNAME}/names.sqlt","","", { RaiseError => 1, AutoCommit => 1});
    
    print "\n\tWelcome to Challenge7!  If you have not yet created your names and ages table, enter 'new' in the following prompt to do so.  Otherwise, select 'store' to store rows, 'get' to retrieve all rows or filter by name or age, and 'exit' to leave this program.  Your empty database (without the necessary table) has already be created if it did not already exist in '/home/$ENV{LOGNAME}/names.sqlt' Enjoy, and please have the courtesy to file a bug report if you find a bug.\n\n";
    
    $command=&ask_command;
    
    while ($command ne 'exit')
    {
    	if ($command eq 'new')
    	{
    		is_new();
    	} else
    	{
    	if ($command eq 'store')
    	{
    		store_entry();
    	} else
    	{
    	if ($command eq 'get')
    	{
    		get_entry();
    	}
    	}
    	}
    	$command=&ask_command;
    }
    Last edited by indecisive; November 11th, 2008 at 11:21 PM. Reason: Important note
    Help raise community spirit! Contribute to the BUMP Thread at http://ubuntuforums.org/showthread.php?t=520091
    Assimilate! http://ubuntuforums.org/group.php?groupid=265!

  6. #26
    Join Date
    Dec 2006
    Location
    Perth Amboy, NJ
    Beans
    141
    Distro
    Ubuntu 9.04 Jaunty Jackalope

    Re: [Beginner] Programming Challenge: 7

    yeah i was wondering if a new challenge would be given yet...

    Welcome to the world of Open Source!!!
    Linux User #471120 Ubuntu User #21997
    Jaunty Jackalope 9.04

  7. #27
    Join Date
    Oct 2007
    Beans
    67
    Distro
    Ubuntu 7.04 Feisty Fawn

    Re: [Beginner] Programming Challenge: 7

    LaRoza was banned, that must be why.
    Help raise community spirit! Contribute to the BUMP Thread at http://ubuntuforums.org/showthread.php?t=520091
    Assimilate! http://ubuntuforums.org/group.php?groupid=265!

  8. #28
    Join Date
    Apr 2007
    Location
    (X,Y,Z) = (0,0,0)
    Beans
    3,715

    Re: [Beginner] Programming Challenge: 7

    Quote Originally Posted by indecisive View Post
    LaRoza was banned, that must be why.
    ?

    Anyone is free to post a challenge... (I'd do, but have no idea on what )

  9. #29
    Join Date
    Jul 2008
    Beans
    1,706

    Re: [Beginner] Programming Challenge: 7

    how bout something that isnt math related like most challanges are...i mean strictly math related (as in calculate...)

  10. #30
    Join Date
    Feb 2013
    Beans
    3

    Re: [Beginner] Programming Challenge: 7

    Here is my attempt for this Challenge, I'm using Python 3.2.

    Code:
    # Beginner programming challenge 7
    
    from sqlite3 import dbapi2 as sqlite
    import sys
    
    connection = sqlite.connect("test.db")
    cursor = connection.cursor()
    
    print("Welcome. Type 'r' to print the database or 'w' if you want to add data.\nType 'q' to exit.\n")
    
    
    def get_choice():
        global choice
        choice = input("Please type 'r','w', or 'q': ")
                
        if choice in ("r","w","q"):
            pass
        else:
            print("This is not a valid command.")
            get_choice()
        
    
    def get_name():
        uinput = input("Please type a name: ")
    
        global name
        name = str(uinput)
    
    
    def get_age():
        uinput = input("Please enter an age higher than 0 (100 max): ")
    
        try:
            global age
            age = int(uinput)
        except ValueError:
            print("You must type an integer!")
            get_age()
            
        if age < 1 or age > 100:
            print("This is not a valid age.")
            get_age()
    
    
    
    try:
        cursor.execute("create table data(NAME,AGE)")
    except: # if the table already exists
        pass
    
    get_choice()
    
    
    while choice == "w":
        get_name()
        get_age()
        cursor.execute("insert into data values(?,?)",(name,age))
        connection.commit()
    
        print("Type 'w' again to add more data, 'r' to print or 'q' to exit.")
        get_choice()
    
    
    if choice == "r":
        cursor.execute("select * from data")
        for row in cursor:
            print ("-"*20,'\nName:', row[0],'\nAge:', row[1])
            print("-"*20)
    
    
    cursor.close()
    connection.close()
    
    if choice == "q":
        sys.exit(0)

Page 3 of 4 FirstFirst 1234 LastLast

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •