Ene Uran 638 Posting Virtuoso

You should have 2 files, let's say your p2e templet file p2e_test1.py modified with your code filename, and your code file test1.py. Save these 2 files in the same directory and just douple-click on p2e_test1.py

That's really all there is to it!

Otherwise make sure the Python versions match, you seem to be using Python 2.5. I avoid IDLE as an IDE, just too primitive!

Ene Uran 638 Posting Virtuoso

1) Py2Exe is not easy to use!

2) Have you looked at the Py2Exe snippet at Daniweb? That should make it easier to use!

3) Have you been able to package any Python code into an exe?

4) Your program might be small, but there are some 'outhouse' modules that don't do well.

Ene Uran 638 Posting Virtuoso

Your error trapping in the letter grades can be mildly improved:

s = 'A,A-,A+,B,B-,B+,C,C-,C+,D,D-,D+,F'
ps = """
Enter grade letters A through F, you
can also postfix A through D with + or -
(press just Enter to exit the loop when done): """
while True:
    x = raw_input(ps).upper()
    print x  # test
    if x == "":
        done = True
        break
    if x in s:
        break
    else:
        print "Error, use", s

# .........

There is another improvement possible when you assign a value to the grade letters:

letter = 'B+'  # test

# the index found is 0 to 4, and -1 if not found
ngrade = "FDCBA".find(letter[0])  

partial = 0.33  # or 0.25 this may vary with the school
if '+' in letter:
    ngrade = ngrade + partial
if '-' in x:
    ngrade = ngrade - partial
    
print ngrade  # test
Ene Uran 638 Posting Virtuoso

This if statment logic will not work for you if letter == "A" or "A-" or "A+": . You have to break it up, here is an example:

ps = """
Enter grade letters A through F, you
can also postfix A through D with + or -
(press just Enter to exit the loop when done): """
x = raw_input(ps).upper()

if 'A' in x:
    n = 4
elif 'B' in x:
    n = 3
elif 'C' in x:
    n = 2
elif 'D' in x:
    n = 1
elif 'F' in x:
    n = 0
    
partial = 0.33  # or 0.25 this may vary with the school
if '+' in x:
    n = n + partial
if '-' in x:
    n = n - partial

print n  # test
Ene Uran 638 Posting Virtuoso

Actually the Python25 version of wxPython has a flash player component. Here is the demo they give:

import  os
import  wx

if wx.Platform == '__WXMSW__':
    from wx.lib.flashwin import FlashWindow

from Main import opj

#----------------------------------------------------------------------

class TestPanel(wx.Panel):
    def __init__(self, parent, log):
        wx.Panel.__init__(self, parent, -1)
        self.pdf = None

        sizer = wx.BoxSizer(wx.VERTICAL)
        btnSizer = wx.BoxSizer(wx.HORIZONTAL)

        self.flash = FlashWindow(self, style=wx.SUNKEN_BORDER)
        self.flash.LoadMovie(0, 'file://' + os.path.abspath('data/Asteroid_blaster.swf'))

        sizer.Add(self.flash, proportion=1, flag=wx.EXPAND)

        btn = wx.Button(self, wx.NewId(), "Open Flash File")
        self.Bind(wx.EVT_BUTTON, self.OnOpenFileButton, btn)
        btnSizer.Add(btn, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)

        btn = wx.Button(self, wx.NewId(), "Open Flash URL")
        self.Bind(wx.EVT_BUTTON, self.OnOpenURLButton, btn)
        btnSizer.Add(btn, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)

        btnSizer.Add((50,-1), proportion=2, flag=wx.EXPAND)
        sizer.Add(btnSizer, proportion=0, flag=wx.EXPAND)

        self.SetSizer(sizer)
        self.SetAutoLayout(True)



    def OnOpenFileButton(self, event):
        dlg = wx.FileDialog(self, wildcard="*.swf")

        if dlg.ShowModal() == wx.ID_OK:
            wx.BeginBusyCursor()
            self.flash.LoadMovie(0, 'file://' + dlg.GetPath())
            wx.EndBusyCursor()

        dlg.Destroy()


    def OnOpenURLButton(self, event):
        dlg = wx.TextEntryDialog(self, "Enter a URL of a .swf file", "Enter URL")

        if dlg.ShowModal() == wx.ID_OK:
            wx.BeginBusyCursor()
            # setting the movie property works too
            self.flash.movie = dlg.GetValue() 
            wx.EndBusyCursor()

        dlg.Destroy()



#----------------------------------------------------------------------

def runTest(frame, nb, log):
    if wx.Platform == '__WXMSW__':
        win = TestPanel(nb, log)
        return win
    else:
        from Main import MessagePanel
        win = MessagePanel(nb, 'This demo only works on Microsoft Windows.',
                           'Sorry', wx.ICON_WARNING)
        return win


overview = """\
<html><body>
<h2>wx.lib.flashwin.FlashWindow</h2>

The wx.lib.pdfwin.FlashWindow class is yet another example of using
ActiveX controls from wxPython using the new wx.activex module.  This
allows you to use an ActiveX control as if it is a wx.Window, you can
call its methods, set/get properties, and receive events from the
ActiveX control in a very intuitive way.

<p> Using this class is simpler than ActiveXWrapper, doesn't rely …
Ene Uran 638 Posting Virtuoso

There are 4,017,010 characters in the authorized version of the Bible. War and Peace shouldn't be much larger.

Can you put the entire text of the Bible in one string and save it?
You can test it with this simple program, gives no problems on my PC:

# create a 5M character string
large_string = 'a' * 5000000

# open the file for writing
fout = open( 'String5M.txt', 'w' )
# write 5M character text
fout.write(large_string)
# close the file
fout.close()
Ene Uran 638 Posting Virtuoso

I looked at some of your questions.

#I AM CONFUSED RIGHT HERE. SHOULD IT BE:
 self.letter = letter

Since you only going to use the variable 'letter' in this particular method, you can keep it local, no need to add the 'self.' prefix.

for ch in letter:
            print ord(ch)

The function ord() gives you the ASCII value for the character, for instance 'A' would give you the integer 65.

stu.addLetterGrade(grade_str, credits)

Yes you are calling a method of the class instance 'stu'

You really wouldn't need a class for a simple program like this, but if you had a number of students you could create an instance for each, something like:

bill = Student("Bill Bunker", 0.0, 0.0)
tom = Student("Tom Tinker", 0.0, 0.0)
henry = Student("Hank Prince", 0.0, 0.0)

An extension of your program, so each student has his/her own class instance that could be saved with all the data when you are done.

Ene Uran 638 Posting Virtuoso

If you use a test print statement above the line that puts a value into pricePass, you will find that the if condition doesn't allow you to get there, so the variable pricePass is valueless. Since Python defines the type of the variable by inference, it can't do that with a valueless variable.

Here is the offending condition:

if variable2[0] == passType:
                print variable2[1]
                print variable2[2]
                print "defining variable passPrice"  # test
                passPrice = float(price)*float(variable2[2])
                print passPrice

In your first version you never used passPrice, but price. So the runtime error did not come up.

Also a word of advice:
1) start your class names with a capital letter
2) create class instances like:
main = Main(root)
child = Child()
3) now you can get rid of the globals by associating the variables properly to the class instance via self. or the instance name.

Ene Uran 638 Posting Virtuoso

You need to learn to experiment a little with the code, its fun!

# let user resize the Tkinter window, but do not move widgets
 
from Tkinter import *
 
root = Tk()
 
b1 = Button(root, text='Button 1')
# tells the widget not to expand into the packing cell
# and to anchor itself to the NW (upper left) corner
b1.pack(expand=NO, anchor=NW)

b2 = Button(root, text='Button 2')
# tells the widget not to expand into the packing cell
# and to anchor itself to the next free NW (upper left) corner
b2.pack(expand=NO, anchor=NW)
 
root.mainloop()
Ene Uran 638 Posting Virtuoso

Here is away to take care of chemical prefixes like 'o-', 'm-' and 'p-' when sorting. Just a little commonly used trick you can also use when sorting by your table columns:

# table of chemicals in stockroom as list of lists
# order --> stock number, chemical name, quantity (grams)

from operator import itemgetter

def sort_table(table, column_num):
    """
    sort a list of sublists that form a table by column number
    note that first column in table starts with column_num zero
    """
    return sorted(table, key=itemgetter(column_num))

def sort_chem(table):
    """
    this should take care of 'o-', 'm-' and 'p-' prefixes
    temporary change of sublist by adding modified chemical as first item
    sort this temp list and then rebuild by removing the temporary first item
    """
    temp = []
    for item in table:
        chem = item[CN]
        # removes leading 'o-' and adds '-o' to end for sort
        # you can add more similar prefixes here too
        if chem.startswith('o-'):
            chem = chem[2:] + '-o'
        if chem.startswith('m-'):
            chem = chem[2:] + '-m'
        if chem.startswith('p-'):
            chem = chem[2:] + '-p'        
        temp.append([chem,item])
    # this will sort by first item in each sublist
    temp.sort()
    new_table = []
    # rebuild the proper table
    for item in temp:
        #print item  # for test
        new_table.append(item[1])
    return new_table
 
def print_table(table):
    """
    pretty print the table
    """
    print '-'*66
    print "%-10s   %-40s  %s" % ('stock', 'chemical', 'quantity(g)')
    print '-'*66
    for item in table:
        print "%-10s   %-40s  %8d" % (item[0], item[1], item[2])
    print '-'*66

# assign constants
SN = 0  # index of …
Ene Uran 638 Posting Virtuoso

Method curselection() returns a tuple of the selections in case you selected more than one line, in your case pick tuple item zero. Change the your code line to reflect that:

passType=self.listPass.curselection()[0]
Ene Uran 638 Posting Virtuoso

Might have to add an edit option to the search_title() function. Good idea though! I am thinking of wrapping this all into a Tkinter GUI, that would make editing easier using an Entry widget.

Ene Uran 638 Posting Virtuoso

Looks like yo want to open a file called "50" even though the list is all integers.

mattyd commented: Ene Uran is always of Great Help. He\ She should Moderate at DaniWeb! +1
Ene Uran 638 Posting Virtuoso

There are a number of GUI toolkits for Python, but they are all Python wrappers for other languages. Tkinter is based on tcl, wxPython is based on wxWindows (works on Unix and Windows) written in C++, there is pygtk based on the ever so popular GTK, even pygame can be looked at as a GUI based on SDL.

There is nothing that should keep you back from writing a GUI from scratch. Not having seen such an effort by anyone I know, I supect that it might be a tad time consuming. Let me know when you have a product.

Ene Uran 638 Posting Virtuoso

So that is where that went to! I thought I saw that for a moment in the stickies.

Ene Uran 638 Posting Virtuoso

You can use eval() to turn a string into an object.

Ene Uran 638 Posting Virtuoso

This is just a test frame where the robot moves at more or less at random, avoiding walls and blocks. When the robot sees an open coin it moves there and fetches it. Eventually it will get all the coins unless they are totally blocked in. Now one has to add look ahead strategy to minimize the moves. I am having fun with that!

# module robotlib.pyc from: 
# http://www.cs.sfu.ca/CC/120/ggbaker/assign-1067/assign4-robot

#from Tkinter import *
import random
from robotlib import *

# use one of the testboards (0 - 16)
r = Robot(testboard=12)

def look_around():
    """
    directions are N, E, S, W
    obj can be WALL, COIN, BLOCK (avoid hitting Block and WALL)
    dist is distance including the space of obj    
    """
    sensor_list = []
    for dir in [N, E, S, W]:
        obj, dist = r.sensor(dir)
        sensor_list.append((dist, obj, dir))
    return sensor_list

def check_coin():
    """
    check if there is a COIN in item[1] of the tuple
    """
    sensor_list = look_around()
    coin_list = []
    for item in sensor_list:
        if item[1] == COIN:
            coin_list.append(item)
    if coin_list:
        # sort the tuples so closest distance is first
        return sorted(coin_list)
    else:
        return False

def fetch_coin(coin_list):
    # move robot to closest=item[0] of tuple in coin_list[0]
    spaces = coin_list[0][0]
    # move direction=item[2] of tuple in coin_list[0]
    dir = coin_list[0][2]
    for x in range(spaces):
        r.move(dir)

def check_blockwall():
    """
    check if there is a BLOCK or WALL in item[1] of the tuple
    and is it next to the robot
    don't move in any of the directions in the …
Ene Uran 638 Posting Virtuoso

Solving a project's problems is really a good way to learn Python. You did well!

Ene Uran 638 Posting Virtuoso

Your error is in the line:

image_dir = "C:\Documents and Settings\RockStar\Desktop\Python\drpython-161\Cards_gif\C2.gif"

you have to change it to just the directory name:

image_dir = "C:\Documents and Settings\RockStar\Desktop\Python\drpython-161\Cards_gif\"
Ene Uran 638 Posting Virtuoso

If with 'simple' you mean 'not unnecessarily complex', I agree. Python is in many ways more powerfull than C++ or Java. Learning Python first might lead to a lot of pissing and moaning by the students who have to confront the often silly complexities of these other languages later. Well, good karma with your studies.

Have you started pseudo-coding your project? You might find out that it looks almost like Python syntax.

Ene Uran 638 Posting Virtuoso

Interesting project, I will play with it!
Just curious, is this a computer science course? Hard to digest, since most CS departments are bastions of conservative stuff like C++ and Java. Engineering and Science departments luckily have been more pragmatic and open to using Python.

Ene Uran 638 Posting Virtuoso

C:\Documents and Settings\RockStar\Desktop\Python\drpython-161\Cards_gifC2.gif looks like your image directory is C:\Documents and Settings\RockStar\Desktop\Python\drpython-161\ and your image file name is Cards_gifC2.gif . You wnat to make this C:\Documents and Settings\RockStar\Desktop\Python\drpython-161\Cards_gif\ and then the image name will be C2.gif

Ene Uran 638 Posting Virtuoso

Avoiding the endless begin/end or curly braces, and also the end of line semicolons makes code simpler to read and understand. When you use an editor made for Python, indentations become easy to follow. You absolutley have to avoid mixing spaces with tabs in your indents. That's the main reason you have problems with other folks code! I religiously use spaces (4) only, since tab settings vary so much.

Ene Uran 638 Posting Virtuoso

If you don't want to get into the complexities of a standard sql database, you could simply modifiy my little structure/record based database in the Python code snippets at:
http://www.daniweb.com/code/snippet604.html

It allows you to load, save, add, list (as table), search, and delete data items. Need any help with that, just ask here.

Ene Uran 638 Posting Virtuoso

Hey thanks!
I enjoyed testing your nice code! I love to learn and really appreciate your problemsolving!

Ene Uran 638 Posting Virtuoso

Rather then MySQL you can use SQLite, sqlite3 is built into Python version 2.5 or you can download pysqlite2 for older versions.

Here is an example to create a database file:

# create a SQL database file
# pySQLite homepage (for Python24): http://initd.org/tracker/pysqlite
# tested with Python25 (has sqlite3 builtin)

try:
    from sqlite3 import dbapi2 as sqlite    # Python25
except ImportError:
    from pysqlite2 import dbapi2 as sqlite  # Python24 and pysqlite

# create a database:
con = sqlite.connect('mydatabase.db3')
cur = con.cursor()

# create a table:
cur.execute('create table clients (id INT PRIMARY KEY, name CHAR(60))')

# insert a single line:
client = (5,"John Smith")
cur.execute("insert into clients (id, name) values (?, ?)", client )
con.commit()

# insert several lines at once:
clients = [ 
(7,"Ella Fitzgerald"),
(8,"Louis Armstrong"),
(9,"Miles Davis")
]
cur.executemany("insert into clients (id, name) values (?, ?)", clients )
con.commit()

cur.close()
con.close()

Here is the example that reads the database file:

# read a SQL database file

try:
    from sqlite3 import dbapi2 as sqlite    # Python25
except ImportError:
    from pysqlite2 import dbapi2 as sqlite  # Python24 and pySqlite

# connect to an existing database
con = sqlite.connect('mydatabase.db3')
cur = con.cursor()

# get row by row
print "Row by row:"
cur.execute('select id, name from clients order by name;')
row = cur.fetchone()
while row:
    print row
    row = cur.fetchone()

# get all rows at once:
print "All rows at once:"
cur.execute('select id, name from clients order by name;')
print cur.fetchall()

cur.close()
con.close()
Ene Uran 638 Posting Virtuoso

You use something like shutil.copy(source_file, destination_file). You can't use the items in listbox2 since that's only the filename, so you have to use the items in the companion fullpath_list. The source_file is made up from the tuple's dirname and filename components. The destination_file is made up from the destination directory and the same filename.

Ene Uran 638 Posting Virtuoso

You are lucky getting a hold of Robin, the expert with wxPython. Did he ask you to buy his book on wxPython?

Ene Uran 638 Posting Virtuoso

Hi there danizzil14, I am giving you two examples of a simple Tkinter 'Hello World' code. The first one is without the use of class:

# Tkinter programming without a class

from Tkinter import *

def say_hi():
    # function for hi_button action
    # show new text on the label
    hi_label.config(text="Hi there, everyone!")


# create the basic window
root = Tk()

frame = Frame(root)
frame.pack()
# specify button action with command=function
# foreground/fg is red to color text
q_button = Button(frame, text=" QUIT ", fg="red", command=root.destroy)
q_button.pack(side=LEFT)

hi_button = Button(frame, text=" Hello ", command=say_hi)
hi_button.pack(side=LEFT)
# width of label is in characters
hi_label = Label(frame, text=" Hello, world! ", bg='yellow', width=20)
hi_label.pack(side=LEFT)

# start the event loop to respond to mouse clicks etc.
root.mainloop()

Here is the same program using a class structure:

# Tkinter programming using a class

from Tkinter import *

class App(object):
    """create a frame/window with 2 buttons and a label"""
    def __init__(self, master):
        frame = Frame(master)
        frame.pack()
        # specify button action with command=function
        # foreground/fg is red to color text
        self.q_button = Button(frame, text=" QUIT ", fg="red", command=root.destroy)
        self.q_button.pack(side=LEFT)

        self.hi_button = Button(frame, text=" Hello ", command=self.say_hi)
        self.hi_button.pack(side=LEFT)
        # width of label is in characters
        self.hi_label = Label(frame, text=" Hello, world! ", bg='yellow', width=20)
        self.hi_label.pack(side=LEFT)

    def say_hi(self):
        # function for hi_button action
        # show new text on the label
        self.hi_label.config(text="Hi there, everyone!")

# create the basic window
root = Tk()
# instantiate the App class
app = App(root)
# start the event loop to respond to …
Ene Uran 638 Posting Virtuoso

My humble contribution using a list comprehension:

# create a unique sorted list of all upper case letters in text
text = "This text has Upper and Lower Case Letters"
unique_list = []
[unique_list.append(c) for c in text if c.isupper() and c not in unique_list]
print sorted(unique_list)   # ['C', 'L', 'T', 'U']

Here is the breakdown of vegaseat's one liner as I see it:

text = "This text has Upper and Lower Case Letters"

uppers_raw = re.findall("[A-Z]", text)  # ['T', 'U', 'L', 'C', 'L']
uppers_set = set(uppers_raw)            # set(['C', 'U', 'T', 'L'])
uppers_list = list(uppers_set)          # ['C', 'U', 'T', 'L']
uppers_sorted = sorted(uppers_list)     # ['C', 'L', 'T', 'U']
Ene Uran 638 Posting Virtuoso

Scripting languages:
If you are familiar with C/C++ use Python.
If you are familiar with Java use Jython.
If you are familiar with Csharp use Lsharp (LispSharp).

Ene Uran 638 Posting Virtuoso

Used Reply with Quote, but it came up empty.
Anyway DarkFlash, thanks for the great Python site!

Ene Uran 638 Posting Virtuoso

Alright, I figured out how to do it, did some more research and stumbled on the answer

import ftplib                                          # We import the FTP module
session = ftplib.FTP('myserver.com','login','passord') # Connect to the FTP server
myfile = open('toto.txt','rb')                         # Open the file to send
session.storbinary('STOR toto.txt', myfile)            # Send the file
myfile.close()                                         # Close the file
session.quit()                                         # Close FTP session

hopefully somebody may find this useful. the site i found this at was:
http://sebsauvage.net/python/snyppets/

Hey DarkFkash, greate Python site!!! Thanks!

Ene Uran 638 Posting Virtuoso

In MAIN SIZER CONTROL don't add the sizer to a sizer, but the panel:

import wx
 
ID_MENU_EXIT   = 101
ID_MENU_ABOUT  = 102
ID_RADIO_FORWARDS   = 201
ID_RADIO_STATIONARY = 202
ID_RADIO_BACKWARDS  = 203
 
 
class Frame1(wx.Frame): 
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, -1, title, pos=(150, 150), size=(640, 480))
 
### MENU ###
 
        # Create a menubar at the top of the frame
        MenuBar = wx.MenuBar()
        FileMenu = wx.Menu()
        HelpMenu = wx.Menu() 
        # Add items to the menu                
        FileMenu.Append(ID_MENU_EXIT, "E&xit\tAlt-F4", "Exit the program")
        HelpMenu.Append(ID_MENU_ABOUT, "&About", "About the program")
 
        # Bind the menu event to an event handler        
        self.Bind(wx.EVT_MENU, self.OnMenuExit, id=ID_MENU_EXIT)
        self.Bind(wx.EVT_MENU, self.OnMenuAbout, id=ID_MENU_ABOUT)
 
        # Put the menu on the menubar
        MenuBar.Append(FileMenu, "&File")
        MenuBar.Append(HelpMenu, "&Help")
        self.SetMenuBar(MenuBar)
 
### STATUS BAR ###
 
        # create a status bar at the bottom of the frame
        self.CreateStatusBar()
 
 
### TITLE PANEL ###
 
        Title_Panel = wx.Panel(self)
 
        Title_Label = wx.StaticText(Title_Panel, -1, "Sequence Driven Controller")
        Title_Label.SetFont(wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.BOLD, True))
        Title_Label.SetForegroundColour('#00009F')
 
        Title_Sizer = wx.BoxSizer(wx.VERTICAL)
        Title_Sizer.Add(Title_Label, 0, wx.ALL, 10)
 
        Title_Panel.SetSizer(Title_Sizer)
        Title_Panel.Layout()
 
### DIRECTION PANEL ###
 
        Direction_Panel = wx.Panel(self)
        RadioButtonForwards = wx.RadioButton(Direction_Panel, ID_RADIO_FORWARDS, "Forwards")
        RadioButtonStationary = wx.RadioButton(Direction_Panel, ID_RADIO_STATIONARY, "Stationary")
        RadioButtonBackwards = wx.RadioButton(Direction_Panel, ID_RADIO_BACKWARDS, "Backwards")
        Direction_Sizer = wx.BoxSizer(wx.HORIZONTAL)
        Direction_Sizer.Add(RadioButtonForwards, 0, wx.ALL, 10)
        Direction_Sizer.Add(RadioButtonStationary, 0, wx.ALL, 10)
        Direction_Sizer.Add(RadioButtonBackwards, 0, wx.ALL, 10)
 
        Direction_Panel.SetSizer(Direction_Sizer)
        Direction_Panel.Layout()
 
 
### MAIN SIZER CONTROL ###
        
        Main_Sizer = wx.BoxSizer(wx.VERTICAL)
        #Main_Sizer.Add(Title_Sizer, 0, wx.ALL, 10)  # don't add the sizer but the panel
        Main_Sizer.Add(Title_Panel, 0, wx.ALL, 10)
        #Main_Sizer.Add(Direction_Sizer, 0, wx.ALL, 10)  # don't add the sizer but the panel
        Main_Sizer.Add(Direction_Panel, 0, wx.ALL, 10)
 
        self.SetSizer(Main_Sizer)
        Main_Sizer.Layout()
        
 
### MENU EVENTS ###
 
    def OnMenuExit(self, evt):
        self.Close()
 
    def OnMenuAbout(self, evt):
        dlg = …
Ene Uran 638 Posting Virtuoso

Must be your first attempt at ELIZA type AI.
The function friends() is called, but does not exist. What is it supposed to do?

Ene Uran 638 Posting Virtuoso

This is a perfect application for a class! I took the Python snippet at:
http://www.daniweb.com/code/snippet390.html
and modified it slightly for the solvent database application:

# example of a small solvent database using a list of class instances

import operator  # for attrgetter()

class Solvent(object):
    """a structure class for solvents, self refers to the instance"""
    def __init__(self, name=9999, bp=9999, mp=9999, fp=9999):
        self.name = name
        self.bp = bp     # boiling point degC
        self.mp = mp     # melting point degC
        self.fp = fp     # flash point degC


def table(solvent_list):
    """print a table of all solvent attributes"""
    print "-"*50
    print "%-20s  %8s  %8s  %8s" % ("Name", "Bp", "Mp", "Fp")
    for solvent in solvent_list:
        print "%-20s  %8.1f  %8.1f  %8.1f" % (solvent.name, solvent.bp, solvent.mp, solvent.fp)
    print "-"*50
    print "9999 --> not applicable"
    print

def table_bp(solvent_list, bp_limit):
    """print a table of all solvent attributes, with bp restrictions"""
    print "-"*50
    print "%-20s  %8s  %8s  %8s" % ("Name", "Bp", "Mp", "Fp")
    for solvent in solvent_list:
        if solvent.bp > bp_limit:
            print "%-20s  %8.1f  %8.1f  %8.1f" % (solvent.name, solvent.bp, solvent.mp, solvent.fp)
    print "-"*50
    print "9999 --> not applicable"
    print

# make a list of class Solvent instances
# data order = name, boiling point, melting point, flash point
# 9999 --> not applicable
solvent_list = []
solvent_list.append(Solvent("methanol", 65, -98, 11))
solvent_list.append(Solvent("ethanol", 78, -114, 8))
solvent_list.append(Solvent("butanol", 118, -89, 35))
solvent_list.append(Solvent("acetone", 56, -95, -17))
solvent_list.append(Solvent("toluene", 111, -95, 4))
solvent_list.append(Solvent("water", 100, 0, 9999))
# got the drift, add more solvents here ...


print "Show one particular item:"
print solvent_list[1].name         # …
Ene Uran 638 Posting Virtuoso

Thank you! I am still trying to digest the one liners, particularly:

x_reversed = int(str(x)[::-1])

Can anybody break that down for me so I can see the flow?

x = 12345
x_string = str(x)                   # "12345"
x_reversedstring = x_string[::-1]   # "54321"
x_reversed = int(x_reversedstring)  # 54321
Ene Uran 638 Posting Virtuoso

Any program with extension .pyw is considered a windows program, not a console program!

Ene Uran 638 Posting Virtuoso

I tried your suggestionL

for item in names:
    ch = item
    # main code
    if ch[1:6] == [1,0,0,0,0]:
        c,m,b,e,t = bbf(c,m,b,e,t)
        c=+1
    elif ch[2:6] == [0,0,0,1]:
        c,m,b,e,f = bbf(c,m,b,e,f)

but doesn't seem to add the 1 to the end totals

A little error here use c = c + 1 or c += 1 not c = +1

Ene Uran 638 Posting Virtuoso

Import is only for Python files that are written as modules. If you want to execute an external Python program use execfile("myfile.py") or execfile("myfile.pyw") .

In your program the line if denaystart == "denay" or "denay wiles": is wrong.
It should be if denaystart == "denay" or denaystart == "denay wiles": or simpler if "denay" in denaystart:

Ene Uran 638 Posting Virtuoso

Why do you want to keep two lists, a card has both a rank and a suit, they belong together to make the card. If you just shuffle the rank list, then you lost the connection with the suit list. As I mentioned before, keep your cards in a list of (rank, suit) tuples. That list will by default sort by rank (item 0 of the tuple) and keep the suit along. The same goes for the random.shuffle().

Ene Uran 638 Posting Virtuoso

We just discussed that in one of sneekula's threads:

# exercise in argument passing

def increment(*args):
    """receives tuple *args, change to list to process, then back to tuple"""
    args = list(args)
    index = 0
    for arg in args:
        args[index] += 1
        index += 1
    return tuple(args)
        

def main():
    c = d = e = 0

    # make sure you match arguments
    c, d, e = increment(c, d, e)
    print c, d, e   # 1 1 1

    c, d = increment(c, d)
    print c, d  # 2 2
    
    c, = increment(c)
    print c  # 3 


main()
Ene Uran 638 Posting Virtuoso

A few reasons to use Python classes come to mind, one is to group functions (in a class they are called methods) that belong together. This is sort of what modules do. However, classes have a leg up on modules, they have a way to inherit other classes and establish a tree search structure for attributes in any of these inherited/linked classes. You can go witout classes and OOP, but the ease of reuse of existing code makes a difference as you write larger programs.

So keep OOP in mind, introduce/immerse yourself gradually in this somewhat different world. Do it only if you are familiar with Python programming as a whole. There are some complex issues to tackle and a real beginner simply gets lost!

Ene Uran 638 Posting Virtuoso

With __cmp__() you can override, overload, customize (whatever you want to call it) the cmp() function for the class instance. There are a bunch of these babies, all starting and ending with double underlines. I think they are also called instance methods. They can do powerful things, but also can make your code a bitch to read and comprehent.

Here is one that hijacks the iterator used by a for loop:

# operator overloading with instance method __iter__()

class Reverse(object):
    """custom iterator for looping over a sequence backwards
    sort of hijacks the iterator used by the for loop
    uses __iter__(self) and next(self) to do the trick"""
    def __init__(self, data):
        self.data = data
        self.index = len(data)
    def __iter__(self):
        return self
    def next(self):
        if self.index == 0:
            raise StopIteration
        self.index = self.index - 1
        return self.data[self.index]

for c in Reverse('iterator overload'):
    print c,  # d a o l r e v o   r o t a r e t i

Note that Reverse('iterator overload') is really a class instance!

Ene Uran 638 Posting Virtuoso

Function sleep(seconds) from module time is pretty much the best. Remember seconds is a float so you can delay 0.5 seconds.

import time

print "Hello ..."
time.sleep(2.5)  # wait 2.5 seconds
print "... there!"
Ene Uran 638 Posting Virtuoso

Do all of us a favor and uses spaces for indentation!! The reason, different text editors have set different number of spaces for the tabs!!

Looks like the line that starts with global does not line up with the next line starting with print!

A Python statement block expects consistent spacing! I prefer 4 spaces. Use an editor made for Python coding and set the indentation option to "spaces only", also translate tabs to 4 spaces.

Also, please use code tags around your code, it will preserve the indents.
I will show the needed tags in reverse so they don't activate
at the end of your code add this tag [/code]
at the start of your code add tag [code]

Ene Uran 638 Posting Virtuoso

Here are two Python code smaples using the Tkinter GUI. Each example has a hint how to do the dart game:

from Tkinter import *

root = Tk()
root.title("Archery Target")

canvas = Canvas(root, width=600, height=600)
canvas.pack()

# draw five circles, largest one first, circles draw within a 
# square with given upper left corner and lower right corner coordinates
canvas.create_oval(50,50,550,550,fill='white',outline='white')
canvas.create_oval(100,100,500,500,fill='black',outline='black')
canvas.create_oval(150,150,450,450,fill='blue',outline='blue')
canvas.create_oval(200,200,400,400,fill='red',outline='red')
canvas.create_oval(250,250,350,350,fill='yellow',outline='yellow')

root.mainloop()

This tells you if the mouse has been clicked on target:

from Tkinter import *
import random

def create_rect():
    chance = random.sample(range(1, 250), 4)
    print chance  # test  eg. [72, 206, 116, 166]
    canvas.create_rectangle(chance, fill="red")

def check_rect(event):
    rect = canvas.find_overlapping(event.x, event.y, event.x, event.y)
    if rect:
        # delete old rectangle
        canvas.delete(rect)
        # create new rectangle
        create_rect()

root = Tk()
root.title("click on red")

canvas = Canvas(root, height=250, width=250, bg="yellow")
canvas.pack()

# create the starting random rectangle
create_rect()

# respond to left mouse button click
canvas.bind("<Button-1>", check_rect)

root.mainloop()
Ene Uran 638 Posting Virtuoso

Here is one way to do it, using slicing, a for loop and indexing with enumerate():

# let's say you read your file in as a string ...
str1 = """
2 h
3 s
6 d
Ace s
"""

list1 = str1.split()

print list1  # ['2', 'h', '3', 's', '6', 'd', 'Ace', 's']

suit_list = list1[1::2]
rank_list = list1[0::2]

print suit_list  # ['h', 's', 'd', 's']
print rank_list  # ['2', '3', '6', 'Ace']

# replace h with Hearts etc.
for index, suit in enumerate(suit_list):
    if suit == 'h':
        suit_list[index] = "Hearts"
    elif suit == 'c':
        suit_list[index] = "Clubs"
    elif suit == 's':
        suit_list[index] = "Spades"
    elif suit == 'd':
        suit_list[index] = "Diamonds"

print suit_list  # ['Hearts', 'Spades', 'Diamonds', 'Spades']

Please use code tags on your code to preserve the all so important indentation!!!!!!!!!!!

Ene Uran 638 Posting Virtuoso

This tiny code snippet will separate your list and make the alpha list unique. I also added the typical list sort:

raw_list = [1, 'a', 2, 'a', 3, 'v', 4, 't', 5, 'v', 9, 'c']

alpha_list = []
number_list = []
for c in raw_list:
    # make the alpha_list unique
    if alpha_list.count(c) < 1 and str(c).isalpha():
        alpha_list.append(c)
    elif str(c).isdigit():
        number_list.append(c)

# sort list in place
alpha_list.sort()

print alpha_list   # ['a', 'c', 't', 'v']
print number_list  # [1, 2, 3, 4, 5, 9]

Added php tags to make Python code color highlighted.

Ene Uran 638 Posting Virtuoso

%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;C:\Program Files\ATI Technologies\ATI Control Panel;C:\Program Files\QuickTime\QTSystem\;C:\Program Files\Common Files\Adobe\AGL;H:\Python24

or whatever version of Python you have.

Normally you don't have to do this kind of thing, when you install Python properly with the downloaded MSI installer file.