jlm699 320 Veteran Poster

Try removing the following two lines from your board() function and placing them between num_players and board() at the bottom of your script like so:

Num_Humans()
root = Tkinter.Tk()
root.attributes('-topmost', True)
Board()

I hope that's what you were looking for

EDIT:
As far as tips here's my first:
The 50 lines of code used to generate the T1 through T50 labels can be simplified to the following two lines:

for i in xrange( 1, 51 ):
        exec 'T%s = Tkinter.Label(root, text ="%s", relief=RIDGE,padx=3,pady=10 )' % (i,i)

This can be used for the other long sections of code, but this is the most apparent need for it...

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

Are you using Python30\python.exe or Python25\python.exe to run 2to3? I think 3.0 changed the way imports work so this script probably depends heavily on those changes.

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

thanks scru that got rid of the first error but now i have the error of attempted relative import of non package.

from . import item

how can i fix this?

What is that? Did you write it or is part of 2to3?

jlm699 320 Veteran Poster

i tried that in the cmd promt and it said that 'python wasnt a proper command'

You need to use the full path to python.exe if it's not in your PATH variable...

So instead of python path_to_2to3 my_program.py you would need C:\\Python26\\python.exe path_to_2to3 my_program.py Or which ever version of Python is appropriate. Check your system in case you've installed python in a different directory.

jlm699 320 Veteran Poster

Why does it get messed up?

Well apparently the Artist class has overloaded the __repr__ method so that when you print an instance of the class, it gives you a pretty output in string form instead of the reference to the class itself.

When you print the list containing these instances, the __repr__ function is never called since you're not printing the instance but rather the container holding those instances...

Does that explanation make sense? Maybe some code will help to explain what I mean:

>>> class ugly_class(object):
...     def __init__( self ):
...         self.test_var = 'Blank'
...     
>>> class pretty_class(object):
...     def __init__( self ):
...         self.test_var = 'Blank'
...     def __repr__( self ):
...         return 'The value of my test_var is %s' % self.test_var
...     
>>> my_uc = ugly_class()
>>> my_pc = pretty_class()
>>> my_uc
<__main__.ugly_class object at 0x01E85EB0>
>>> my_pc
The value of my test_var is Blank
>>>

As you can see, since I overloaded the __repr__ method in the pretty_class it gave me a nice pretty looking string output instead of the reference to the class instance itself.

HTH

jlm699 320 Veteran Poster

Instead of sleeping for the user to see the end message you can place an input at the end of your program so that the user has to hit <Enter> to quit like this:

# This is the last line of code
raw_input( "Press <Enter> to exit..." )
jlm699 320 Veteran Poster

You can try declaring the file as a different enoding all together with something like this: # -*- coding: <encoding-name> -*- .

Refer to this documentation on declaring new encodings.

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

not quite sure what the difference with int(raw_input) is from just input, but i'll figure it out...i notice command is in 2.6, but not in 3.0

raw_input forces the user's input into a string data type, where as input actually parses the input... this should illustrate the difference:

>>> input( "Enter something: " )
Enter something: 4 + 7 * 10
74
>>> raw_input( "Enter the same thing: " )
Enter the same thing: 4 + 7 * 10
'4 + 7 * 10'
>>>

As you can imagine, it would be possible to enter malicious code using this method.

In 3.0 this "hole" was closed by making input() the new raw_input() and doing away with the parsing method... I hope that wasn't too confusing I know I didn't explain it well.

Check this out: it's Python Regrets, a good read.

max.yevs commented: ah alright nice +1
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

now going into python i found that python 3 is just out but recourses are limited (including IDEs) any help on that ?

I'd stay away from Python 3 for now. None of the GUI modules support Python 3 except for Tkinter, which is in my opinion much harder to work with than wx.

I think the best bet is to use 2.5. (I'm not sure if wx has a 2.6 version or not, if so I'd go with that guy)

jlm699 320 Veteran Poster

hi
I want to write this code in do while or if else, or any other way except for loop. here is the code

for i in range(65,90):
     for j in range(65,90):
         for k in range(65,90):             
             token=chr(i)+chr(j)+chr(k)	 	    
             block = ((i<<16)+(j<<8)+(k))             
             cblock = pow(block,e,n)
             table[token]=cblock

can anyone please help me to write this in anyother format?
thanks

Why are you looking to get away from the for loop? I believe that is the easiest and most straight forward way to do this....

Note: range(65,90) will only give you letters A through Y. You're missing out on the 'Z'; although perhaps that's what you had intended...

jlm699 320 Veteran Poster

However I'm not too clear on what this code does. Specifically, what does the line track_info, track_date = tracks do? Does this unpack the tuple?

Precisely. Here's an illustrative example:

>>> my_tuple = ('Item 1', 2)
>>> elem_1, elem_2 = my_tuple
>>> elem_1
'Item 1'
>>> elem_2
2
>>>

I'm also unclear on the relation between the classes and attributes. In the documentation, there are 3 classes: User, Artist and Track. How can one attribute (scrobble.Artist) be inside an instance of a different class (Track)?

Basically this seems to be something that is done in the instantiation of the parent class. It would make sense to have an over-arching Track class that contains an instance of the Artist class; however we are getting ahead of ourselves, since Artist might not be a class at all and really just an element of the Track class.

Have you tried doing something like this:

track_info, track_date = tracks
dir(track_info)

This should print out all the methods and attributes of that instance of the Track class. Hopefully this will help to highlight what functions and elements you're able to make use of to get the info you're looking for.

If I use the above code, I get this output now:

<scrobble.Artist(u'Groove Armada') - u'Hands of Time'

How could I unpack this to just get 'Groove Armada'?

See my last comment...

EDIT: If at all possible I suggest loading up your Python interpreter and step through your code so that it's easier …

jlm699 320 Veteran Poster

Sounds like you'd want to spawn two threads. One to constantly update mytime and another to wait on the user's input. Is that what you mean?

I'm pretty sure vegaseat has provided a number of examples of spawning threads with subprocess, try searching the forum for some good examples

jlm699 320 Veteran Poster

# we should not be a service to solve interesting lab projects. This one clearly is just that, a request for help in CS 380.

This is true, but thankfully the OP came with example code and exactly what his difficulty is. Most people come into this forum and simply copy-paste the instructions to their problem and say

NEED HELP ASAP! Urgent! PLEASEEEEEEEEEEEEEEE!!!!!

So a pat on the back for the OP for reading the forum announcements about homework help.

jlm699 320 Veteran Poster

Each tuple in that list has an instance of scrobble.Track, which contains an instance of scrobble.Artist; however the tuple itself does not have those attributes.

I'm not entirely sure on the specifics of the scrobble module, but a way to unpack the tuple would be like this:

for tracks in recent:
  track_info, track_date = tracks
  print track_info

Perhaps the scrobble.Track class has a built-in __repr__ overload so that printing the object itself will result in 'Groove Armada' - 'Hands of Time' instead of <scrobble.Track(<scrobble.Artist(u'Groove Armada') - u'Hands of Time') Although, perhaps once you have that tuple unpacked you can use something like track_info.Artist .. I guess it will take a little experimenting

jlm699 320 Veteran Poster

Here's a way:

shape = 0
while shape != 4:
    # Your existing code can go here

Just slap that -blam- into a while loop and you've got a class 5 repeater.

jlm699 320 Veteran Poster

Ok I have a while loop set but can you guys give me an example of a while loop that takes information, reads the more specific detail and then another specific detail? In my code I cant figure out how to make the loop search another line or sentence. All it does is keep looping the first information and specific detail.

I think I get it... but does this answer your question?

>>> in_data = """Some details are hidden
...     Many details are obvious
...     Yet many more details remain obscure
...     Such is the burden of seeking details
...     Let the chips fall where they may"""
>>> for line in in_data.split('\n'):
...     if line.find('details') != -1:
...         print line[ line.find('details') + len('details') + 1 : ]
...     
are hidden
are obvious
remain obscure

>>>

But seriously, wtf are you talking about? A little more detail and maybe the code that you've already worked on would help clarify your question

jlm699 320 Veteran Poster

"cross platform (windows + linux)"
This is possible. What you have to keep in mind, that if you are creating some GUI (with TkInter e.g) then it looks quite differentwith windows and linux, so you maybe could test the "look&feel" of your work with both os

I'd go with wxPython for the GUI, as it's already designed with cross-platform apps in mind. The GUI that you create appears native to any system that the app is run on.

I've used it before for cross-platform GUIs and they've all turned out to be beautiful on all the platforms that I tested (win, *nix)

scru commented: our ideas of "beautiful" are very different. +6
jlm699 320 Veteran Poster

You're not multiplying by 2^16 and 2^8 you're shifting by 16 and 8 bits, respectively.

By doing so (and then adding), you're able to fit the two letters into a single 16 bit block... or something like that.

jlm699 320 Veteran Poster

After you perform x = s.find("<img") you will receive an index. Feed this index into the find function when looking for your closing parenthesis and it will give you the ending index. You can then use the two indexes to slice out the image source URL here's an example (off the cuff)

img_tag_idx = s.find("<img")
start_idx = s.find("\"", img_tag_idx + 1)
end_idx = s.find("\"", start_idx + 1)
url = s[ start_idx + 1 : end_idx ]

But really this is not a very good method, as you should use a regex or an HTML parsing module, as the many variations in how people code HTML could easily throw this off.

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

Running it as a service works great!!! thanks for the help

What did you do to get it running as a service?

jlm699 320 Veteran Poster

I notice that your condition 3 is missing a continue statement...

To answer your question however, you should check to see if intWork is greater than 40 and if it is, calculate the overtime based on the number of hours over 40 that the employee worked.

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

the script still doesn't work

What doesn't work? If you are getting error messages please paste the traceback here.

jlm699 320 Veteran Poster

Well I notice in your maze class under the rfindPath function you have the following comparison: if(self.theMaze[i][j] == ' *') ; hoewver none of the entries in the maze EVER have an asterisk in them. Did you mean this to be a wildcard?

In your maze class under the main function you should also test this "solve" method and just work on that until you get it working. That should get you on your way.

jlm699 320 Veteran Poster

You're looking to remotely shutdown a linux server? Or to quit a python program? sys.exit(rtn_code) can exit a python program... but I'm not sure if that's what you're looking for.

jlm699 320 Veteran Poster

Oh whoops, sorry I meant exec... I always mix the two up. Use it like the following:

>>> apple1
Traceback (most recent call last):
  File "<input>", line 1, in <module>
NameError: name 'apple1' is not defined
>>> for x in xrange(1,6):
...     exec 'apple%s = %s' % (x, x * 2.5)
...     
>>> apple1
2.5
>>> apple2
5.0
>>> apple3
7.5
>>> apple4
10.0
>>> apple5
12.5
>>>

If you go the list route, there's a random.shuffle function in the random module. Additionally you can use each list element as the "name" for the variables like so:

>>> my_objects = []
>>> class test_class(object):
...     def __init__(self, param1):
...         self.p1 = param1
...     def test(self):
...         print 'Hi, my p1 is %s' % self.p1
...     
>>> for x in xrange(1,6):
...     my_objects.append(test_class('Test%s' % x))
...     
>>> my_objects
[<__main__.test_class object at 0x01D49BB0>, <__main__.test_class object at 0x01D49E30>, <__main__.test_class object at 0x01D49E70>, <__main__.test_class object at 0x01D49EB0>, <__main__.test_class object at 0x01D49A30>]
>>> for each_object in my_objects:
...     each_object.test()
...     
Hi, my p1 is Test1
Hi, my p1 is Test2
Hi, my p1 is Test3
Hi, my p1 is Test4
Hi, my p1 is Test5
>>> my_objects[2].test()
Hi, my p1 is Test3
>>>
jlm699 320 Veteran Poster

First things first, self.theMaze[i][j] == ' v' is a comparative statement. Double '=' compare two values while a single '=' assigns variables. So change that to self.theMaze[i][j] = ' v' I would suggest putting some tracing print statements throughout your maze class to verify that things are working the way you expect... I noticed that you mix up a single space and double spaces in your maze class which will definitely always fail, ie: ' v' is not equal to ' v' ... This comparison will always fail.

jlm699 320 Veteran Poster

This code doesn't really do anything for me... can you explain the concept a little bit? When none of the menu choices do anything except for the 'new maze' bit.

Printing shows the maze but neither solve nor "Remove v's" does anything whatsoever. I'm not getting errors though...

jlm699 320 Veteran Poster

how can i create 50 apples at different positions on screen without having to each time call the constructor 50 times?

Just put the call to the Apple constructor within your for loop and randomize the values a bit... or use a linear approach to the values... or whatever suits your purposes.

If you need to retain the object handles for each Apple object you can use a list and just use something like apple_list.append(Apple(x,y,z,w)) . Or you could use a combination of eval() and string formatting to generate variable names like my_apple1, my_apple2, etc.

Do you understand what I'm suggesting?

jlm699 320 Veteran Poster

I don't understand... is there a question hidden within these cryptically edited posts?

jlm699 320 Veteran Poster

Beautiful Soup. If you search this forum there's plenty of examples using it, as well as the numerous other parsers out there.

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

You could use the python debugger to put a break statement I guess? I'm not terribly versed in using it, but from my limited exposure I know that you can put break statements and step through loops, etc. just like most other debuggers. In order to use it you have to import pdb into your program... Here's some docs

jlm699 320 Veteran Poster

You can certainly add things to a file and then import functions selectively within your other programs. If you create classes it will give you even more power behind importing those functions. All depends on how exactly you're looking to do it!

jlm699 320 Veteran Poster

I'm very new to python, so this is very basic. I'm using the same basis i used on an add row program, which is probably why it comes up adding a row. When i read it back to myself, it seems to make sense. Thanks in advance for any help.

def add_column(matrix):
    """
      >>> m = [[0, 0], [0, 0]]
      >>> add_column(m)
      [[0, 0, 0], [0, 0, 0]]
      >>> n = [[3, 2], [5, 1], [4, 7]]
      >>> add_column(n)
      [[3, 2, 0], [5, 1, 0], [4, 7, 0]]
      >>> n
      [[3, 2], [5, 1], [4, 7]]
    """

    rows=len(matrix)
    columns=len(matrix[1])
    new_matrix = []
    for columns in range(rows):
        new_matrix = matrix + [(1 * [0]) * rows] 
    return new_matrix

if __name__ == '__main__':
    import doctest
    doctest.testmod()

this is what comes up when i run it:

>>> ================================ RESTART ================================
>>> 
**********************************************************************
File "__main__", line 4, in __main__.add_column
Failed example:
    add_column(m)
Expected:
    [[0, 0, 0], [0, 0, 0]]
Got:
    [[0, 0], [0, 0], [0, 0]]
**********************************************************************
File "__main__", line 7, in __main__.add_column
Failed example:
    add_column(n)
Expected:
    [[3, 2, 0], [5, 1, 0], [4, 7, 0]]
Got:
    [[3, 2], [5, 1], [4, 7], [0, 0, 0]]
**********************************************************************
1 items had failures:
   2 of   5 in __main__.add_column
***Test Failed*** 2 failures.
>>> *******************************************

Note the usage of code tags and icode tags are as follows:
[code=python] # Block of code goes here

[/code]
For inline code you'd use [icode] # Short code statement [/icode]

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
###Programmer Brian Austin
###FOP
###3/30/09
###Assignment 8
###Using a loop, allow the user to input as many student names as they like and store the names in a list. in title format
#then write the list of names to a file named NAMES.
#Read your file back into a list and sort the list.
#Write the sorted list to a different file named SORTEDNAMES.
#Read in and print (on the screen) all the names of the SORTEDNAMES file.
#Add logic to handle file I/O error exceptions.  You should include ALL I/O operations inside exception handling (open, read, write and close)



import cPickle
any_listnames=open("NAMES.TXT","w")
NAMES_list=["John", "Mary","Scott","Curly","Moe","Jon Doe"]
NAMES_file.close()
NAMES_list=cPickle.load(NAMES.file)



anylistnames=(raw_input("Enter as many student names as you have"))

print ("\nReading the entire file into a list.")
for line in anylistnames:
    print line
    

try:
    name= int(raw_input("Enter a name"))
except:
    
def _init_(names):
    

any_listnames=(NAMES.readlines.sort())
any_listnames.writelines(NAMES.title())
NAMESfile=open("NAMES.txt","r")
all_the_data=NAMES.read()
NAMES.close()
textfile = open("NAMES.txt", "r")
all_the_data=anyNAMES.read()
NAMES.close()
lines = NAMES.readlines()
print lines
print len(lines)
for line in lines:
    print line
NAMES.close()
print "Opening and closing the file."
anylistnames= open("names.txt", "r")
namesfile.close()
print "\nReading the entire file at once."
anylistnames_file = open("names.txt", "r")
whole_thing = names_file.read()
print whole_thing
namesfile.close()
for line in any_files:
    print line
anylistnames.writelines(NAMES_file.title())
anyNAMESfile=open("names.txt","r")
all_the_data=any_namesfile.read()
anyNAMESfile.close()


try:
    name= int(raw_input("Enter a name"))
    exce[t(ValueError),e:
         print "Data entered was not a name", e
         else:
         print "The value of name is", name

If I were you I'd learn how to use something like tabNanny to check your syntax.

Your indentation is all off and you've got random code …

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
#creating a Class
#

class wpoMath(object):
    """This is a Math object"""

#main program
wpoMath1=wpoMath()
wpoMath1.talk()
def _init_(self,wpoMath):
    print "I am wpoMath object"
    self.name = wpoMath
    print wpoMath1.wpoMath
def _str_(self):
    print "Hi, I'm, wpoMath, "\n"
    self._wpoMath=wpoMath
    def get_wpoMath(self):
        return self._wpoMath
def _init_(self, plus):
    self.plus = plus
def _str_(self):
    doubled = self.plus + 1
    return doubled
def _init_(self,times):
    selftimes = times
def _str_(self):
    squared = self.times * self.times
    return squared
wpoMath = WpoMath()
wpoMath.talk()
def _init(self.wpoMath):
    print self.name
    print doubled
    print squared

Sorry, but the above code doesn't make sense... why do you keep redefining _init_ and _str_ as different things??

Also, when you try to "overload" built in functions such as init, str, repr, etc. they should have TWO underscore ('_') characters... so _init_ should be __init__, _str_ should be __str__, etc...

Also take note that on your line 15 in the example above you have print "Hi, I'm, wpoMath, "\n" , which contains an extra double quote right before the \n... that's why you can see the blue color extending all the way to the end of your code... It thinks you started a new string.

Fix your errors and re-post your code along with what you're stuck on after fixing those mistakes and we can help further.

One last thing, avoid using wpoMath and WpoMath as variables, class names interchangeably... It's best practice to do something like this:

class wpoMath(object):
     def __init__(self):
         # Something

my_object = wpoMath()

Basically, name it something completely different …

jlm699 320 Veteran Poster
import random  #Imports the random modual from the library.

def main():  #First function.
    x = 'true'
    x = 'false'
while x=='true':
    input = raw_input('Choose 1, 2 or 3')
    input = int(input)
    if input not in (1,2,3):
        print 'Invalid input, exiting program'
        x = 'false'
    else:
        PlayerChoice(input)
    print 'Lets play Paper Rock Scissors!\n'
    print '1 For Rock\n2 For Paper\n3 For Scissors\n4 To Quit'
    number=raw_input ('What do you choose? ') #Gets users input.
    pc = ComputerChoice()
    PlayerChoice(number, pc)

def ComputerChoice(): #Compuers function
    ComputerChoice = random.randrange(1, 4) #Computers random range.
    return ComputerChoice


def PlayerChoice(number, CC): #Uses the users input & compares 
    number = int(number)                             #With the computers.
    print "\n"
    if CC == 1 and number == 3:
        print 'Computer wins: Rock beats Scissors'
    elif CC == 1 and number == 2:
        print 'Player wins: Paper beats Rock'
    elif CC == 2 and number == 3:
        print 'Player wins: Scissors beat paper'
    elif CC == 3 and number == 1:
        print 'Player wins: Rock beats scissors'
    elif CC == 2 and number == 1:
        print 'Computer wins: Paper beats rock'
    elif CC == number:
        print '''Draw!''' #Trying it with 3
    elif CC == 3 and number == 2:
        print 'Computer wins: Scissors beats rock'
    elif number == 4:
        print 'Goodbye'
    else:
        print CC
        print number
    if number != 4:  
        print '\n'
        main()



#Start of program
main()

NameError: name 'x' is not defined

While you declare x = 'true' and then x = 'false' in your main() function (which makes no sense by the way, …

jlm699 320 Veteran Poster

Please provide the current state of your code and the problems that you are currently having. Please be specific and show us the exact portion of code that is broken and any error messages that you receive. Do not forget to wrap your code in code tags to preserve formatting.

As this announcement in this forum states, we will not provide homework help to those who do not show effort.

jlm699 320 Veteran Poster

This might be the easiest thing to do:

fh = open('myfile.txt')
for each_line in fh:
    print each_line.strip().replace(':', '|')
fh.close()

That'll iterate line by line through the file and print out each line only replacing all occurences of ':' with '|'...

You could alternately use methods read(), readline(), or readlines()... here's some documentation on the file object.

Hope that helps.

jlm699 320 Veteran Poster

You've got numerous indentation errors in your code as vegas seat mentioned... first off, fix your lines 2-5 above, as they need to be at the same indentation level as your first if statement... Then work from there, as you've got a LOT of work to do to get this program to pass a simple syntax check, not to mention to get it running.

Some things you need to learn and apply to this script:
- The difference between the comparative (==) and the assigning (=) usage of the equal sign
- How to compare a variable to a string
- How to use the print function
- How to call a function
- How to indent

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]