jlm699 320 Veteran Poster

You've got to post the code where principal comes from. It would seem that principal is a list instead of a number... here look at this example of generating that error:

>>> [ 1,2,3,4] * 0.02
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'float'
>>>
jlm699 320 Veteran Poster

When using code tags, you should use [code=python] instead of [code=syntax].

In your code, you do a few things incorrectly. First of all, you shouldn't define functions within other functions. So move those back out a level and take them out of main() . Either that or don't use functions, since neither of those functions actually perform anything at all.

The main problem here is that your principal_data function does not return any values. This means that on the line that reads principal = principal_data , principal is getting assigned a value of None , which is why you're experiencing your fail.

jlm699 320 Veteran Poster

Thanks to both replies, I just need help from more experienced python users as of where and how to find education materials to help me writing the codes, I am not expecting you guys to do it for me.

Thanks again

Here

If you spent five seconds googling any one of those search methods you'd already have pseudo-code for each and every one.

jlm699 320 Veteran Poster

You'll have to write those sort algorithms yourself. Or search google. To sort a list in Python:

my_list = [1,5,2,8,3,4,7,6]
my_list.sort()
jlm699 320 Veteran Poster
height = principal * 0.02
TypeError: unsupported operand type(s) for *: 'NoneType' and 'float'

0.02 is your float and * is your operand. That only leaves principal to be your NoneType. At another point, you are setting principal equal to the return value of a function that doesn't return anything. That's your problem.

Slight correction to your explanation... '*' is your operator and 0.02 and principal are your operands, of type float and NoneType respectively. The remainder I agree with.

jlm699 320 Veteran Poster

thanks, that's a good start for now, but eventually it would be nice to do

--files *.txt --Size 4.2 --Duration 5

Dave

I'm not entirely clear on what you're trying to do, but if you want to get all files in a directory that are *.txt you can use the glob module:

>>> import os,glob
>>> os.chdir('C:\\Documents and Settings\\Administrator\\Desktop')
>>> my_files = glob.glob('*.py')
>>> my_files
['batt.py', 'newt_root.py', 'perf_num.py', 'template.py']
>>>

EDIT: I'm sure that you're not actually restricted to a single directory since you can probably use wild cards for the directory too. I think glob just expands exactly the way that Unix path expansion works.

HTH

jlm699 320 Veteran Poster

Also, how do you handle required options? I saw a lot of threads about a philosophical debate of if options can be required, but no information on how to actually use them.

Dave

This is from the optparse doc:

required option
an option that must be supplied on the command-line; note that the phrase “required option” is self-contradictory in English. optparse doesn’t prevent you from implementing required options, but doesn’t give you much help at it either. See examples/required_1.py and examples/required_2.py in the optparse source distribution for two ways to implement required options with optparse.

jlm699 320 Veteran Poster

right jlm, except the whole point of the loop is testing different numbers to see if they're perfect... like testing 1, then a +=1, or 2, then 3, etc.

My first advice to FIX your code, was to clear the contents of b when you move onto a new a since it won't have the same factors.

I understand the point of the loop, as I have your program working on my system. Do you have it working yet? Didn't think so. Maybe you misunderstood what I was suggesting. I said to move it outside of the for loop, not the while loop.

You're testing different numbers using a , which is incremented at the end of the while loop. The for loop is used to get all the factors of a and append them to b . So I suggested moving the sum(b) and subsequent perfect number check to after the for loop to save processing time.

As it stands now, every time you find a factor of a you append it to b and check to see if the contents of the array are twice the original number even though you haven't completed finding all factors.

EDIT: Oh, and when doing a comparison you have to use == , not = , as the single equals sign is for assignment.

jlm699 320 Veteran Poster

Actually the more I try to get this code working the more I realize that you might be confusing your variable names.... you're iterating over guess in your for loop, but then also using it afterwards to say what the final guess was... which will always be the last value of the for loops iteration. So on a range(1,15) call, guess will start at guess = 1 , then on the next iteration it'll be guess = 2 , then guess = 3 , and so on until it becomes guess = 14 to end the loop.

Also, you never convert the "number of times" that the user enters to a number, you're leaving it as a string... try to wrap that input with a call to int() I also should re-state that you need to re-think the way you're casting your floats... instead of the following:

for guess in range (1, i):
        float((float(x / guess) + guess) / 2)

    answer = float(math.sqrt(x))
    check = abs(float(guess - answer))

You should have these lines:

for some_value in range (1, i):
        guess = ((x / guess) + guess) / 2

    answer = math.sqrt(x)
    check = abs(guess - answer)

And one last thing: You should use raw_input instead of input (if this is a 2.X version of Python). Check what happens if the user enters 4 * 5 into an input() prompt and then think about what would happen if they entered any malicious code....

jlm699 320 Veteran Poster

So, apparently the for statement makes my guesses worse. Thanks in advance

Look at what range(15) and range(1,15) produce:

>>> range(15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> range(1,15)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>>

You're leaving off the number 15 (if that's what you were shooting for).

Now just out of curiosity, what is the purpose behind your for loop? As it stands, it isn't doing anything. It's simply doing some arbitrary calculations but never updating any values or storing any results.

Also, what's with the multiple float casting? Only one operand needs to be a float in order to invoke true division in Python < 3.0 ... that means you could simply put guess = float(guess) before the calculation line and remove all float casting and achieve the same output. **EDIT** Actually, I just checked and it's actually waaay more accurate to remove that float casting and simply use guess = float(guess) followed by result = ((x / guess) + guess) / 2 .

jlm699 320 Veteran Poster

Here, I don't think you understood what I was saying. I updated your code to slightly reflect the way that I would write it...

import random, textwrap

cho = '\t1.Attack'
att = 'You attack!'

def get_ran():
    random.seed()
    return random.randrange(10)

def bat_sta( hp ):
    print cho
    des = int(raw_input(' \tPick! '))
    if des == 1:
        ran = get_ran()
        cran = get_ran()
        deth = get_ran()
        #print 'Ran:',ran,'Cran:',cran,'Deth:',deth
        print textwrap.fill(att)
        if (ran == cran and ran > 0):
            print 'Critical hit! %i points of damage!' % (cran * 2)
            hp -= ran * 2
        elif ran == 1:
            print 'Your attack does 1 point of damage!'
            hp -= ran
        elif ran > 1:
            print 'Your attack does %s points of damage!' % ran
            hp -= ran
        elif ran == 0:
            print 'Your attack didn\'t do anything!'
        print 'Enemies hp: %i' % hp
        if hp == 0:#(ran == cran and cran == deth):
            print 'You killed it!'
    
    return hp


if __name__ == '__main__':
    hp = 100
    while True:
        hp = bat_sta(hp)

Please ask about anything you don't understand

jlm699 320 Veteran Poster

I suggest verifying your login method line-by-line in the interpreter before implementing into the function.

Adding the event is simply a requirement that gtk enforces. Any method bound to a button press or key stroke will need to accept an event as input.

jlm699 320 Veteran Poster

The "built in" module would be Tkinter, but if you're looking for something simple that will generate native-looking GUIs with minimal effort I would suggest wxPython.

There's a wealth of tutorials and sample code in this forum that you are welcome to use (refer to the sticky wxPython samples thread on the first page).

jlm699 320 Veteran Poster

You need to change the definition of con() to support the event details that get automatically passed to any bound method.

The new definition should look like this:

def con(self, event=None):

Note that I initialized event to None so that you can still call it yourself without needing to supply an event class.

jlm699 320 Veteran Poster

Well first problem is that you're never clearing the contents of your list b . Also, you should move the summation of b outside of the for loop so that it only happens once you've found all the factors of the desired number... That should get you pointed in the right direction.

jlm699 320 Veteran Poster

You should be using return values instead of global variables... see if this makes any sense, and if not ask questions.

>>> import random
>>> def get_ran():
...     return random.randint(1,10)
...     
>>> get_ran()
5
>>> get_ran()
10
>>> get_ran()
4
>>> hp = 100
>>> hp -= get_ran()
>>> hp
97
>>> hp -= get_ran()
>>> hp
87
>>> hp += get_ran()
>>> hp
95
>>>
jlm699 320 Veteran Poster

thanks for the post.. that definitely helps, the prog still goes non responsive sometimes tho.

Ah I misread your question. I thought you were asking how to make the frame unresponsive (as in don't allow the user to give input).

The answer lies in spawning a thread to do your intensive processing and just allow your frame to hang out and wait for the thread to return a result.

jlm699 320 Veteran Poster

How do you keep a wx frame from not responding while the code is running in the background? ie a search or other demanding function.

You can use a busy cursor so that the user can't click on anything within the application:

wx.BeginBusyCursor()
# Do all the stuff here
# Once complete:
wx.EndBusyCursor()
jlm699 320 Veteran Poster

I don't understand your first question.. can you clarify what you mean by non-unique random numbers?

That being said, I find the best way to have a program run continuously is a super loop. Example:

import time

def main():
    print "I'm the main function!"
    # Do some other stuff
    time.sleep( 2 )

if __name__ == '__main__':
    usr_inp = 'y'
    print "This program is starting now"
    while usr_inp != 'n':
        main()
        usr_inp = raw_input( "Do you want to continue? (y/n) " )
    print "User selected to quit the super loop"
jlm699 320 Veteran Poster

anyone know the command to define n?

n = #something
# For user input use:
n = raw_input( 'This is a prompt: ' )
jlm699 320 Veteran Poster

I think the function you may be looking for in Python is eval . Or perhaps exec , or its variant execfile , which eliminate reading the files all together.

Refer here to information on these built-in functions.

As far as how to open files within a for loop it could be something like this (untested):

file_base = 'heat'
file_ext = '.dat'
for file_num in xrange(1,101):
    file_name = file_base + str(file_num) + file_ext
    fh = open( file_name )
    file_data = fh.readlines() # or just read()
    fh.close()
    # Do something with the file data
jlm699 320 Veteran Poster

One last note is that employeeWage.readlines(salaries) should actually be salaries = employeeWage.readlines()

jlm699 320 Veteran Poster
try:
    salariesWage=open("PAY.txt", "w")
    salariesList.writelines(salaries)
    salariesWage.close()
except(IOError):
    print "Error writing to file list"
...
try:
    employeeWage=open("PAY.txt", "r")
    employeeList.readlines(salaries)
    employeeWage.close()
except(IOError):
    print "Error writing to file list"

Upon initial inspection I see that you're opening PAY.txt as salariesWage and then employeeWage but then trying to read/write as salariesList and employeeList respectively. That should fix your reading/writing problem...

I also notice that you initialize the variables hour and wage as "0" which means you want those variables to be strings containing the character zero. Once inside your loop you try comparing the values of these variables numerically, so I think that for initialization before the loop you'd actually want hours = wage = 0 . This might not have caused any problems but it's just for completeness' sake.

As far as not being able to input new hours and wage it is due to the fact that you don't reset the values of the variables hour and wage to 0 before the loop restarts. So when the logic hits the line that says: while hours<1 or hours>60: , it will not enter the code block and ask the user for input. To fix this issue just reassign hours = wage = 0 either at the end or the very beginning of your main while loop.

Oh and one last thing... you never add anything to your salaries list unless the user enters 'Done' to quit the program. You should be doing that at the end of your while loop …

jlm699 320 Veteran Poster

What do you mean by "obtained nothing yet"?

I would suggest using a regular expression to group out the SEC= portion and the beginning of the line, but I don't know how consistent that data will appear in said form. Refer here for the re module information

To write a variable to a line in a file you would use something like this:

var1 = 'test1'
var2 = 3456
var3 = 'Something else'
#
fh = open( 'myfile.txt', 'w' )
fh.write( 'var1=%s, var2=%s, var3=%s\n' % ( var1,var2,var3 ) )
fh.close()
jlm699 320 Veteran Poster

thanks for the info do you know how i can paste the code in python and see it in action

Select the code from webpage -> Ctrl + C
Open your favorite code/text editor -> Ctrl + V
Save As.... <File_name>.py
Run!

For your own sanity's sake you should replace the tabs with spaces... also make sure you have the modules required for xturtle

jlm699 320 Veteran Poster

google is your friend http://commons.wikimedia.org/wiki/File:Dragon_curve.png

Wow. I love that db replaced the text within that hyperlink with a smiley. I'm sorry this post isn't on topic but I just wanted to get that out there.

Hey, and the link still works!

EDIT:
kette = chain
laenge = length
zeichne = draw
* Courtesy Google Translate

jlm699 320 Veteran Poster

Also please post code using code tags, as it preserves the formatting and highlights reserved words (such as file). This will increase the chance that other forum members will read your post and be more willing to help.

Use code tags like this:
[code=python] #You code goes here

[/code]

jlm699 320 Veteran Poster

Here's some documentation on the file object and associated methods.

jlm699 320 Veteran Poster

Karen,

Please use code tags when posting code, or else it will become unreadable as it has above.

To use the code tags, wrap your code like this:
[code=python] # Code inside here

[/code]

This will turn on syntax highlighting and preserve your indentation. Also, forum members are much more inclined to help you if your post isn't a huge mess of plain text.

jlm699 320 Veteran Poster

Well, Then how do you guys write proprietor(non-free) software with python?

Open-Source software is the way to go.

jlm699 320 Veteran Poster

I don't believe that there is a way to ensure Python is un-reverse engineer-able... Meaning that even Python byte code programs can be translated back to source code if someone were dedicated enough to do it.

That being said, I used to be a C++ programmer until I discovered Python. I have not touched C++ since I learned Python and have never looked back. I hope that I can continue to use Python for the rest of my professional career as it is by far the best language that I've ever used. It makes programming actually enjoyable and stress free.

The resource I used to learn Python was Dive Into Python, which is a book that is geared towards programmers and not beginners, as it assumes you already know much about control structure, data types, etc.

I hope that you enjoy learning Python and I think that you'll find that it is nothing short of a pleasure to use.

jlm699 320 Veteran Poster

I find that best practice is to always use strip() on lines that I read in from files. This gets rid of all leading and trailing white-space (tabs, spaces, newlines, etc.)

Also, here's a rewrite of your code... I removed the tabs and replaced them with spaces and also stripped out the unnecessary work that you were doing... Please look it over and if there's anything you don't understand, ask and we shall explain.

def rec_paths(file_name):
    f = open(file_name)
    g = f.readlines()	

    for each_line in g:
        if 'path' in each_line.strip():
            return( each_line.strip() )

print(rec_paths('C:\\Documents and Settings\\folderX\\Desktop\\t.txt'))
jlm699 320 Veteran Poster

f.seek(0) will always return to the beginning of a file as well. If you print out the value of beginning in the code snippet above, you'll likely find that it is an integer == 0.

jlm699 320 Veteran Poster

What's an append?

Append is a way to "add on" to the "end" of the list... Here's a visual example:

>>> my_list = [1,2,3]
>>> my_list
[1, 2, 3]
>>> my_list.append(4)
>>> my_list
[1, 2, 3, 4]
>>> my_list.append([9,8,7])
>>> my_list
[1, 2, 3, 4, [9, 8, 7]]
>>> my_list.append(-1)
>>> my_list
[1, 2, 3, 4, [9, 8, 7], -1]
>>>

HTH

jlm699 320 Veteran Poster

I have put # -*- coding: utf-8 -*- on the top of the script

If you remove that line from the top of your script does it change the result?

Also, have you tried utf-16 ?

jlm699 320 Veteran Poster

I need help with my homework :( but no one's replying. [note: this comment was just to move this thread back to the top of the list]

This isn't a place to come and have your homework done for you. Forum-goers here typically don't just give out solutions to homework, as that would be immoral and you'd never learn anything.

When it comes to homework or projects the best bet for getting help is to give us the code that you've tried and the errors or incorrect results that it has produced. We can then give you tips and help you tweak the code, but we do not provide e2e solutions. Not for homework, anyway... I suggest reading this announcement

Oh and we know what a *bump* is; no need to explain.

jlm699 320 Veteran Poster

file_list ends up with the final value from data, rather than a string of all values in the file

On every iteration you're simply over-writing the value of file_list. The proper way to use a list is:

my_list = []
for line in my_file:
    my_list.append( line )

Now on ever iteration of the for loop, we'll *append* each line to the list...

When you say "Just kill the readline() and print the results of the slice in line 3" do you mean to simply end the for loop with file_list = line?

Yes he is saying to remove the line of code containing readline(); however file_list = line is not going to give you the results that you want (refer to my first section of comments)

Somehow I'm not getting the full concept here. Sorry. The bit about "print the results" is throwing me off since I really want to load all the data in to file_list, not "print" it.

He was only suggesting that you print the results for your own debug purposes. Using print statements periodically throughout your code helps when you don't know what's happening... it helps to show you what each step is doing to your data.

HTH

jlm699 320 Veteran Poster

Any corrections and explanations to my code?

Your return statement is inside your for loop so it's exiting on the first iteration.... if you knock it back an indentation level it'll work:

>>> def int2roman(number):
...     numerals={1:"I", 4:"IV", 5:"V", 9: "IX", 10:"X", 40:"XL", 50:"L",
...               90:"XC", 100:"C", 400:"CD", 500:"D", 900:"CM", 1000:"M"}
...     result=""
...     for value, numeral in sorted(numerals.items(), reverse=True):
...         while number >= value:
...             result += numeral
...             number -= value
...     return result
...     
>>> print int2roman(input("Enter a number (1 to 4999) in decimal form: "))
Enter a number (1 to 4999) in decimal form: 1942
MCMXLII
>>> print int2roman(input("Enter a number (1 to 4999) in decimal form: "))
Enter a number (1 to 4999) in decimal form: 1994
MCMXCIV
jlm699 320 Veteran Poster

I wasn't sure of what type of averaging you were looking to do so I assumed something that sounds nothing like what you want. Basically here's the template version:

# Initialize your variables here for avg, sum, count, etc..
    # You may also declare what directory you're working with
    # Example my_dir = '/home/usr/data_collection'
    file_list = os.listdir(my_dir)
    #
    for file_name in file_list:
        # os.path.join will be needed for open() if we're not
        #   currently within my_dir as a working directory
        # To remove the need for os.path.join we could also do
        #   os.chdir( my_dir )
        file_path = os.path.join(my_dir,file_name)
        # example file_path = '/home/usr/data_collection/test1.txt'
        # To protect us from sub directories we'll check if file_path points to a regular file or a directory
        if os.path.isfile(file_path):
        # Open the file, read it's contents into a list, and close it
            fh = open(file_path)
            lines = fh.readlines()
            fh.close()
            #
            # Iterate line-by-line
            for line in lines:
                # Split each line up by white space and strip off line separators (\n or \r\n)
                line_data = line.strip().split()
                # Check that we have two values per line to avoid error
                if len(line_data) == 2:
                    Assign each segment of the line to a variable
                    element = line_data[0]
                    value = line_data[1]
                    # This is where you update your average, sum, count, etc...
                    # Again, this all depends on what you're looking to average
            #
    # Print the results here at the end

Please, try to understand each and every step of this. Don't be afraid to ask questions …

jlm699 320 Veteran Poster

I assume that re-ordering is due to the way that dictionaries are stored in memory... in order to provide faster searching and indexing dictionaries are stored in a special way... much unlike lists and tuples, which retain their order.... Example:

>>> d = {'cat':'purr', 'dog':'woof', 'aardvark':'?', 'chocolate rain':'feel the pain'}
>>> print d
{'aardvark': '?', 'chocolate rain': 'feel the pain', 'dog': 'woof', 'cat': 'purr'}
>>> l = ['cat:purr', 'dog:woof', 'aardvark:?', 'chocolate rain:feel the pain']
>>> print l
['cat:purr', 'dog:woof', 'aardvark:?', 'chocolate rain:feel the pain']
>>>
jlm699 320 Veteran Poster

My thoughts:

Traverse the grid from top-to-bottom, and left-to-right (ie, just like reading a book).
On each character, make a list of *this letter concatenated with every surrounding letter (for this example we'll start at the left or due west position and progress counter-clockwise, ie:

grid = """
ashfghj      0,0 1,0 2,0 3,0 4,0 5,0 6,0
weatyuu      0,1 1,1 2,1 3,1 4,1 5,1 6,1
xctbnmz      0,2 1,2 2,2 3,2 4,2 5,2 6,2
"""

Assume we're looking for hat... we start at position 0,0 and make the list ['as', 'ae', 'aw'] , none of which match 'ha' (from 'hat'). Although since the letter a doesn't match the first character of 'hat', we can move on...

We repeat for s and then h. The character 'h' matches the input_word[0] so we construct the list as above, which reads ['hs', 'he', 'ha', 'ht', 'hf'] and we have a match with 'ha', so we take the indices of the two positions and extrapolate the direction for the length of the desired word (3)...
So 'ha' corresponds to 2,0 and 2,1 ... implying that the final character is at 2,2. After a simple check of 2,0+2,1+2,2 , we have a match and we win.

As such I guess instead of a list of we could use a dictionary keeping track of indices as well... however that wouldn't be necessary since if we know the starting index, along with the position (index) of the two-letter combo in our list, we …

jlm699 320 Veteran Poster

Alright, well here's the code's merged together....

import os

def main():
    """ Example file contents from the /home/usr/data_collection directory:
        2.825       1.00697992588
        2.875       0.952989176901
        2.925       0.91428970229
        2.975       0.890110513425
        3.025       0.879731596138
        3.075       0.959217137445
        3.125       1.07391392796
        3.175       1.04874407027
        3.225       0.857693793906
    """
    # We can keep track of our data in this structure;
    #  however you may make use of any data structure 
    running_avgs = {}
    my_dir = '/home/usr/data_collection/'
    file_list = os.listdir(my_dir)
    #
    for file_name in file_list:
        # Protect us from sub directories
        # os.path.join will also be needed for open() if we're not
        #   currently within my_dir as a working directory
        # To remove the need for os.path.join we could also do
        #   os.chdir( my_dir )
        file_path = os.path.join(my_dir,file_name)
        if os.path.isfile(file_path):
        # Perform the above code on the file as long as it's valid.
            fh = open(file_path)
            lines = fh.readlines()
            fh.close()
            #
            for line in lines:
                line_data = line.strip().split()
                if len(line_data) == 2:
                    element = line_data[0]
                    value = line_data[1]
                    if running_avgs.get(element):
                        # IF it's in our dictionary we can calculate the new avg here
                        pass # This section depends on how you want to handle your avgs
                    else:
                        # The first element can be the running sum of values
                        # The second element will be the count of elements
                        running_avgs[element] = [value,1]
            #
    print running_avgs

if __name__ == '__main__':
    main()
    raw_input('Press enter to exit...')

Again, I haven't tested this so it could contain a syntax error or two... but I hope it helps get you on your way.

jlm699 320 Veteran Poster

Here's how to open a file and parse the contents as per your example:

def main():
    """ test_data.txt contents (minus leading tabs):
        2.825       1.00697992588
        2.875       0.952989176901
        2.925       0.91428970229
        2.975       0.890110513425
        3.025       0.879731596138
        3.075       0.959217137445
        3.125       1.07391392796
        3.175       1.04874407027
        3.225       0.857693793906
    """
    # We can keep track of our data in this structure;
    #  however you may make use of any data structure that suits you (classes, list, etc)
    running_avgs = {}
    #
    fh = open('test_data.txt')
    lines = fh.readlines()
    fh.close()
    #
    for line in lines:
        line_data = line.strip().split()
        if len(line_data) == 2:
            element = line_data[0]
            value = line_data[1]
            if running_avgs.get(element):
                # IF it's in our dictionary we can calculate the new avg here
                pass # This section depends on how you want to handle your avgs
            else:
                # The first element can be the running sum of values
                # The second element will be the count of elements
                running_avgs[element] = [value,1]
    #
    print running_avgs

if __name__ == '__main__':
    main()
    raw_input('Press enter to exit...')

I haven't tested that so it could contain a syntax error or two... but I hope it helps get you on your way.

EDIT: Also keep in mind that you'll want to loop this whole operation for all your files... So if the files are all under a directory you could simply do this:

import os

my_dir = '/home/usr/data_collection/'
file_list = os.listdir(my_dir)
#
for file_name in file_list:
    # Protect us from sub directories
    # os.path.join will also be needed for open() if we're not
    # …
jlm699 320 Veteran Poster

Perhaps this can help: button.set_sensitive(False) Documentation

jlm699 320 Veteran Poster

What version of Python are you using here? On 2.5.2 I get the following:

>>> my_lines = [
...     "======================================================",
... "Name Place Age",
... "======================================================",
... "John US 11",
... "Mary UK 12",
... "Mike US 14" ]
>>> for line in my_lines:
...     if len(line.split()) == 3:
...         sys.stdout.writelines("%s %10s %10s\n" % tuple(line.split()))
...     else:
...         sys.stdout.writelines("%s\n" % line)
...     
======================================================
Name      Place        Age
======================================================
John         US         11
Mary         UK         12
Mike         US         14
>>>

Why are you using stdout.writelines ? Do you specifically need it or can you make use of print ?

jlm699 320 Veteran Poster

@Lizapotter: To preserve indentation and get syntax highlighting (and also spare the forum-goer's eyes) please use code tags as such:

[code=python]
# Your code goes in here
[/code]
jlm699 320 Veteran Poster

You would want to initialize the counter to 0 before your while loop like my_count = 0 and then near the end of the loop contents you can add a my_count += 1 (which is equivalent to my_count = my_count + 1 )

eyewirejets commented: Soved it easily +1
jlm699 320 Veteran Poster

Maybe you need

self.gladefile = open( "hello.glade" )

instead of

self.gladefile="hello.glade"

?

jlm699 320 Veteran Poster

You can place that check at the end of your while loop only add a break to each case so that if either X or O wins, the while loop is ended.

jlm699 320 Veteran Poster
def printGrid(self):
        for y in range(self.height):
            for x in range(self.width):
                print self[x, y].value,
            print

	def printGrid2(self):
		for y in range(self.height):
			for x in range(self.width):
				print self[x, y].value,
			print

the printGrid2 method can't be found or something.

Indentation is very important in Python. Your printGrid2 method is defined within printGrid, so it isn't a member of the class Grid

This should fix it:

def printGrid(self):
        for y in range(self.height):
            for x in range(self.width):
                print self[x, y].value,
                print

    def printGrid2(self):
        for y in range(self.height):
            for x in range(self.width):
                print self[x, y].value,
                print

It appears that you're using a mix of tabs and spaces, which is a no-no. Save yourself the trouble and convert all your tabs to spaces (4)