sneekula 969 Nearly a Posting Maven

To confuse variable Foo.__privatebar with Foo._Foo__privatebar would be a hard thing to do. As you can see, Python uses name mangling to protect a private variable.

sneekula 969 Nearly a Posting Maven

You can use a dialog window in conjunction with a main window. Here is a wxPython example:

# a wxPython general frame with a dialog window
# the dialog shows full size even it the frame is minimized

import wx
import wx.calendar as cal

class MyCalendar(wx.Dialog):
    """create a simple dialog window with a calendar display"""
    def __init__(self, parent, mytitle):
        wx.Dialog.__init__(self, parent, wx.ID_ANY, mytitle)
        # use a box sizer to position controls vertically
        vbox = wx.BoxSizer(wx.VERTICAL)

        # wx.DateTime_Now() sets calendar to current date
        self.calendar = cal.CalendarCtrl(self, wx.ID_ANY, 
            wx.DateTime_Now())
        vbox.Add(self.calendar, 0, wx.EXPAND|wx.ALL, border=20)
        # click on day
        self.calendar.Bind(cal.EVT_CALENDAR_DAY, 
            self.onCalSelected)
        # change month
        self.calendar.Bind(cal.EVT_CALENDAR_MONTH, 
            self.onCalSelected)
        # change year
        self.calendar.Bind(cal.EVT_CALENDAR_YEAR, 
            self.onCalSelected)

        self.label = wx.StaticText(self, -1, 'click on a day')
        vbox.Add(self.label, 0, wx.EXPAND|wx.ALL, border=20)

        self.button = wx.Button(self, -1, 'Exit')
        vbox.Add(self.button, 0, wx.ALL|wx.ALIGN_CENTER, border=20)
        self.button.Bind(wx.EVT_BUTTON, self.onQuit)

        self.SetSizerAndFit(vbox)
        self.Show(True)
        self.Centre()

    def onCalSelected(self, event):
        #date = event.GetDate()
        date = self.calendar.GetDate()
        day = date.GetDay()
        # for some strange reason month starts with zero
        month = date.GetMonth() + 1
        # year is yyyy format
        year = date.GetYear()
        s1 = "%02d/%02d/%d \n" % (month, day, year)
        # or just take a slice of the first 8 characters
        # to show mm/dd/yy
        s2 = str(date)[0:8]
        self.label.SetLabel(s1 + s2)

    def onQuit(self, event):
        self.Destroy()


class MyFrame(wx.Frame):
    """create a frame as the main window"""
    def __init__(self, parent, mytitle, mysize):
        # use wx.ID_ANY or -1 as ID
        wx.Frame.__init__(self, parent, -1, mytitle, 
            pos=(10, 10), size=mysize)
        self.SetBackgroundColour("yellow")
        
        # this dialog will stay up even if MyFrame is minimzed
        mc = MyCalendar(None, 'dialog window with calendar')

        #
        # …
sneekula 969 Nearly a Posting Maven

Generally you would save the following three code files in the same directory:
class Tank as tank.py
class Grid as grid.py
your main code as tank_game.py
then run tank_game

Note that filenames for modules tank and grid are case sensitive!

sneekula 969 Nearly a Posting Maven

Got a goofy message and ended up with a duplicate, sorry folks!

sneekula 969 Nearly a Posting Maven

Lardmeister suggested something much simpler, something like this:

# using the Tkinter canvas to
# draw a line from coordinates x1,y1 to x2,y2
# create_line(x1, y1, x2, y2, width=1, fill="black")

try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

root = tk.Tk()
root.title("drawing lines")

# create the drawing canvas
canvas = tk.Canvas(root, width=450, height=450, bg='white')
canvas.pack()

# draw horizontal lines
x1 = 0
x2 = 450
for k in range(0, 500, 50):
    y1 = k
    y2 = k
    canvas.create_line(x1, y1, x2, y2)

# draw vertical lines
y1 = 0
y2 = 450
for k in range(0, 500, 50):
    x1 = k
    x2 = k
    canvas.create_line(x1, y1, x2, y2)

root.mainloop()
sneekula 969 Nearly a Posting Maven

The Python world is going through a transition. I do more and more work with Python 3.1.2, but still use Python 2.6.5 for some stuff.

Most folks are waiting for wxPython and PIL to make the transition. In the mean time I am using the PyQT GUI toolkit and the newer version of Tkinter that ships with Python31

sneekula 969 Nearly a Posting Maven

If it's a bug with Windows 7, maybe you have to wait until they release Windows 7.1

sneekula 969 Nearly a Posting Maven

Sometimes you want a button that toggles between two different actions:

# wxToggleButton2.py
# testing wxPython's
# wx.ToggleButton(parent, id, label, pos, size, style)
# snee

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, mysize):
        wx.Frame.__init__(self, parent, -1, mytitle, size=mysize)
        # use panel so position of button behaves
        panel = wx.Panel(self, wx.ID_ANY)

        self.tbtn = wx.ToggleButton(panel, id=-1, label='Toggle Off',
            pos=(20, 25))
        # bind mouse click event to an action
        self.tbtn.Bind(wx.EVT_TOGGLEBUTTON, self.onToggle)

    def onToggle(self, event):
        # self.tbtn.GetValue() toggles between True or False
        if self.tbtn.GetValue():
            self.tbtn.SetLabel('Toggle On')
        else:
            self.tbtn.SetLabel('Toggle Off')


app = wx.App(0)
MyFrame(None, 'wx.ToggleButton test', (300, 100)).Show()
app.MainLoop()
sneekula 969 Nearly a Posting Maven

One way to do this is using a shifted alphabet, here is a simple example:

# rotation_crypt1.py
# use the index in the regular alphabet and apply it to a
# shifted alphabet (all upper case letters for simplicity)

import string

alpha = string.ascii_uppercase

shift = 3
# shift the alphabet with slicing
shift_alpha = alpha[shift:] + alpha[:shift]

# testing
letter = 'X'
coded = shift_alpha[alpha.find(letter)]
print "%s shifted %d gives letter %s" % (letter, shift, coded)

letter = 'Z'
coded = shift_alpha[alpha.find(letter)]
print "%s shifted %d gives letter %s" % (letter, shift, coded)

letter = 'A'
coded = shift_alpha[alpha.find(letter)]
print "%s shifted %d gives letter %s" % (letter, shift, coded)

"""my test result -->
X shifted 3 gives letter A
Z shifted 3 gives letter C
A shifted 3 gives letter D
"""
sneekula 969 Nearly a Posting Maven

It will make future wars so much easier! Send in your robots, make a mess out of that country and leave. Any politicians dream!

The only defense against such an attack is to have nuclear weapons and a good delivery system, retaliatory weapons produced and stored in secretive deep underground systems.

sneekula 969 Nearly a Posting Maven

We have established client-server connection in python using send() and recv() . Now we need to send a shell command(eg: ls) from 1st system to 2nd; execute it in 2nd and copy back the result to the 1st. You people out there, please suggest something...

Hijacking an old thrtead is not the way to go. If you really want help, start a new thread with a good descriptive title.

sneekula 969 Nearly a Posting Maven

Actually quite simple using button["text"]:

# explore Tkinter button as simple toggle

import Tkinter as tk  # for Python3 use import tkinter as tk

def toggle_text():
    """toggle button text between Hi and Goodbye"""
    if button["text"] == "Hi":
        # switch to Goodbye
        button["text"] = "Goodbye"
    else:
        # reset to Hi
        button["text"] = "Hi"


root = tk.Tk()
root.title("Click the Button")

button = tk.Button( text="Hi", width=12, command=toggle_text)
button.pack(padx=100, pady=10)

root.mainloop()
vegaseat commented: very good example +10
sneekula 969 Nearly a Posting Maven

You need to add a space between words:

def small():
    words = 'hello, this is my test'
    forbidden = 'l, h, e'
    a = ''
    for word in words.split():
        for letter in word:
            if letter in forbidden:
                letter = ''
            else:
                a = a + letter
        # add a space between words
        a = a + ' '

    print a

small()
sneekula 969 Nearly a Posting Maven

Has anybody seen that 2012 movie?

sneekula 969 Nearly a Posting Maven

I have to create a new password every month, so it is the name of my first girl friend plus the number of the month.

sneekula 969 Nearly a Posting Maven

You might have to preprocess the file first.

sneekula 969 Nearly a Posting Maven

Green letters on a black background are really hard to read.

sneekula 969 Nearly a Posting Maven

Could you mark this as solved?

sneekula 969 Nearly a Posting Maven

You are close:

import string

def punc(s):
    txt = open(s, 'r').read()
    print(txt)  # for test only
    for punct in string.punctuation:
        if punct in txt:
            # update txt
            txt = txt.replace(punct, "")
    return txt

# test your potential function.py module
if __name__ == '__main__':
    # pick a text file you have in the working folder
    fname = "name.txt"
    new_text = punc(fname)
    # show the result return from the function punc()
    print(new_text)
    
"""my test display -->
Frank, Miller: III
Dr. August Jarr
Mrs. Lola Meyer-Lipstick


Frank Miller III
Dr August Jarr
Mrs Lola MeyerLipstick
"""
sneekula 969 Nearly a Posting Maven

The module numpy is your friend here:

# create matrix with arange().reshape()
# perform add and multiply matrix operations
# module numpy (numeric python extensions, high speed)
# free from: http://sourceforge.net/projects/numpy

import numpy as np

# create 2 matrices using
# arange([start,] stop[, step,], dtype=None) and
# reshape((row, col)) use (row, col) tuple
# list created by arange() has to fit 3x3 matrix
mx1 = np.arange(11, 20).reshape((3, 3))
mx2 = np.arange(31, 40).reshape((3, 3))

# add the 2 matrices
mx3 = np.add(mx1, mx2)
# multiply the 2 matrices
mx4 = np.multiply(mx1, mx2)

# show the result
print('mx1 =')
print(mx1)
print('-'*15)
print('mx2 =')
print(mx2)
print('-'*15)
print('mx1 + mx2 =')
print(mx3)
print('-'*15)
print('mx1 * mx2 =')
print(mx4)

"""my result -->
mx1 =
[[11 12 13]
 [14 15 16]
 [17 18 19]]
---------------
mx2 =
[[31 32 33]
 [34 35 36]
 [37 38 39]]
---------------
mx1 + mx2 =
[[42 44 46]
 [48 50 52]
 [54 56 58]]
---------------
mx1 * mx2 =
[[341 384 429]
 [476 525 576]
 [629 684 741]]
"""
sneekula 969 Nearly a Posting Maven

It looks like badboy00z is correct. The last result is really a permutation with a sample size of 2.

sneekula 969 Nearly a Posting Maven

I think badboy00z is correct. You can use module itertools to show it:

# combinations and permutations using Python3 itertools

import itertools

iterable = [1, 2, 3]
# sample_size < len(iterable)
sample_size = 2
combi_list = list(itertools.combinations(iterable, sample_size))
print(combi_list)

print( '-'*50 )

sample_size = 2
combi_list2 = \
list(itertools.combinations_with_replacement(iterable, sample_size))
print(combi_list2)

print( '-'*50 )

perm_list = list(itertools.permutations(iterable))
print(perm_list)

print( '-'*50 )

perm_list2 = list(itertools.permutations(iterable, 2))
print(perm_list2)

""" my result -->
[(1, 2), (1, 3), (2, 3)]
--------------------------------------------------
[(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]
--------------------------------------------------
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
--------------------------------------------------
[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
"""
sneekula 969 Nearly a Posting Maven

I modified the code in the previous post to join two images into one:

# use a drawing bitmap and wx.MemoryDC to create a canvas you can
# draw on and optionally save the drawing to an image file
# here we draw two images side by side and save the combined image
# vegaseat code modified by sneek

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, title, mysize):
        wx.Frame.__init__(self, parent, -1, title, size=mysize)
        # create a bitmp for display and optional saving
        self.show_bmp = wx.StaticBitmap(self)
        # get the width and height for the blank bitmap
        w, h = self.GetClientSize()
        # create a blank bitmap as a drawing background
        # should be large enough to fit the 2 images side by side
        draw_bmp = wx.EmptyBitmap(w, h)

        # put a canvas on top of draw_bmp
        canvas = wx.MemoryDC(draw_bmp)

        # fill the canvas white
        canvas.SetBrush(wx.Brush('white'))
        canvas.Clear()

        # pick 2 image files you have in the working folder
        # (can be a .jpg, .png, .gif, .bmp image files)
        # note that filenames are case sensitive in Linux
        image1 = wx.Bitmap("Duck_right.jpg")
        image2 = wx.Bitmap("Duck_left.jpg")

        # draw the 2 images side by side
        canvas.DrawBitmap(image1, 0, 0)
        canvas.DrawBitmap(image2, w/2, 0)

        # this also shows your drawing
        self.show_bmp.SetBitmap(draw_bmp)

        # get the image object
        myimage = self.show_bmp.GetBitmap()
        # save it to a file
        myimage.SaveFile("joined_pic1.jpg", wx.BITMAP_TYPE_JPEG)


app = wx.App(0)
# make width w large enough to have the 2 images next to each other
w = 610
# make height h large enough to fit the max height of …
sneekula 969 Nearly a Posting Maven

I modified the code in the previous post to join two images into one:

# use a drawing bitmap and wx.MemoryDC to create a canvas you can
# draw on and optionally save the drawing to an image file
# here we draw two images side by side and save the combined image
# vegaseat code modified by sneek

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, title, mysize):
        wx.Frame.__init__(self, parent, -1, title, size=mysize)
        # create a bitmp for display and optional saving
        self.show_bmp = wx.StaticBitmap(self)
        # get the width and height for the blank bitmap
        w, h = self.GetClientSize()
        # create a blank bitmap as a drawing background
        # should be large enough to fit the 2 images side by side
        draw_bmp = wx.EmptyBitmap(w, h)

        # put a canvas on top of draw_bmp
        canvas = wx.MemoryDC(draw_bmp)

        # fill the canvas white
        canvas.SetBrush(wx.Brush('white'))
        canvas.Clear()

        # pick 2 image files you have in the working folder
        # (can be a .jpg, .png, .gif, .bmp image files)
        # note that filenames are case sensitive in Linux
        image1 = wx.Bitmap("Duck_right.jpg")
        image2 = wx.Bitmap("Duck_left.jpg")

        # draw the 2 images side by side
        canvas.DrawBitmap(image1, 0, 0)
        canvas.DrawBitmap(image2, w/2, 0)

        # this also shows your drawing
        self.show_bmp.SetBitmap(draw_bmp)

        # get the image object
        myimage = self.show_bmp.GetBitmap()
        # save it to a file
        myimage.SaveFile("joined_pic1.jpg", wx.BITMAP_TYPE_JPEG)


app = wx.App(0)
# make width w large enough to have the 2 images next to each other
w = 610
# make height h large enough to fit the max height of …
sneekula 969 Nearly a Posting Maven

Call for update() as shown below:

from tkinter import *

class fb( Frame ):
    def fastbuttons( self ):
        b = Button(self)
        b.grid()
        self.update()
        print( b.winfo_ismapped() )

    def __init__( self, master=None ):
        Frame.__init__( self, master )
        self.grid( sticky='nsew' )
        self.button = Button( self, text='Start', command=self.fastbuttons )
        self.button.grid()
        
if __name__ == '__main__':
    root = Tk()
    app = fb( master=root )
    app.mainloop()
sneekula 969 Nearly a Posting Maven

If there is no space in the rank or name you can do it this simple way:

mydata = """\
<Ranking: AA (John)>
<Ranking: CA (Peter)>
<Ranking: TA-A (Samantha)>
"""

rank_list = []
for line in mydata.split('\n'):
    print line, line.split()  # testing
    if line:
        rank_list.append(line.split()[1])

print
print rank_list
    
"""my result -->
<Ranking: AA (John)> ['<Ranking:', 'AA', '(John)>']
<Ranking: CA (Peter)> ['<Ranking:', 'CA', '(Peter)>']
<Ranking: TA-A (Samantha)> ['<Ranking:', 'TA-A', '(Samantha)>']
 []

['AA', 'CA', 'TA-A']
"""
sneekula 969 Nearly a Posting Maven

Well, in Python just about anything is an object not just the typical OOP stuff. I assume that your instructor forgot about that and actualy means creating a class Student where each instance is a particular student.

sneekula 969 Nearly a Posting Maven

snippsat.. Everybody is here with a question to be answered.. Google gives result for everything.. Then why people are answering and wasting their time??? Just can give the link to www.google.com..
I think you might not(matured) know the concept of a forum even though you are a member:S.. It is created for like minded people to share their ideas of what they know.. You know there is always a difference between what machine(google) gives and a man can give to you out of their experience(Every human Knows. But you????).
I asked for some materials to refer on PyQt.. I've already googled around and got some materials(i've mentioned that too in my post. open your eyes and see that or put on specs). I've asked here coz. good people like vegaseat,griboulis etc., have got first hand experience in GUI programming and they might give some ideas,suggestions,useful links and in what way i've to proceed(from so and so book to so and so book) as a beginner to become a good programmer(out of their handful of experience)..
If u can't answer for the question please just stop discouraging others who ask questions(especially beginners). I posted this question expecting reply from guys who got positive attitude of assisting and motivating a beginner rather than getting reply from people like you...

Maybe because this is a jobb for goolge

By the by nobody knows any search engine in the name goolge:D..

Let's be somewhat pleasant about this. If you search …

sneekula 969 Nearly a Posting Maven
sneekula 969 Nearly a Posting Maven

Sorry, I am using Python 3.1.1 and graphics.py does not work with Python3.

This little module has been updated to work with Python2 and Python3 recently, look at the new beta version at:
http://mcsp.wartburg.edu/zelle/python/

sneekula 969 Nearly a Posting Maven

This should give you an idea how to split the window into three parts. One could add to the left side score, the other to the right side score, and the third is for a click to exit.

#

from graphics import *

def main():
    win = GraphWin("My Score", 120, 100)
    rect_left = Rectangle(Point(0, 0), Point(50,100))
    rect_left.setFill('red')
    rect_left.draw(win)
    rect_right = Rectangle(Point(50, 0), Point(100,100))
    rect_right.setFill('green')
    rect_right.draw(win)
    while True:
        # get the x position of the mouse click
        click_posx = win.getMouse().getX()
        print( click_posx )  # test
        if click_posx < 51:
            print ( "left rect has been clicked")
        elif click_posx < 101:
            print ( "right rect has been clicked")
        else:
            break
    win.close()

main()
sneekula 969 Nearly a Posting Maven

The title is somewhat misleading. You want to add 2.

sneekula 969 Nearly a Posting Maven

Okay, this might even be mildly better:

import string
a = list(string.ascii_lowercase + "!@#$%^&*()-+={}|\/?><,.'") + range(1, 10)

print a

For Python3 change to list(range(1, 10)). Oh, the joys of Python! :)

sneekula 969 Nearly a Posting Maven

Just testing wxPython's wx.TextCtrl widget used as an edit field for input and output of text based data:

# testing wxPython's
# wx.TextCtrl(parent, id, value, pos, size, style)
# a widget used for text data input or output
# note:
# style=wx.TE_PROCESS_ENTER is needed for Linux to
# respond to the enter key event!!!
# snee

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, mysize):
        wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize)
        self.SetBackgroundColour("yellow")

        s = "Enter name below:"
        edit_label = wx.StaticText(self, wx.ID_ANY, s)
        # create a single line edit input area
        self.edit = wx.TextCtrl(self, wx.ID_ANY, value="",
            style=wx.TE_PROCESS_ENTER)
        # put the cursor in edit
        self.edit.SetFocus()
        # respond to enter key when focus is on edit
        self.edit.Bind(wx.EVT_TEXT_ENTER, self.onEnter)

        # create a scrolled multiline text output area
        self.text_out = wx.TextCtrl(self, wx.ID_ANY, value="",
            style=wx.TE_MULTILINE|wx.HSCROLL|wx.TE_READONLY)
        
        # use a box sizer for vertical widget layout
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(edit_label, 0, wx.LEFT|wx.TOP|wx.EXPAND, border=10)
        sizer.Add(self.edit, 0, wx.ALL|wx.EXPAND, border=10)
        sizer.Add(self.text_out, 2, wx.ALL|wx.EXPAND, border=10)
        self.SetSizer(sizer)

    def onEnter(self, event):
        """the Enter key has been pressed, do something"""
        # GetValue() gives a string
        name = self.edit.GetValue()
        s = "You entered the name: " + name + '\n'
        # text output, either method works
        #self.text_out.AppendText(s)
        self.text_out.WriteText(s)
        # clear edit input space
        self.edit.Clear()


app = wx.App(0)
# create a MyFrame instance and show the frame
MyFrame(None, 'testing wx.TextCtrl()', (300, 480)).Show()
app.MainLoop()

Notice the special requirement for Linux users.

Gribouillis commented: Useful test. Thanks also for linux users :) +2
sneekula 969 Nearly a Posting Maven

Also the OP didn't want a zero in the digits part. :)

sneekula 969 Nearly a Posting Maven

It's always good to use a few test prints:

import operator

OPERATORS = {
        '+': operator.add,
        '-': operator.sub,
        '*': operator.mul,
        '/': operator.div,
        }

class Stack(object):
    "Creates a stack to enter numbers or operators into"

    def __init__(self):
        self.storage = [0,0,0,0]
        self.sptn = -1

    def push(self, item):
        self.sptn = self.sptn + 1
        self.storage[self.sptn] = item
        
    def pop(self):
        self.sptn = self.sptn -1
        
    def top(self):
        return self.storage[self.sptn]

    def __rep__(self):
        return self.storage[:self.sptn + 1]
    

def get_input():

    equation = raw_input("Enter the equation in reverse polish notation: ")
    return equation

def evaluate_rpn(equation):
    
    s = Stack()

    try:
        for item in equation.split():
            try:
                result = float(item)
                s.push(result)
            except ValueError:
                x = s.pop()
                y = s.pop()
                print x, y   # test --> None None  problem is here!!!
                result = OPERATORS[item](x, y)
                s.push(result)
        result = s.top()
        print result  # test
        return result
            
    except IndexError:
        print "Please input at least two numbers before entering an operator."

def main():
    # use for testing
    equation = '2 3 +'
    #equation = get_input()
    answer = evaluate_rpn(equation)
    print answer

main()

The problem is in your class Stack. If you use a Python Queue as a stack it works fine:

import operator
import Queue

OPERATORS = {
        '+': operator.add,
        '-': operator.sub,
        '*': operator.mul,
        '/': operator.div,
        }

def get_input():

    equation = raw_input("Enter the equation in reverse polish notation: ")
    return equation

def evaluate_rpn(equation):
    
    # use a Python queue for a stack
    s = Queue.Queue(-1)

    try:
        for item in equation.split():
            try:
                result = float(item)
                s.put(result)
            except ValueError:
                x = s.get()
                y = s.get()
                #print x, y   # …
sneekula 969 Nearly a Posting Maven

Well, you could do something like this:

# File_lister2.py
# create a list of all the files and sizes in a given direcory
# and optionally any of its subdirectories (Python2 & Python3)
# snee

import os

def file_lister(directory, subs=False):
    """
    returns a list of (size, full_name) tuples of all files
    in a given directory
    if subs=True also any of its subdirectories
    """
    mylist = []
    for fname in os.listdir(directory):
        # add directory to filename for a full pathname
        full_name = os.path.join(directory, fname)
        # size in kb
        size = int(os.path.getsize(full_name)//1024) + 1
        if not os.path.isdir(full_name):
            # append a (size, full_name) tuple
            mylist.append((size, full_name))
        elif subs==True:
            # optionally recurse into subdirs
            file_lister(full_name)
    return mylist

#dir_name = r"C:\Python31\Tools"  # Windows
dir_name = "/home/dell/Downloads"  # Linux
file_list = file_lister(dir_name)

# show the list sorted by size
for file_info in sorted(file_list, reverse=True):
    print(file_info)

print('-'*66)

print( "The largest file is: \n%s (%skb)" % \
    (max(file_list)[1], max(file_list)[0]) )

"""a typical partial output -->
(24144, '/home/dell/Downloads/ActivePython-2.6.2.2-linux-x86.tar.gz')
(23320, '/home/dell/Downloads/ActivePython-3.1.0.1-linux-x86.tar.gz')
(9288, '/home/dell/Downloads/Python-3.1.tar.bz2')
...
...
------------------------------------------------------------------
The largest file is:
/home/dell/Downloads/ActivePython-2.6.2.2-linux-x86.tar.gz (24144kb)
"""
sneekula 969 Nearly a Posting Maven

You could do:

for c in "Hello World":
    print c ,

In Python2 the comma puts in a space and keeps it on the same line.

sneekula 969 Nearly a Posting Maven

How do you know when to use a function by wraping the content between parentheses "function(x) or through dot notation x.function()
? thanks.

You are somewhat confused about functions.

sneekula 969 Nearly a Posting Maven

I made an attempt on user friendly data entry with just such a simple temperature converter program, see:
http://www.daniweb.com/forums/showthread.php?p=992595#post992595

sneekula 969 Nearly a Posting Maven

Looks like one of the 638 web pages is not available. You should use a try/except trap for this case.

sneekula 969 Nearly a Posting Maven

And don't forget to use self to turn those functions into methods for the instance, like
def moveup(self):

sneekula 969 Nearly a Posting Maven

Something like that might do. I avoided the use of float() until the end to keep time-stamp and port info from turning into floats:

raw_data = """\
501 	 0 	 0.932 0.933 0.931 0.931 0.929 0.933 0.93 0.928
501 	 1 	 0.974 0.98 0.978 0.976 0.974 0.974
501 	 2 	 0.953 0.949 0.944 0.951 0.942 0.942 0.942 0.948
501 	 3 	 0.933 0.934 0.934 0.935 0.931 0.933 0.932 0.934
501 	 4 	 0.939 0.934 0.934 0.934 0.937 0.932 0.938
501 	 5 	 0.944 0.942 0.942 0.943 0.939 0.95 0.942 0.948
501 	 6 	 0.974 0.976 0.974 0.971 0.97 0.967 0.971 0.974
501 	 7 	 0.986 0.984 0.984 0.986 0.986 0.984
502 	 0 	 0.927 0.933 0.931 0.931 0.929 0.933 0.93 0.928
502 	 1 	 0.974 0.98 0.978 0.976 0.973 0.971 0.974
502 	 2 	 0.953 0.949 0.951 0.942 0.942 0.942 0.948
502 	 3 	 0.933 0.934 0.934 0.935 0.931 0.933 0.932 0.931
502 	 4 	 0.939 0.934 0.934 0.932 0.937 0.932 0.938
502 	 5 	 0.944 0.942 0.942 0.943 0.939 0.95 0.95 0.948
502 	 6 	 0.974 0.974 0.974 0.971 0.97 0.967 0.971 0.974
502 	 7 	 0.986 0.984 0.984 0.986 0.984 0.986"""

fname = "my_data.dat"
# write the test file
fout = open(fname, "w")
fout.write(raw_data)
fout.close()

# read the test file
fin = open(fname, "r")
data_hol = []
for line_hol in fin:
    line_hol = [x for x in line_hol.split() ]
    data_hol.append(tuple(line_hol))

my_datalist = []
for line in data_hol:
    #print(line[1], line[2:])  # test
    port = line[1]
    # now you can use float()
    data_sum = sum([float(x) for x in line[2:]])
    my_datalist.append((port, data_sum))

# test the list of (port, data_sum) tuples
for tup in my_datalist:
    print(tup)

"""my output -->
('0', 7.4470000000000001)
('1', 5.8559999999999999)
('2', 7.5709999999999997)
('3', 7.4660000000000002)
('4', 6.548)
('5', 7.5500000000000007)
('6', 7.7770000000000001)
('7', 5.9099999999999993)
('0', 7.4420000000000002)
('1', 6.8260000000000005)
('2', 6.6270000000000007)
('3', 7.4630000000000001)
('4', 6.5460000000000003)
('5', 7.5579999999999998)
('6', 7.7749999999999995)
('7', 5.9099999999999993)
"""
sneekula 969 Nearly a Posting Maven

With wxPython code you can give py2exe an XML based manifest to force it to adopt the Windows XP theme.

sneekula 969 Nearly a Posting Maven

To make more sense you should have written your class this way:

class Animal:
    def __init__(self, legs):
        self.legs = legs
        
cow = Animal(4)
chicken = Animal(2)
octopus = Animal(8)
# Bob is a pet chicken with 1 leg missing
bob = Animal(1)

print( octopus.legs )  # 8
print( chicken.legs )  # 2
sneekula 969 Nearly a Posting Maven

Like gerard4143 says, you have to make the print statement part of the function, since Tf is local to the function. The other option would be to return Tf to make it available outside the function:

#Convert C to F
def Tc_to_Tf ():
    Tc = input ("What is the Celsius Temperature ?   " )
    Tf = 9.0/5.0 * Tc + 32
    return Tf

Tf = Tc_to_Tf ()
print 'The temperature is ', Tf, ' Degrees Fahrenheit'

Please use the [code=python] and [/code] tag pair to enclose your python code.

sneekula 969 Nearly a Posting Maven

Just a quick example on how to use the wx.grid.PyGridTableBase with wxPython's wx.grid.Grid. Provides a simple way to create, load and use a spreadsheet like grid:

# exploring wxPython's wx.grid.Grid()
# load grid via a '(row, col): value' dictionary and a table class
# that inherits and applies wx.grid.PyGridTableBase
# snee

import wx
import wx.grid

class MyFrame(wx.Frame):
    def __init__(self, header_list, data_dict):
        wx.Frame.__init__(self, None, wx.ID_ANY,
            title="ACME Inc. Staff Stats", size=(510,200))

        self.grid = wx.grid.Grid(self)
        self.grid.SetRowLabelSize(30)     # sets leading row width
        self.grid.SetDefaultRowSize(20)   # sets all row height
        self.grid.SetColLabelSize(30)     # sets leading col height
        self.grid.SetDefaultColSize(80)  # sets all col width

        # select the cell with a mouse left click
        self.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.cell_click)

        # the table takes care of all the grid stuff
        table = MyTable(header_list, data_dict)
        self.grid.SetTable(table, True)
        
        # optional, calculate rows of data needed for fun stats
        self.rows = max(data_dict.keys())[0] + 1

    def cell_click(self, event):
        """cell has been left clicked"""
        row = event.GetRow()
        col = event.GetCol()
        # move the grid's cursor to frame the cell
        self.grid.SetGridCursor(row, col)
        # you can do some fun stats with the numbers
        num = []
        if col > 0:
            #num = []
            for nrow in range(self.rows):
                num.append(float(self.grid.GetCellValue(nrow, col)))
        val = self.grid.GetCellValue(row, col)
        if num:
            sf = "r%dc%d %s  max=%.1f min=%.1f avg=%.1f" % \
               (row, col, val, max(num), min(num), sum(num)/nrow)
        else:
            sf = "r%dc%d %s" % (row, col, val)
        self.SetTitle(sf)


class MyTable(wx.grid.PyGridTableBase):
    def __init__(self, header_list, data_dict):
        wx.grid.PyGridTableBase.__init__(self)
        self.data = data_dict
        # calculate rows and cols needed to fit the data
        self.rows = max(data_dict.keys())[0] + 1
        self.cols = max(data_dict.keys())[1] + …
sneekula 969 Nearly a Posting Maven

Gribouillis is right, global constants have their place, but like he mentioned, make them stick out. One time when all upper case is appropriate.

sneekula 969 Nearly a Posting Maven

Some simple changes will do:

comments = []
inComment = False
for i, line in enumerate(open(filename)):
    if "//***" in line:
        inComment = not inComment
    elif inComment:  # changed to elif
        print( "comment found at line %d" %i )  # test
        # optionally strip trailing '\n' char
        line = line.rstrip()
        comments.append((i, line)) 

print( comments )

for comment in comments:
    print( comment[1] )
sneekula 969 Nearly a Posting Maven

If you are new to Python, I wouldn't 'putz' around with old Python2. There are simply too many things that Python3 has to offer. Otherwise, after a few years you will be stuck with old Python2 code that does not easily convert to Python3. The little 2to3.py utility program only handles simple stuff.