jlm699 320 Veteran Poster

Use the button_object.config(text=my_text) option. Source

jlm699 320 Veteran Poster

Maybe it's four 8-bit numbers together?

>>> i = '100010101001000010000011111001010'
>>> first_num = int(i[:8],2)
>>> secnd_num = int(i[8:16],2)
>>> third_num = int(i[16:24],2)
>>> fourt_num = int(i[24:32],2)
>>> first_num
138
>>> secnd_num
144
>>> third_num
131
>>> fourt_num
229
>>>
jlm699 320 Veteran Poster

The backslash (\) is used for an "escape character". So \t is the escape character for a tab, \n is for newline, and \" or \' are escapes for a double and single quote respectively.

Let's say we have a string: 'Hi my name is Charlie' . The single quotes are what tells the interpreter that every character in between is part of the string. Now if we wanted to use a contraction inside that string and change it to: 'Hi my name's Charlie' , you can see that the string (ie, what's inside the quotes) is actually only 'Hi my name' and the rest is attempted to be interpreted to Python code.

To solve this there are two methods:

1) Change the type of quotation marks that are used on the string, so we would instead have: "Hi my name's Charlie" 2) Escape the "inner" quotation so that it is interpreted as the character instead of the syntax marker: 'Hi my name\'s Charlie' HTH

jlm699 320 Veteran Poster

Here, this should give you some insight into how to define an encoding style for your whole python script.

jlm699 320 Veteran Poster

At anytime, dinner... literally anytime.

jlm699 320 Veteran Poster

Personally I'd use regular expressions like so:

>>> import re
>>> regex_compiled = re.compile('^<Ranking: (.*) \((.*)\)>$')
>>> input_data = """<Ranking: AA (John)>
... <Ranking: CA (Peter)>
... <Ranking: TA-A (Samantha)>
... """
>>> for each_entry in input_data.split('\n'):
...     regex_match = regex_compiled.match(each_entry)
...     if regex_match:
...         print 'Ranking: % 5s  Name: %s' % (regex_match.group(1), regex_match.group(2))
...     
Ranking:    AA  Name: John
Ranking:    CA  Name: Peter
Ranking:  TA-A  Name: Samantha
>>>

If you need any specific part of that explained I'd be happy to do so.

If you're really in need of using string methods I'd do something like the following:

>>> for each_entry in input_data.split('\n'):
...     rank_search = '<Ranking: '
...     idx = each_entry.find(rank_search)
...     if idx != -1: # string.find returns -1 when not found
...         idx += len(rank_search) # Increase idx to where rank_search ends
...         end_idx = each_entry.find(' (', idx) # idx as starting point for find
...         print 'Ranking: % 5s  Name: %s' % (each_entry[idx:end_idx], each_entry[end_idx+2:-2])
...     
Ranking:    AA  Name: John
Ranking:    CA  Name: Peter
Ranking:  TA-A  Name: Samantha
>>>
jlm699 320 Veteran Poster

Here's a regular expression that should work for you: re.split('([.!?] *)', a) If you need it broken down and explained for you I can do that; otherwise, it may be more fun to investigate using the documentation and pick it apart to learn how it works!

Here's me using your test string:

>>> import re
>>> a = "this is the test string! will it work? let's find out. it should work! or should it? oh yes. indeed."
>>> rtn = re.split('([.!?] *)', a)
>>> ''.join([each.capitalize() for each in rtn])
"This is the test string! Will it work? Let's find out. It should work! Or should it? Oh yes. Indeed."
>>>

At the end there I did a list comprehension. To break it out it would be:

>>> str_pieces = []
>>> for each in rtn:
...     str_pieces.append(each.capitalize())
...     
>>> ''.join(str_pieces)
"This is the test string! Will it work? Let's find out. It should work! Or should it? Oh yes. Indeed."
>>>
jlm699 320 Veteran Poster

If you want to use backslashes in a path name for loadtxt (or savetxt), the you need to put in double backsplashes so:
'c:/users/ross/desktop/radiograph_data.txt'
becomes:
'c://users//ross//desktop//radiograph_data.txt'

Those are forward slashes, which do not need to be escaped (the escape character is \, which is backslash)

jlm699 320 Veteran Poster

The method os.getcwd() can only ever return a single string. There's ever only one current working directory, so when you're saying for d in os.getcwd() , you're actually iterating over the string character by character. What you really want is just generators = os.walk(os.getcwd())

jlm699 320 Veteran Poster

If you search the forum you'll see this question has been asked a bajillion times.

Here's an example from earlier today.

jlm699 320 Veteran Poster

Not exactly, I'd like to take the values that are being sorted on and put them into a new list/dict etc.

For example, extracting only these values from the dictionary above:
new_list = ('2.5','3.5','3.9','4.0','3.1')

Okay... how about this:

>>> data_dict = {
... '1234': ['Matt', '2.5', 'CS'], 
... '1000': ['John', '4.0', 'Music'], 
... '1023': ['Aaron', '3.1', 'PreMed'], 
... '1001': ['Paul', '3.9', 'Music'], 
... '9000': ['Kris', '3.5', 'Business']
... }
>>> [data[1] for data in data_dict.values()]
['2.5', '3.5', '3.9', '3.1', '4.0']
>>>

That's just a quick list comprehension that will extract the second element (at index 1) from each list (which is stored as the "value" part of each dictionary entry.

jlm699 320 Veteran Poster

Can you help?

Why, yes! This case would be a good one to use the dictionary's get method, which will allow you to determine if the key is already in the dictionary or not, and act accordingly.

def file_to_dict(fname):
    f = open("file.txt")
    d = {}
    for line in f:
        columns = line.split(" ")
        letters = columns[0]
        numbers = columns[1].strip()
        if d.get(letters):
            d[letters].append(numbers)
        else:
            d[letters] = list(numbers)
    print d
    
if __name__ == "__main__":
    fname = "file.txt"

Try that on for size.

Basically, by default get will return None if the key is not in the dictionary (you can pass a second parameter to mean default but I prefer None type). So first we check to see if the key is in the dictionary already. If it is, we use the list method append to add the new number onto the end of our list. If the get statement returned None, we instead do what you used to do (create a list as the value to the key).

HTH

jlm699 320 Veteran Poster

Here's some examples of converting between strings, lists, lists of strings, and ints using list , str and int :

>>> usr_inp = '123456'
>>> usr_inp2 = '1,2,3,4,5,6'
>>> list(usr_inp)
['1', '2', '3', '4', '5', '6']
>>> usr_inp2.split(',')
['1', '2', '3', '4', '5', '6']
>>> list(usr_inp)[4]
'5'
>>> int(list(usr_inp)[4])
5
>>> str(int(list(usr_inp)[4]))
'5'
>>>
jlm699 320 Veteran Poster
def main():
    print "This program illustrates a chaotic function."
    print "Please enter two numbers between 0 and 1."
    x = input ("Enter first number: ")
    y = input ("Enter second number: ")
    print
    print "input", x, y
    print "-----------------"

    for i in range (8):
        x = 3.9 * x * (1 - x)
    for i in range(8):
        y = 3.9 * y * (1 - y) 
        print x, y

main()

output:

This program illustrates a chaotic function.
Please enter two numbers between 0 and 1.
Enter first number: .25
Enter second number: .25

input 0.25 0.25

0.540417912062 0.73125
0.540417912062 0.76644140625
0.540417912062 0.698135010439
0.540417912062 0.82189581879
0.540417912062 0.570894019197
0.540417912062 0.955398748364
0.540417912062 0.166186721954
0.540417912062 0.540417912062

I'm adding code and quote tags to your stuff so that it's easier for other forum members to read. Please try to make use of these options when posting, as it will greatly increase the likelihood that you'll get satisfactory responses.

To see the different tags I've used in this post, simply "Reply" to the message and look at what I typed. Also, you can use the tool buttons at the top of the editing window to help with generating tags. There's lots of different BB Tags available on this forum, you'd benefit from using them.

--

Now onto your dilemma.

You have print x,y in your second loop only. Loop 1 modifies the value of x. Loop 2 modifies the value of y. …

jlm699 320 Veteran Poster

It would be nice if the GUI had color-coded parentheses, to show groupings... or better yet, shading of a similar method...

Why not use one that does then?

I use Notepad++, but I know that even python-specific IDEs like PyScripter have parenthesis highlighting, etc. In fact, PyScripter will have a red underline on any unmatched parenthesis similar to a "spelling error" in a word processing application.

jlm699 320 Veteran Poster
def getpos():
        r1 = x,y = 100,100
        r2 = x,y = 800,800

i get the error:

[I]Traceback (most recent call last):
    r1.step(r2.getPos()[0],r2.getPos()[1])
AttributeError: r2 instance has no attribute 'getPos'[/I]

I have defined getPos() for both r1 and r2 (my objects), so why do i get that error?
Any one got any clues?

So if getpos() is a function for a class object, then you forgot the most important detail. The parameter self !

Your function should be defined as such:

def getpos(self):
        r1 = x,y = 100,100
        r2 = x,y = 800,800

But then again you're using r1 and r2 inside this function, which may indicate this isn't a class function at all. So in that case, you wouldn't use r2.getPos(), you should just use getPos().

Maybe you should post a little bit more code so that we have some context to go by.

thehivetyrant commented: Very good detail and help +1
jlm699 320 Veteran Poster

In the if statement you are using w[i+5].

This means that you need to make sure the maximum i plus 5 does not go out of bounds for the string. Let me demonstrate:

>>> w = 'aabbccdd'
>>> print len(w), len(w) - 5
8 3
>>> range(3)
[0, 1, 2]
>>> print w[0], w[1], w[2], w[3]
a a b b
>>> print w[2+2], w[2+3], w[2+4], w[2+5]
 c c d d
>>> print w[3+5]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
IndexError: string index out of range
>>>

You see that the index of the string can only go up to 7 (the length - 1; and you need to subtract 1 because the first index is 0).

If we try to look at index 8 we get an IndexError. So your code just is making sure we're not breaking the indexing.

HTH

A_Dubbs commented: Thank you +1
jlm699 320 Veteran Poster

Anyone got any ideas?

This should help. Don't ever underestimate the power of documentation.

jlm699 320 Veteran Poster

1. So you're saying I'm not going to be using curses ever in my life unless I get a linux?... crap...

Unless you run your script on a compatible platform, you will not be able to experience the joy of curses, no. If you're on windows you can either download and burn a linux live CD to boot from (this doens't require installing linux), or you could install cygwin. This program is basically an emulated version of linux; however it will allow you to at least play around with curses and a few linux commands to get used to it.

2. If you mean IDLE, I'm using IDLE. I think I saw wxpython somewhere in the program files... but we call it IDLE, so... yeah...

No, IDLE is your IDE (environment to develop your code). wxPython is a module that you would import. The packages within wxPython allow you to develop a GUI for an application. wxPython is not included with Python, it's a separate install. Take a look at the sticky thread in this forum for some examples of using wxPython and the results that it can give.

the code itself -should- work.. in fact... I need someone to test that...

It does not work, unfortunately.

I think you may be confused about how curses works. Curses isn't just a library that allows you to play with how stdout is put on the screen, it's almost like an entire platform. There's literally books on how to use it, …

jlm699 320 Veteran Poster

And when you say compatible platform... uhm... whuh???

The platform can be simplified to mean your operating system. If you load up a python interpreter try the following exercise:

>>> import sys
>>> sys.platform
'win32'
>>> import curses
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Python26\lib\curses\__init__.py", line 15, in <module>
    from _curses import *
ImportError: No module named _curses
>>>

This was done on a windows box. You can see that my platform is win32, which is not a compatible platform for curses (without some type of third-party library, which may not even exist). Now let's try the same thing on a red hat box:

>>> import sys
>>> sys.platform
'linux2'
>>> import curses
>>>

Now on red hat linux (a unix-based OS, which is compatible with curses) the import works just fine.

Uhm... wait, difference between wxpython and python are what?...
.... crap, now I'm so confused...

wxPython is a GUI framework build around the wx.Windows library, which is used to build application GUIs. It's basically a module that you can import into your python programs that opens up a whole new world of options for you when designing your programs. You can find the wx website here, and there's a bajillion code examples of different GUI elements in this thread here (you'll find it as a sticky at the top of this Python forum).

Hope that you find something that works for you. Good luck!

jlm699 320 Veteran Poster

Gribouillis

I'm not sure if this has been fixed or not (perhaps you're using a newer version of Python where this bug has been eliminated) but when I use your path.join this is what I get:

>>> from os.path import join as pjoin
>>> pjoin("C:", "foo", "bar", "baz")
'C:foo\\bar\\baz'
>>>

This is in Python 2.6.2 and has always been this way. I'm not sure why, but I've always found that when using a drive letter in windows you always have to explicitly add backslashes like this:

>>> from os.path import join as pjoin
>>> pjoin("C:\\", "foo", "bar", "baz")
'C:\\foo\\bar\\baz'
>>>
jlm699 320 Veteran Poster

though i'm calling pr() function in the subclass after calling the get_details() function(which assigns value to name) it doesn't print the current value of name.

Actually, it is printing the current value of name. The employee.name is always a space (' '), because you never change it. In your get_details function, you have created a new variable called name and assigned the users' input to it. Why don't you try printing x.name after your call to x.get_details()? You'll see that x.name is still just a blank space. The problem is that then name object that you're creating inside get_details only exists inside the scope of that function. You should be using self.name, which is the persistent attribute of the employee class. Let me demonstrate this principle:

>>> class no_init(object):
...     name = 'I have no init function'
...     def print_name(self):
...         name = input('Input some name: ')
...         print('self.name', self.name)
...         print('name', name)
...     
>>> ni = no_init()
>>> ni.print_name()
Input some name: Testing
self.name I have no init function
name Testing
>>> ni.name
'I have no init function'

As you can see, the name attribute is always "I have no init function" even though there is a " name " inside my print_name function. This is because that particular object is created and destroyed inside that function only. To refer to an attribute of a class from inside the class declaration you need to use self. , whereas outside the class you use the …

python.noob commented: Simply awesome +0
jlm699 320 Veteran Poster

The print row command outputs:


I want 'test' to go into Category and 'one' to go into Value.

In that case you'll want this:

c.execute("INSERT INTO a (Category, Value) VALUES (%s, %s)", tuple(row[0].split()))

Basically this takes the element [0], which represents that string 'test one', and then splits it (the default split delimiter is a space), so it turns it into . Finally, you just need to turn it into a tuple.

When doing string formatting, you need to have a tuple containing each argument for string formatting as an element. Here's an example of a string formatting requiring two arguments:

>>> print 'Hey %s totally %s check' % ('test', 'one')
Hey test totally one check
>>>

As you can see, I need two things to fill into the %s pieces. The two elements in the tuple satisfy this requirement.

Here's the transformation from "row" to the tuple required in broken down steps:

>>> row = ['test one']
>>> row[0]
'test one'
>>> row[0].split()
['test', 'one']
>>> tuple(row[0].split())
('test', 'one')
>>>
Shadow-Illusion commented: Solved problem well +0
jlm699 320 Veteran Poster

Is there a way to use a string to call a previously named variable?

Eval is what you're looking for:

>>> sports = [1,23,4]
>>> eval( 'sports' )
[1, 23, 4]
>>>
jlm699 320 Veteran Poster

When you open your file you should be opening it in append mode using the 'a' flag (right now you're opening it in write mode, 'w').

jlm699 320 Veteran Poster

This is a very hacked solution but:

>>> sports = ## Defined as above - snipped for length
>>> def build_html(chosenCategory):
...     up_locals = sys._getframe(1).f_locals
...     for each_var in up_locals:
...         if id(up_locals[each_var]) == id(chosenCategory):
...             var_name = each_var
...     filename = '%s.html' % (var_name)
...     print filename
...     
>>> build_html(sports)
sports.html
>>>

You could even be brazen and shorten that for loop to a single list comprehension (albeit a very long one):

def build_html(chosenCategory):
    var_name = [each_var for each_var in sys._getframe(1).f_locals if id(sys._getframe(1).f_locals[each_var]) == id(chosenCategory)][0]
    filename = '%s.html' % (var_name)
    print filename
vegaseat commented: actually a good hack +9
qadsia commented: Very Helpful! solved my problem. +0
jlm699 320 Veteran Poster
self.marks.append(self.twelve.GetValue())
        self.average=sum(self.marks)/len(self.marks)

Note that GetValue returns a string. In order to use sum you'll need to convert all elements of self.marks to integers or floating points. You could probably get away with using a try / except block like this:

>>> marks = ['1','2.5','3','4.2','5','6.6666','7.111']
>>> new_marks = []
>>> for mark in marks:
...     try:
...         new_marks.append(int(mark))
...     except ValueError:
...         new_marks.append(float(mark))
...     
>>> new_marks
[1, 2.5, 3, 4.2000000000000002, 5, 6.6665999999999999, 7.1109999999999998]
>>> sum(new_marks)/len(new_marks)
4.2110857142857139

As you can see I try to convert to int first, and if that fails (as a string representing a floating point will raise a ValueError in the int method), I'll then convert to float . This protects me from failure and allows the script to convert correctly between string to int and/or float.

At this point, you should be okay using the sum function, as your list elements will all be numerical instead of strings.

Alternately, you could use list comprehension to convert to floats on the fly like this:

>>> marks = ['1','2.5','3','4.2','5','6.6666','7.111']
>>> sum([float(mark) for mark in marks])/len(marks)
4.2110857142857139

In this version I only use float, as both an int and float will convert to float whereas a float will not convert to an int so this avoids the failure...
To break that down step by step the list comprehension becomes:

>>> new_marks = []
>>> for mark in marks:
...     new_marks.append(float(mark))
...     
>>> sum(new_marks)/len(new_marks)
4.2110857142857139
>>>

If you have questions about list comprehension just …

jlm699 320 Veteran Poster

1) This program has no indentation. To preserve formatting on this forum you must wrap your code in code tags. However after looking closer at your post it appears that your code has no indentation even in its original form.

2) You need to learn the difference between defining a function and calling one. You should never ever ever ever ever be defining a function inside a loop or any other regular code unless it truly needs to be a dynamic function (which you'll likely never encounter).

vegaseat commented: good points +9
jlm699 320 Veteran Poster

Mensa: your code was very well structured and a nice example of reading user input then using it for calculation. Here's how I've modified your code:

def calc_payment(int_rate, num_pmnts, principal, freq):
    ''' This function will calculate the payment amount of a loan.
    @ Inputs
    - int_rate  - The interest rate of the loan
    - num_pmnts - The number of payments required
    - principal - The original amount of the loan (minus down-payment)
    - freq      - Frequency of payments (weekly, monthly, quarterly, annually)
    
    @ Returns
    - pmnt_amt  - The amount that each payment will be
    '''
    
    freq_lookup = {'weekly':52, 'monthly':12, 'quarterly':4, 'annually':1}
    int_rate = float(int_rate) / 100
    
    rr = int_rate / freq_lookup[freq]
    x = (1.0 + rr) ** num_pmnts
    y = rr / (x - 1.0)
    pmnt_amt = (rr + y) * principal
    
    return pmnt_amt


def main():
    r = input('What is your interest rate?   ')
    t = input('How many payments will you make?   ')
    la = input('What was the amount of the loan?   ')
    rt = None
    while rt not in ['weekly', 'monthly', 'quarterly', 'annually']:
        if rt:
            rt = raw_input('Sorry that was not an option, please respond with weekly, monthly, quarterly, or annually:   ').lower()
        else:
            rt = raw_input('Do you make your payments weekly, monthly, quarterly, or annually?   ').lower()
    payment = calc_payment(r, t, la, rt)
    print 'Your %s payment will be %.2f' % (rt, payment)


if __name__ == '__main__':
    main()
    raw_input('Press Enter to Exit...')

Here are the modifications I made:

1. Moved the payment calculation to a function called calc_payment

vegaseat commented: nice info +9
jlm699 320 Veteran Poster

How do I create this server? Can the server and the databases be on any machine's hard disk on the network?

This process is pretty easy with Postgresql; just download and install from here. There's documentation and help resources there for you if you're a command line junkie. There's a GUI front-end for pg that you can use to setup your database quickly and with very minimal effort. And yes, you can install the server/database onto any machine's hard disk but keep in mind that if you need a large database that is always available you'll want to install it on a server (or at least a reliable computer that is always available), preferably with more than plenty of storage.

Also, once the server and databases are created, how is access granted to the server?

You set up user accounts with passwords

In my application I use wxpython as a front-end, but can anyone with a front-end get onto this database server?

wxPython isn't your front-end it's just your GUI toolkit. The front-end would be whatever you use to access the database. Anyone that has a compatible front-end would have access as long as they know a user name/password (can also be open access ie, no pw). When you install pg it comes with a very nice front-end that will allow you quick and easy access to any pg databases. Any body that wants to access your db could install this application.

You could alternately create and …

jlm699 320 Veteran Poster

(a & b):
What happens with logical and? If a is false, does python evaluates b or not?

No. Here's the code I just used to check this:

>>> def a():
...     print 'a'
...     return False
...     
>>> def b():
...     print 'b'
...     return True
...     
>>> a() and b()
a
False
>>> b() and a()
b
a
False
>>>
vegaseat commented: good example +13
jlm699 320 Veteran Poster

I've been unable to get to it for the last hour or so.

This is a great site to keep in mind when you're posed with this question in the future...

www.downforeveryoneorjustme.com

lllllIllIlllI commented: Ah, i love that site! +4
jlm699 320 Veteran Poster

sys.stdin is an "always open" file handle to the stdin and likewise sys.stdout. To use them, import sys.

jlm699 320 Veteran Poster

I think you'll probably need to make use of eval in this case:

>>> myLengths = [3, 8, 5]
>>> for eachLength in myLengths:
...     print eval("'%0" + str(eachLength) + "d' % 2")
...     
002
00000002
00002
>>>

Unless you're willing to split your above code into two steps like this:

>>> my_str = "%0" + str(myLength) + "d"
>>> my_str % 2
'002'
>>>

What's happening now is it's trying to evaluate "d" % 2 . You need to make sure the string formatting and concatenation happens before trying to use the "outer" format. If that makes sense

daviddoria commented: Perfect, quick answer! +3
jlm699 320 Veteran Poster

i am running the worldloader.py file

Try os.getcwd() at the beginning of your script to make sure you're actually in the TPP/engine directory.

Unless you're actually running the script from within the TPP/engine directory you'll need to add it to your path. You can do that at the beginning of your script like so:

import sys

sys.path.append('/home/TPP/engine')
# Rest of your code....
vegaseat commented: thanks for a good solution +12
jlm699 320 Veteran Poster
shadwickman commented: Didn't know about Dive Into Python, I learned something new too! +2
jlm699 320 Veteran Poster

I want to create subfolders in already existing subfolders.

Use os.makedirs() to make directories.

I'm just wondering about how to walk between folders.

Use os.walk() or os.chdir() to move between directories.

shadwickman commented: Thorough +2
jlm699 320 Veteran Poster

Hey jlm699, how come you called random.seed()?

Habit

scru commented: oh I see; I thought it was some requirement that I'd been missing. +6
jlm699 320 Veteran Poster

I provided an answer to the question that you asked, which was

I would like to know if there is some possible way to distinguish between numeric and characters

Now it is up to you to take that principal and implement it in a simple loop to finish this task. We're not here to create custom solutions for you, we simply help when you get stuck and teach you how to teach yourself to program. Please read the site policies and forum guidelines, as well as all posted announcements before posting.

It would also help if you tried searching to see if other people have already had the same question answered (HINT: they have).

vegaseat commented: good point +12
jlm699 320 Veteran Poster

To take a series of lines in a text file that are separated by newline characters and mash them into a single line of text:

# Read from your input file using readlines(), then:
out_txt = '%s %s' % (my_txt[0], ''.join(my_txt[1:]))

Then you can write the out_txt to your new file. Note that the above code assumes you read your file using readlines into a variable named my_txt

vegaseat commented: nice solution +12
jlm699 320 Veteran Poster
loadWords()

This is your problem. While the function actually returns the dictionary, you're never actually "catching" with anything. You should be doing something like this:

my_results = loadWords()

Then the variable my_results will contain whatever object is passed back from the function loadWords()

SoulMazer commented: Always helps and is very thorough. +1
jlm699 320 Veteran Poster

Use code tags when posting code or else it is unreadable (as above).

[code=python] # Put your code in here

[/code]

Please

jlm699 320 Veteran Poster

Fight Club

F*ck redemption. We are God's unwanted children? So be it!
...
You're not your job. You're not how much money you have in the bank. You're not the car you drive. You're not the contents of your wallet. You're not your f*cking khakis... You are not special. You are not a beautiful or unique snowflake. You're the same decaying organic matter as everything else.

Reminds us that material possessions mean nothing in the end. What legacy will you leave behind?

iamthwee commented: Seen this movie 10+ times! +21
maydhyam commented: Great words!!! +2
jlm699 320 Veteran Poster
import os
os.system( 'cat file.txt | grep "line2="' )

Sometimes the simplest solution is the best one.

scru commented: indeed +6
jlm699 320 Veteran Poster

How would you guys put that in laymen's terms? if not line.strip()

I would translate it to: if empty line: I guess. Here's an example, basically this code is relying on the fact that Python considers an empty string, or '' to be a False, while a non-empty string is True. Let me demonstrate:

>>> empty_line = '\n'
>>> text_line = 'Lipsum\n'
>>> 
>>> empty_line.strip()
''
>>> text_line.strip()
'Lipsum'
>>> bool( empty_line.strip() )
False
>>> bool( text_line.strip() )
True
>>> if '':
...     print 'Empty!'
...     
>>> if not '':
...     print 'Empty!'
...     
Empty!
>>>

So as you can see, strip removes the new line character and any bounding white space (tabs, newline, spaces - on the far left and right of the string).

Since Python considers an empty line to be False, this code is waiting for a line that does not evaluate to False, before acting on it.

>>> lines = [ 'Not empty\n', '\n', '         Foobar\n' ]
>>> for line in lines:
...     print bool( line.strip() ), '=', line.strip()
...     
True = Not empty
False = 
True = Foobar
>>> for line in lines:
...     if line.strip():
...         print 'Found a line: %s' % line.strip()
...     else:
...         print 'Empty line!'
...     
Found a line: Not empty
Empty line!
Found a line: Foobar
>>> # Now repeat with 'not' to negate the True/False
>>> for line in lines:
...     if not line.strip():
...         print 'Empty line!'
...     else:
...         print 'Found a …
jlm699 320 Veteran Poster

Here's some clues to help you!

>>> ord('A')
65
>>> ord('a')
97
>>> ord('Z')
90
>>> ord('z')
122
>>> from string import letters
>>> letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> uppers = letters[26:]
>>> lowers = letters[:26]
>>> uppers
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> lowers
'abcdefghijklmnopqrstuvwxyz'
>>>

you cna iterate over those strings easily like this:

for lower in lowers:
    for upper in uppers:
        print lower, upper
kiddo39 commented: Thanks for the help +1
jlm699 320 Veteran Poster

I suggest downloading the 'Docs and Demos' along with your wxPython install, as it gives you a great launch pad to start writing your own GUIs by giving you sample code of almost every single type of wx object.

It's ridiculously helpful when starting wxPython.

Nick Evan commented: Everyone (including me) seems to agree, so +rep :) +17
jlm699 320 Veteran Poster
[Snipped for brevity]

Your problems all stem from the fact that you aren't recognizing the 'scope' of your variables. You shouldn't be using global variables at all in fact, and your code could use a more coherent structure (for your own sake).

Here's a quick example of a better structure to use for your code:

#!/usr/bin/python

import os.path
from random import choice

def displayBoard( ... ):
    ...

def createPositions( ... ):
    ...

...

def main():
    # Initialize all your variables here
    win = False

    while not win:
        # Call your 'game' functions
        ...
        win = winner()
    
    # Print any final messages to the user, etc.

if __name__ == '__main__':
    main()

Every single one of your functions needs to be revamped to make use of local variables only. A function should be completely independent of the code outside the function. It should receive the inputs from the main code, do the work that it needs to do, and then return a result. It should not be using global variables willy-nilly because you'll run into many problems like you have in this code.

Also your functions should not be calling themselves. This is recursion and it's not useful in this type of situation. You should simply set up a while loop as I demonstrated above and continually call each function until the game has been won

scru commented: to be honest man, this guy has a lot more to learn that just the proper use of functions. +6
jlm699 320 Veteran Poster

Holy crap no. Jython is the scourge of humanity, and in my opinion utter and complete garbage. I don't even know why it exists except to astound and bewilder. I used it once to make an application that could interface with Lotus Notes.

Every time I look back at that period in my life I get sick thinking about having to use Jython. Blech.

scru commented: ++++++++++++1 +6
jephthah commented: but how do you REALLY feel? +10
jlm699 320 Veteran Poster

No, you should never be declaring classes inside a function... Your class definitions should go out on the main level and then call them from within the functions...

Also, get rid of your calls to input as it's not safe. You should always use raw_input and then convert to a numerical object. How about you try firing up your interpreter and use input() then type in 4 * 5 + 10 ... It's a flaw that is being removed in Python 3.0

sneekula commented: good advice +6