Sample Programs

Get Help With All Aspects of Web Design & Design Software

Moderators: Moderator, Global Moderator

Post Reply
Trinity
Hero Member
Hero Member
Posts: 808
Joined: Wed May 05, 2004 2:19 am

Sample Programs

Post by Trinity »

Having a go at Python? Post your work here /smile.gif' class='bbc_emoticon' alt=':)' />
Trinity
Hero Member
Hero Member
Posts: 808
Joined: Wed May 05, 2004 2:19 am

Sample Programs

Post by Trinity »

Code: Select all

##########################################################
### Text File Backup Program                           ###
### By Trinity                                         ###
##########################################################

# :- Init -: #
print "Welcome to the python backup system. You can use it to back up txt files."
print "Made by Trinity"

# :- Get File name -: #
file = raw_input("Enter the name of the file to back up: ")
x = file + ".txt"
z = file + "backup.txt"

# :- Get the os -: #
import os
inp = open(x,"r")
outp = open(z,"w")

for line in inp.readlines():
    outp.write(line)

# :- Confirm -: #
print "Backup Completed..."

print "Thankyou for using this program"
raw_input("Please type exit: ")
Very simple program, the first working one I made /smile.gif' class='bbc_emoticon' alt=':)' />
Trinity
Hero Member
Hero Member
Posts: 808
Joined: Wed May 05, 2004 2:19 am

Sample Programs

Post by Trinity »

Code: Select all

##########################################################
### Times Table Commands                               ###
### By Trinity                                         ###
##########################################################

def print_table(multiplier):
    print "--- Printing the %d times table ---" % multiplier
    for n in range(1,16):
        print "%d x %d = %d" % (n, multiplier, n*multiplier)
    print "------------------------------------------------"
    raw_input("Please type exit...")

# :- Init -: #
print "Welcome to your times table helper!"
print "Now entering the login process..."
print "---------------------------------"

# :- Variables -: #
coruser = "Trinity"
corpass = "password"

# :- Login Code -: #

user = raw_input("Please enter your username: ")
if user == coruser:
    print "Thankyou Trinity"
    password = raw_input("Please enter your password: ")
if user != coruser:
    print "Sorry %s you are not a recognized user!" % user
if password == corpass:
    print "Welcome Trinity, your password has been confirmed"
if password != corpass:
    print "That is the wrong password, please retype it!"
    password = raw_input("Please enter your password: ")
    if password == corpass:
        print "Welcome Trinity, your password has been confirmed"

# :- Times Table Code -: #

x = raw_input("Please enter the times table you would like to know: ")
print_table(10)
Again, mucking around with a very simple auth system, ends up printing multiples. First time I used a function /smile.gif' class='bbc_emoticon' alt=':)' />
Trinity
Hero Member
Hero Member
Posts: 808
Joined: Wed May 05, 2004 2:19 am

Sample Programs

Post by Trinity »

This was my first major project, I started it but never ended up finishing it - it was a good challenge but in the end it would be a console program with no GUI, and something that would be of little use to me. It was still an interesting excersize /smile.gif' class='bbc_emoticon' alt=':)' />

Code: Select all

##########################################################
### NetLog Version 1.2                                 ###
### By Trinity                                         ###
##########################################################

import os
import sys
import time


# -: Init :- #
print "Welcome To NetLog"
print "Version: 1.2"
print "By Trinity"
print ""


# -: Menus :- #
def menu_Root():
    print """
     Main Menu
     |==========================|
     | Option | Description     |
     |--------------------------|
     | 1      | Internet Log    |
     | 2      | Address Book    |
     | 3      | Credits         |
     |--------------------------|
     | m      | Menu            |
     | x      | Exit            |
     |==========================|
     
     """

def menu_Ilog():
    curdate = time.strftime("%d/%m/%Y") + ".txt"
    print """
     Internet Log Menu
     Logging to: %s
     |==========================|
     | Option | Description     |
     |--------------------------|
     | 1      | Add Log         |
     | 2      | View Log        |
     | 3      | Open Log        |
     | 4      | Print Log       |
     |--------------------------|
     | m      | Menu            |
     | b      | Back To Main    |
     |==========================|
     
     """ % curdate
# -: Internet Log Options :- #
def ilog_Add():
    os.system("cls")
    print ""
    print """
    For the type of log, you may enter any of the following commands:
    url, email, msn, security, program, info
    Or you may enter your own type.
    """
    type_ = raw_input("Please enter the type of log: ")
    if type_ == "url":
        notes = raw_input("Please enter the url: ")
    elif type_ == "email":
        notes = raw_input("Please enter the email address: ")
    elif type_ == "msn":
        notes = raw_input("Please enter the msn event: ")
    elif type_ == "security":
        notes = raw_input("Please enter the security event: ")
    elif type_ == "info":
        notes = raw_input("Please enter the information you have found: ")
    elif type_ == "irc":
        notes = raw_input("Please enter the irc server or information: ")
    else:
        notes = raw_input("Please enter the notes for your type: ")
    curtime = time.strftime("%H:%M:%S")
    print "Here is a preview of what you have entered:"
    print "-"
    print "Time: %s" % curtime
    print "Type: %s" % type_
    print "Notes: %s" % notes
    print "-"
    confirm = raw_input("Would you like to add this to the log? y/n: ")
    if confirm == "y":
        curdate = time.strftime("%d/%m/%Y")
        filename = curdate.replace("/","-") + ".txt"
        content = open(filename, "a")
        space = "-"
        content.write(space+"\n")
        content.write("Time: "+curtime+"\n")
        content.write("Type: "+type_+"\n")
        content.write("Info: "+notes+"\n")
        m_Ilog()
    elif confirm == "n":
        m_Ilog()
    else:
        print "Please enter y or n"
        confirm = raw_input("Would you like to add this to the log? y/n: ")
        if confirm == "y":
            curdate = time.strftime("%d/%m/%Y")
            filename = curdate.replace("/","-") + ".txt"
            content = open(filename, "w")
            space = "-"
            content.write(space+"\n")
            content.write("Time: "+curtime+"\n")
            content.write("Type: "+type_+"\n")
            content.write("Info: "+notes+"\n")
            m_Ilog()
        else:
            m_Ilog()

def ilog_View():
    os.system("cls")
    filen = raw_input("Please enter the name of the file, followed by .txt. To view today's log, type current: ")
    if filen == "current":
        filename = time.strftime("%d-%m-%Y") + ".txt"
    else:
        filename = filen
    print "File: %s" % filename
    readfile = file(filename, "r")
    for line in readfile.readlines():
        print line
    temp = raw_input("Press any key to return to the menu, or x to exit: ")
    if temp == "x":
        sys.exit()
    else:
        m_Ilog()

def ilog_Open():
    os.system("cls")
    filen = raw_input("Please enter the name of the file, followed by .txt. To view today's log, type current: ")
    if filen == "current":
        filename = time.strftime("%d-%m-%Y") + ".txt"
    else:
        filename = filen
    print "Now opening: %s" % filename
    print "Work out how to open this file!."
    temp = raw_input("Press any key to return to the menu, or x to exit: ")
    if temp == "x":
        sys.exit()
    else:
        m_Ilog()

# -: Menu Operation :- #
def m_Root():
    menu_Root()
    m_Option = raw_input("Please enter your menu option: ")
    if m_Option == "1":
        m_Ilog()
    elif m_Option == "2":
        menu_Abook()
    elif m_Option == "3":
         credits()
    elif m_Option == "m":
           m_Root()
    elif m_Option == "x":
        sys.exit()
    else:
        print "Sorry that choice is not available. Please note that the menu is case sensitive and doesn't use CAPS."  
        m_Root()

def m_Ilog():
    os.system("cls")
    menu_Ilog()
    m_Option = raw_input("Plase enter your menu option: ")
    if m_Option == "1":
        ilog_Add()
        print "Success"
    elif m_Option == "2":
        ilog_View()
    elif m_Option == "3":
        ilog_Open()
    elif m_Option == "4":
        ilog_Print()
    elif m_Option == "m":
        m_Ilog()
    elif m_Option == "b":
        m_Root()
    else:
        print "Sorry that choice is not available. Please note that the menu is case sensitive and doesn't use CAPS."
        m_Ilog()

m_Root()
tidy trax
Newbie
Newbie
Posts: 5
Joined: Sat Oct 23, 2004 2:58 pm

Sample Programs

Post by tidy trax »

Here's a pretty useless example of using Tkinter in python, I won't bother explaining it because you can learn all about tkinter [url="http://www.pythonware.com/library/tkinter/introduction/index.htm"]here[/url].

Code: Select all

from Tkinter import *

class App:
    def __init__(self, master):
        frame=Frame(master)
        frame.pack()

        self.days=Listbox(frame, fg='black', selectbackground='red', selectmode=EXTENDED)
        for day in ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']:
            self.days.insert(END,day)
            self.days.pack(side=TOP)

        self.list=Button(frame, text='List days', command=self.SelectCheck)
        self.list.pack(side=LEFT)

    def SelectCheck(self):
        print 'You have selected the following days:\n'
        for day in self.days.curselection():
            print self.days.get(day)

root = Tk()
app = App(root)
root.mainloop()
tidy trax
Newbie
Newbie
Posts: 5
Joined: Sat Oct 23, 2004 2:58 pm

Sample Programs

Post by tidy trax »

This little snippet will find five types of audio in a certain directory and return the results in a list.

Code: Select all

from glob import *
from string import *

def FindAudio(Directory):
    Audio = []
    Directory += '\\*'
    for Filename in glob(Directory):
        SFilename = Filename.split('.')
        if SFilename[len(SFilename) - 1] in ['midi', 'mp3', 'ogg', 'wav', 'wma']:
            Audio.append(Filename)
    return Audio
Usage: FindAudio(Directory)
Trinity
Hero Member
Hero Member
Posts: 808
Joined: Wed May 05, 2004 2:19 am

Sample Programs

Post by Trinity »

Nice tidy - I used wxPython for GUI instead of Tkinter, it was just too confusing /blum.gif' class='bbc_emoticon' alt=':P' />
Vercz
Hero Member
Hero Member
Posts: 1915
Joined: Sat May 08, 2004 11:13 pm

Sample Programs

Post by Vercz »

never did understand Tkinter..spose thats why i never used it /blum.gif' class='bbc_emoticon' alt=':P' />

wxPython all the way!! /good.gif' class='bbc_emoticon' alt='(Y)' />
Image

Image
tidy trax
Newbie
Newbie
Posts: 5
Joined: Sat Oct 23, 2004 2:58 pm

Sample Programs

Post by tidy trax »

Tkinter's a lot less confusing than wxPython, it just doesn't have as many controls, in fact, it's missing quite a few vital ones such as the combo box.
Post Reply

Return to “Web Design Principles”