Re: [Tutor] How to verify all things are equal to one another
> Is there a more pythonic way of doing this other than, > > if (a == b & > a == c & > a == d & > a == e & > a == f & > a == g): > do stuff You don't want to use & coz its a bitwise comparison, so you should use 'and' if a == b and a == c and ... However you can also do the more intuitive: if a == b == c == d == e == f == g: do stuff Anther slightly mor flexible but much more obscure way uses comprehensions: if [item for item in [a,b,c,d,e,f,g] if item != a]: which returms an empty list(false0 if they are all equal. The comprehensions advantage is that you can keep the list separate from the check and add, remove items and it doesn't break working code, each hard coded test would need to be modified in the event of a change. Finally old assembler hackers will no doubt want to use xor: if not (a^b^c^d^e^f): do it :-) PS. The last works for primitive types but is not intended to be a serious suggestion!! HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with my python app
Hi James, I can't answer your question because I don't know anything about pygame, but your code would look a lot better if you wrote a function (handleKeyEvent() say?) to avoid repeating all that code. One of the big advantages of using functions - aside from saving typing effort - is that they make the code more readable by replacing a lot of detail with a short descriptive phrase(the functions name). The other advantage is that if the code has to be fixed you only change it in one place so there's less chance of you accidentaly missing out one of the event handlers. If the code is slightly diffeent each time - although from a quick look this doesn't seem to be the case here - you can parameterise the function so you can pass in either the changing values or some flag to indicate which variant you need. It's all part of helping us to see the wood instead of the trees... HTH Alan G. - Original Message - From: "james middendorff" <[EMAIL PROTECTED]> To: Sent: Tuesday, May 17, 2005 4:40 AM Subject: [Tutor] help with my python app > Hello, I would like to be able to use the arrow keys > to control a remote control car, which I can do but > only one key at a time. I would like to press the up > key, then while it is moving forward, press the left > or right key to turn while it is moving forward? I am > sure there are probably better ways to write the code, > I am still learning all of this. Also if this > indention is off I am including the file > thanks > > #!/usr/bin/python > import parallel > import pygame > from pygame.locals import * > > p=parallel.Parallel() > p.setData(0) > > > > > > > > def main(): > # Initialise screen > pygame.init() > screen = pygame.display.set_mode((640, 480)) > pygame.display.set_caption("James' custom RC > Car Application") > > # Fill background > background = pygame.Surface(screen.get_size()) > background = background.convert() > background.fill((250, 250, 250)) > > # Display some text > font = pygame.font.Font(None, 36) > text = font.render("Which Way? ", 1, (10, 10, > 10)) > textpos = text.get_rect() > textpos.centerx = > background.get_rect().centerx > background.blit(text, textpos) > > # Blit everything to the screen > screen.blit(background, (0, 0)) > pygame.display.flip() > > # Event loop > while 1: > for event in pygame.event.get(): > if event.type == QUIT: > return > elif event.type == KEYDOWN: > if event.key == K_UP: > background.fill((250, 250, 250)) > font = pygame.font.Font(None, 36) > text = font.render("Forward", 1, (10, 10, > 10)) > textpos = text.get_rect() > textpos.centerx = > background.get_rect().centerx > background.blit(text, textpos) > screen.blit(background, (0, 0)) > pygame.display.flip() > screen.blit(background, (0, 0)) > pygame.display.flip() > p.setData(1) > > > if event.key == K_DOWN: > background.fill((250, 250, 250)) > font = > pygame.font.Font(None, 36) > text = > font.render("Reverse", 1, (10, 10, 10)) > textpos = > text.get_rect() > > textpos.centerx = background.get_rect().centerx > > background.blit(text, textpos) > > screen.blit(background, (0, 0)) > > pygame.display.flip() > > screen.blit(background, (0, 0)) > > pygame.display.flip() > p.setData(2) > > > if event.key == K_LEFT: > background.fill((250, 250, 250)) > font = > pygame.font.Font(None, 36) > text = > font.render("LEFT", 1, (10, 10, 10)) > textpos = > text.get_rect() > textpos.centerx = > background.get_rect().centerx > background.blit(text, > textpos) > > screen.blit(background, (0, 0)) > pygame.display.flip() > > screen.blit(background, (0, 0)) > pygame.display.flip() > p.setData(8) > > > if event.key == K_RIGHT: > background.fill((250, 250, 250)) > font = > pygame.font.Font(None, 36) > text = > font.render("RIGHT", 1, (10, 10, 10)) > textpos = >
Re: [Tutor] How to convert hex representation of char? (Challenge part 8)
> onepart and anotherpart contain many hex representations of nonprintable > characters, like '\x14'. But I can't manage to convert those to the > actual nonprintable characters. Any hints on how to do this? '\x14' is the actual non printable charactewrs. If it were printable you would see its printed representation, because it isn't Pyhon showsw you the hex code as an escaped character but it is the character. You can get the numeric value using ord just as you would any other character: >>> print ord('\x14') 20 >>> print ord{'Q'} 81 so '\x14' is the character, it should just work... Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauldHTH, ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Finding word in file
> I'm making a program that opens a file and tries to find the word you specify. > I can't get it to find the word! What are you trying? You could simply read through the file line by line using the string search methods. Store the previous 2 lines then when found print the previous two lines, the current line and then read and print the next two lines. There are more sophisticated methods but that should do... > One more thing, the try: IOError won't work... I type the name of a > nonexistent file and the except won't kick in and print my error message! > while True: > file_name = raw_input("Enter the full file name: ") > f = file(file_name, 'r') > try: > IOError > except: > print "File not found. Directories are not supported" You need to catch the error not state it. try: f = file() except IOError: print 'file not' If you do want to force an error to be raised you must use raise: try: raise IOError except IOError: print 'sure enough...' See my tutorial topic on errors for more info. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python debugger under Tiger?
> Does anyone know of a Python debugger that will run under OSX 10.4? > The Eric debugger was looked at, but it's highly unstable under > Tiger. Thanks. pdb should still work. Alan g ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Finding word in file
> >What are you trying? > >You could simply read through the file line by line using the string > >search methods. Store the previous 2 lines then when found print the > >previous two lines, the current line and then read and print the next > >two lines. > > How? Does your tutorial cover that (i don't remember it doing so)? Two topics -- one on handling files the other on handling text. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Whle Loop to run again.
> I want the program to run again when i input 'run' But, It doesn't... You need another loop, or to ask for input inside the loop. If you always want 100 iterations then prompt for another hundred structure it like: run = raw_input('run or exit? ') while run = 'run': for n in range(100): coin = random.randrange(2) if coin == 1: heads += 1 else coin == 2: tails += 1 run = raw_input('run or exit? ') But if you want to check after every coin toss (as your if/elif chain code seems to suggest) but with a maximum of 100 iterations, try it this way: heads,tails = 0,0 while heads+tails < 100: coin = random.randrange(2) if coin == 1: heads += 1 else coin == 2: tails += 1 run = raw_input('run or exit? ') if run = 'run': continue else: break HTH, Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] using -i flag with '''if __name__ == "__main__":'''
> > I think this approach to debugging won't scale well and you are just > > seeing the tip of the iceberg [and more helpful stuff, snipped.] > > Thanks to you both. I think I may need to step up my "development > environment" beyond emacs and a command line. I don't see why. The very biggest systems I've ever worked on were built using an editor and command line. Emacs in particular is extra-ordinarily powerful, especially in its integration with the interpreter and debugger. Modern IDEs offer a few extra features over emacs but generally they lose out in terms of raw editing power. I missed the original part of the post that prompted your decision, but the quoted comment above suggests a new aopproach to debugging, not necessarily a new debugger... Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] "classmethods"
> Now, how do I create an instance of MyClass when calling: x = MyClass.fromfile(path) ? Why not use an instance method and just do: x = MyClass().fromFile(path) provided fromPath() returns self there should be no problem. That is, MyClass looks like: class MyClass: def __init__(self): pass def fromFile(self, fname): f = open(fname,'r') self.attribute = f.readline().strip() self.attribute1 = f.readline().strip() self.attribute2 = f.readline().strip() f.close() return self > return parameter1,parameter2,...,d Instead of returning them you store them in the object. Or am I missing something? It is possible to write true class methods but I'm not sure this is the best place to use them. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Comparing a string
> I'm tryin compare a string with a value with style of pattern-matching. > > string = 'i686' > > if string == glob.glob(i?86): Use regular expressions and turn it around: import re s = 'i686' ex = re.compile('i?86') if ex.match(s): print 'they match!' Is that what you mean? Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] printing documents
> I am writing a program to store name/contact/business transaction > information. I would like the ability to print out a form for each > client with all this stored information. Can somone point me in the > write direction for printing documents. I usually just create html files. PDF would work too but is less programmer friendly in native form. > Also I would like to take the information I input and store it as > an images. Essentially take the above mentioned document In that case I'd go with a PDF file which does both jobs in one and batch printing can be done from Acrobat using: http://www.reportlab.org/rl_toolkit.html to create the PDF and the /p flag in acrobat. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] creating files on open()
> to address in binary mode - are these things possible, or do I have to > seek() to prepend and delete to clobber? Thanks. Using seek() will not prepend it will overwrite! To prepend you will have to write out your preamble then append the existing data to that. There is no random access mechanism in Python other than seek() You can't create fixed length records and navigate through them as you can in some other languages. (you can of course use format strings to fake this but its messier than true random record access) Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python in HTML
> it would be a smart idea if I could figure out how to somehow replace > the javascript in the html with python. However, everything I've seen > online seems to require installing something on the server, which I The problem lies not on the server but on the client. JavaScript support is embedded in every popular browser so it just works, but none of them know about python. Even if they did it would require the user to have Python installed, which you can't assume. It is possible to embed python in web pages on Windows and IE, using ActiveX scripting (Now called WSH) and the winall package includes a script to activate it. However that will still require the end users to have Python installed and the WSH feature for Python turned on - quite unlikely outside a closed user community. So sadly its back to JavaScript I'm afraid. OTOH I didn't find JavaScript to be too terrible, what kind of problems are you having? PS I couldn't reply to the original message because it had beebn digitally signed. Please don't do that when posting to public mailing lists folks! (Well, not if you want a reply!) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] main()
> able to glean some information. When you call a script __name__ is set > to the "Name" of the script called. example: python Hope.py > __name__ = Hope Actually no. When you *import* a file its name is set to the file name(or more acurately the module name) When you run a file from the command line like python Hope.py then __name__ is set to __main__ > but why would I want to do this if __name__ == '__main__': So this line lets you create code that is executed when the file is run from the command line but not when the file is imported. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Debugger?
> I see so many errors when i execute my programs. > > Where can i get debugger for python? or How can i debug a prgram? import pdb gets you the standard python debugger. But IDLE and Pythonwin etc have their own builtin graphical debuggers too. But if you are getting a lot of errors the debugger is the wrong place to look. DEbuggers are for deep diagnostics when the simple things fail and usually only used on a single obscure fault at a time. To deal with lots of errors use the >>> prompt to try things out before committing them to a file. THen import the "finished" file and try exercising the functions classes one by one from the >>> prompt. Finally insert print statements at suitable points, and only after doing all of that try the debugger. The best debugger of all is the one between your ears! Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python in HTML
> specific bit of code I'm having trouble with is the part that selects a > random song from the playlist. To make sure every song is selected at > least once, i tried to copy the playlist and have it choose songs from > the copy, removing each song as it is played, and refilling the copy > when it is empty. OK, so what happened? Did you start just making the copy and playing the songs from the copy? Did that work OK? Does the random number generation work - I assume you tested that by just writing out the sequence of numbers first? And finally when you use the random numbvers to select songs does it pick the songs as you expect? I still don't know what we are looking for as a problem? But writing code in Javaript is like any other language, except the debugging environment of poorer! You start doing the easy things and build on features one by one, fixing as you go. As soon as you get a feature working put it in a function. It keeps the working code and experimental stuff separate! Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python in HTML
HI Orri, > >OK, so what happened? You still aren't telling us what happens. Its very hard to find a fault in a program when you have no idea what the problem is. The code is very likely doing what you have asked it to do, so when we read it it will seem to 'work' at a superficial level. Without a clear explanation of the problem you force the tutors to read every line closely, and speaking personally, I don't have enough free time for that, I need to know what I'm looking for. > Well, like I said, the darkplayer is on an online journal, which means > that the only output possible is modifying the option strings of songs > as they are played or something similar. I do know that the random > number generator works, and the songs played always match the option > selected. So you got a version working that played the sings in random order? Or did you write separate programs, one that demonstrated the random generator working and another that played songs with diffrerent options? > However, this was before adding the bit about copying the > songs and playing from the copy. So if you forget about playing the songs can you copy the songs and generate a random selection from the copy? Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python in HTML
> >You still aren't telling us what happens. Its very hard to find > >a fault in a program when you have no idea what the problem is. > Well, the language being Javascript, I unfortunately don't know what > happened, because there are no IDE's for Javascript; it just fails > silently, as Liam put it. OK, unlock that silence by using lots of print statements (or document.write() in Javascript terms). Check the value of the strings you are using, the current index etc by printing them on the web page. Stub out the calls to the player until you are sure you are passing the correct values in. > there was a random number generator selecting random songs directly from > the song list, meaning that songs were re-played before every song had > been played once. So it sounds like an error in the copy mechanism... Liam(?) already pointed out one possible cause, but the key to working in any language is to break the program into bite size pieces and get them working bit by bit. Sometimes that means taking out a bit that was working before. > also doesn't help that there are no Javascript IDE's available. As far > as I know, the problem lies within some small syntax error. Actually there are a few JavaScript IDEs around, Microsoft do one for example. > be a completely different problem. Due to the lack of output when > Javascript crashes, I just don't know. There is a JavaScript console that you can display and it sometimes gives you some clues too. But the best bet is lots of write() statements IMHO. Also the fact its one big file shouldn't be a problem. Provided you make liberal use of functions to encapsulate the functionality and keep those together in the head of the html then the amount of code scattered through the html should be manageable. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] __init__.py
HI Joseph, > I've seen many (python) "plugins" (some located in site-packages [windows > here]) with the name __init__.py. init.py is the file that controls the behaviour of python packages - that is collections of modules used as a single entity. Read the python docs for the fine detail, but essentially the init file often imports functions or classes that the package designer wants to appear as top level(in the package as opposed to being in a sub module). Also initialisation of package variables such as constants can be done there. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] passing variables between frames?
> want to access the values from the parent frame in the dialog. > for example say I had a listbox in the parent frame and I choose > the first entry 'a' from the list. I then launch the child > dialog and I want to put the value of the selection from the > list box into a text field - when I lauch the child dialog > a text field appears with the value '0'. From within Frame1 > I can use the getselection() function to get the listbox > selection. although in the child dialog I tried to use > Frame1.listBox.getselection() to get the selection from Frame1. > this doesn't work. not sure what to do here? any ideas? thanks. The dialog should be subclassed and you can add a parameter to the constructor. When you create the dialog pass in Frame1 as the value of your new parameter. Within the constructor assign the parameter to an attribute of the object, self.parent say. Within the event handlers in the dialog you can now reference Frame1 as self.parent. HTH Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] better resolution on time.sleep()?
> I'm running an application that has a polling loop to check a serial port > for certain signals, and on my laptop I can get about 6700 samples per > second, which (of course) consumes 100% CPU; which may impact battery life. Consuming 100% CPU won't make much difference, the CPU is running all the time anyway (when its not asleep). What will consume batteries much faster is if you are accessing hardware such as disk or modem or other power hungry devices. > Anyone know of: > > 1) a working millisleep/microsleep implementation for python 2.2+? I've never tried in Python but can you use select()? I've used it in C for short duration intervals. Just a thought. Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python won't play wav file
Joseph, I don't know if this will help or not, but some observations: > def manipulate(): > manipulate = raw_input("Type 'help' for help\nManipulate>> ") > if manipulate == "play": > w.tell() > elif manipulate == "back()": > main_menu() You expect the user to type 'play' or 'back()' One response is a command the other a pseudo function call complete with parentheses. Thats not a very consistent user experience. Also by calling main_menu from inside manipulate you are effectively using recursion as a loop. Thats OK if the number of loops is small but if this program were used over a long preiod you will eventually run out of menory. Its usually better to return a value and have a main control loop somewhere that calls the functions. For example have your main_menu function display the prompt, sanity check the input and return a valifd response from the user. Then have a single if/elif tree dispatch the appropriate function that returns success or failure. Wrap the menu and if/elif tree inside a loop that exits on error or command. That way ypur program can run indefinitely without risk of memory overflow. def main_menu(): return choice while True: choice = main_menu() if choice == 'foo': foo() elif chooice == 'bar': bar() # etc... elif choice == 'exit' break else: break > ... to play a .wav music file. I tried w.play() but got an error that > module has no attribute 'play'. Have you used dir(w) to see what it does offer? Even better what does the documentation say? Have you tried help(w)? HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Wizards in Tkinter
Your mail came as an attachment so no quoted text, but basically there are two approaches to your problem of a Wizard. In Tkinter you normally use a Frame as your main window. You can pack another Frame inside that frame with your content. When you press next simply unpack frame 1 and pack frame 2. Repeat for as many frames as your Wizard requires. (This makes going back easy too...) A second approach is to use TopLevel widgets which are normally used for modeless dialog boxes. These effctively have their own mainloop running in parallel wit the main window but in a controlled way. But creating lors of TopLevel "dialogs" is IMHO resource hungry and harder work than using multiple frames. The Frame approach also has the advantage that you can, to a degree data drive the wizard by putting references to the Frames in a dictionary or list and stepping through the sequence. That way you can easily change the sequence, reuse frames over again within the same wizard etc etc. Hope that made sense, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] xml
Hi Denise, Sounds like you need a tutor on the basics of the web rather than one on the Python aspects. It seems you are not familiar with the web terminology and therefore can't understand the explanations in the Python docs. I'll try to help with a few specifics here but you probably need to google for a web tutor somewhere. > modules it seems like I need xmlrpclib - I created a serverproxy > instance, which I want to use to talk to a server - to send it > information (in this case, a name), and return to me its response. I don't think you need this if you only want to use XML as a local storage medium. (Although a database is probably a better idea for that!) XNL serves several purposes but the one for which it was designed is as a platform independane data transport. So the expected use is for sending data between two different types of box - Windows and Linux say... Thats when you need servers and proxies and RPC (Remote Procedure Calls) etc. > (forgive my probably erroneous wording of things). It > said: "The returned instance is a proxy object with methods > that can be used to invoke corresponding RPC calls on the > remote server. So basically this thing is creating an object on your system that can talk to an object on another box somewhere (including on your own system of course!). This saves you the trouble of writing networking code, you just send messages to the local proxy object and it relays them to the remote object. But for your address book you don;t need this unless you intend to make the address list available over the network. > discovery) and fetch other server-associated metadata." > - and that sounds like what I want. Perhaps I am wrong? You might want to do that but the meta-data it refers to is data about data - for example the schema definition file that defines what your XML file looks like is an example of meta data. > Also, when I read the ElementTree page, it talked about element > instances instances of XML elements. An XML element being, basically, a single ... segment of your file. So you might have an address element with nested street and city elements. > and adding "code to load SML files as trees of Element And the above address elements form a tree structure. > objects, and save them back again" - as often happens to me (and, I > hope to other beginners), this explanation does not even tell me if it > does the same thing, or anything remotely related to what I am looking > for. When you start using a new technology its important to spend the time understanding the terminology of that tehnology, because the documentation will invariably assume you already know that. > "Both the HTTP and HTTPS transports support the URL syntax extension > for HTTP Basic Authentication: http://user:[EMAIL PROTECTED]:port/path. The > http://myname:mypass/www.mysite.com > > does not work - but I dont know a "host" or "port" ? You missed an @ sign for a start! :-) The host is the IP address part: www.mysite.com ports are optional and by default http uses port 80. But you can specify a different port and this can be useful for building a test site prior to going live, so you might specify that as www.mysite.com:8080 to use port 8080 instead of port 80. In most cases you don't need to worry about that. Finally the path is the bit after the slash and looks like a file path, but is relative to the home directory of the web site and may have html references added on to the end. > documentation is not always user-friendly for beginners!) It assumes you are a beginner to the library but not to XML and XML tutors generally assume you are new to XML not to http or HTML. So you need to start at the beginning of web technology and read your way up the tree. HTH, Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Covert numbers to hex fails
> Good evening! I am trying to pass a number variable and have it > converted to hex. Any recommendations on how to achieve this? You appear to have answered your own question below. What exactly is the problem? FAILS -- >>> value = 1234567890 >>> hexoutput = hex('%d' % (value)) WORKS - >>> hexoutput = hex(1234567890) Are you trying to insert a hex representation of the number into a string for printing? If so the easiest way is using string format characters: >>> print "In hex: %d = %X" % (42,42) In hex: 42 = 2A HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python won't play .wav file
> And if I'm on Linux or programing for Mac? Sadly sound is one of those things that tends to be system dependant. There is a Sun audio module somewhere too... On the Mac I believe its a Quicktime thing using the MacPython libraries. The good news is that I think PyGame provides a platform independant sound capability so I'd recommend that route, although I've never used it. In fact, come to think of it, in my 30 years of programming, sound is one of the few things I've never, ever worked with! (I once built a midi player on Windows using the Delphi player control but that hardly counts!) Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (no subject)
> S = [chr(x) for x in range (0,256)] > for x in S: > print x, for x in range(256): print chr(x), > The next step is to use the built-in functin ord() in order to convert each > character to an ASCII integer. That will give you the numbers 0..255 ord() is simply the inverse of chr() so that x == ord(chr(x)) > it says that it only take one argument i.e. ord('a'). How could I execute to > convert each character into an ASCII integer? The same as you did for chr(), use a loop: S = [chr(x) for x in range (0,256)] for x in S: print ord(x), But it will simply print out the list of numbers from 0..255. Do you have a purpose in mind or are you simply wanting to observe chr() and ord() in action? Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python problem
> i'm trying to write a code that handle errors help > > def print_menu(): ... Personally I try to get the menu function to return the value selected that way the meniu options and the code to check it is all wrapped up in the same place. But that is only a side issue... > while menu_choice != 5: > menu_choice = input("Type in a number (1-5):") > break > except(TypeError,NameError): You need to use try: before an except. So if you start your while loop body with a try while menu_choice != 5: try: menu_choice = input(...) if menu_choice == 1: etc... except NameError, TypeError: # handle error here break # only if you really need to.. print_menu() HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Are Empty "Placeholder" Functions possible?
> Is there a way to create an empty function definition with no lines of code > in it? In my coding style I will often do this ( in other languages ) for > RAD just to remind myself that I will need to implement the function later. > Use pass def f(): pass also works for classes: class MyClass: pass I use that a lot. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (no subject). Ord and Chr query
Hi John, > Alan I am just going through the book "Learning Python" written by Lutz and > Ascher, and this is part of one exercise. I suspected it might be something you were doing just to explore. Lutz and Ascher is a great book but they do assume some knowledge of programming and computer concepts. > putting my head around in writting even very simple script. I can see the > whole picture but have enormous problem in putting it down to paper Learning to think in the minute level of detail that a computer 'thinks' is half the battle of programming. Humans are intelligent but slow, computers are stupid but fast. You have to break every action down to the simplest level and get the sequence just right. But once you do get this stupid box responding to your every whim then it is a grat buzz! Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] better resolution on time.sleep()?
> Rumor has it that Alan G may have mentioned these words: > > >Consuming 100% CPU won't make much difference, the CPU is running all > >the time anyway (when its not asleep). > > Not mine... my laptop runs a Crusoe processor, and it can automatically > scale itself from 300Mhz to 933Mhz. It's called "LongRun" technology, Ah yes indeed, I confess I forgot about that little trick. But the real point I was trying to make was that the CPU itself is not usually the biggest drain on battery compared to HD and modems, WiFi, BlueTooth etc. If I activate my PCMCIA(??) modem my laptop life drops from 3-4 hours down to 45 minutes or so! And leaving my WiFi connection enabled on a train means I pick up any other WiFi enabled laptop and it cuts battery life by an hour compared to when I disable the WiFi... Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] pattern matching problem
> I have to write a function that will return the index of a line like this: > > gvcdgvcgdvagTVTVTVTVTVTHUXHYGSXUHXSU > > where it first becomes capital letters. I'd go with a regex search for that one... Alan g. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Formatted writing to a file
> 1. how can I format outfile so i can write multiple lines > and then apend multiple lines later before closing the file? I think you mean add a new column to the existing lines? try something like line = line + '%25s' % newdata > 2. how can I make data formatting string '%25s' intiger (in this case 25) a variable? Just create the string outsoide the formatting line: fmtString = '%%ds' % width s = fmtString % data HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Formatted writing to a file
> >Just create the string outsoide the formatting line: > > > >fmtString = '%%ds' % width > > I think it should be '%%%ds' % width Good catch Bob, you need the extra % to 'escape' the literal % character. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] increment operator
> Is there a increment operator in python similar to c++ > like so "SomeVariable++" No. There is the shorthand += assignment but no ++ So x += 1 is the closest thing to x++ HTH, Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Planning a program with algorithm?
> And I'm doing chapter4. In the book it says it's recommended to plan a prog. > with pseudocode. > > Can i just ignore it? No, pseudo code is a very powerful technique. But one of the guidelines is that every line of pseudocode should correspond to 5-10 lines of program code (which means that it depends on the language used of course - one of its weaknesses since pseudocode intended for C programmers is not of much benefit to a Python programmer!) Since anything less than about 5-10 lines of pseudoccode is pretty much pointless that means that pseudocode comes into its own when your programs get to around 30 lines of Python or bigger. Practice using psudocode in shorter programs by all means but it won't be very useful unil you start to write bigger programs. By the time your programs are several hundreds of lines long and spread over several files psueudocode becomes a very powerful techniqie of seeing the "big picture" of your programs structure. Once you get above 500-1000 lines pseudo code starts to break down again - you need pseudo code for your pseudo code!! At this point you need to start looking at higher level design techniques including diagramming tools. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Planning a program with algorithm?
> One approach you could consider is to write pseudocode, turn it into comments > and write the real code in between those. That way you get the benefits of > pseudocode (being able to spot algorithm errors at a higher level) as well as > properly commented code. Difficult portions then automatically get more > comments, while easier portions get fewer comments - just as it should be. And this is exactly what we do at work in large projects. Because pseudo code sits at the 5-10 lines of real code level it works well as comment text regardless of language and you can extract the detailed design from the code using a simple text filter like grep... The ISO 9000 quality auditors love it... Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Planning a program with algorithm?
> The textbook "How to Design Programs" focuses on a design approach to > program construction. The book's host language is Scheme, but I feel a > lot of the material is language agnostic and valuable to any programmer: > > http://www.htdp.org > I second the recommendation, but you do have to remember to ignore the heavy use of recursion if you are working in Python. Otherwise the basic concepts are very sound. And the formulistic approach to designing a function is excellent. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Strange IndexError
> Traceback (most recent call last): > File "NeedBrain.py", line 233, in update > self._isNearMarker = self._markerDist < self.STAY_MIN_DIST > IndexError: tuple assignment index out of range > > I don't see, where tuples are involved. I only compare two floats. I've Python > 2.3.4. Usually when that kind of thing happens to me I've accidentally used a comma instead of a period. Are you sure you don't have self,_isNearMarker = ... So Python sees it like a,b = True Just a thought, Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Win32 Question
> this line causes the error given above -> process.GetOwner() > #apply( process.GetOwner ) I may be barking up the wrong tree but why not just call process.GetOwner() directly? Why use apply() at all? Or is that what the comment means? That you get an error when you try to use it directly? Also checking the Win32 API it looks like: uint32 GetOwner( string User, string Domain ); expects a couple of parameters to hold the return values. I dunno how Winall handles that but it may be worth investigating. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] List processing
> I have a load of files I need to process. Each line of a file looks > something like this: > > eYAL001C1 Spar 81 3419 4518 4519 2 1 > > So basically its a table, separated with tabs. What I need to do is make a > new file where all the entries in the table are those where the values in > columns 1 and 5 were present as a pair more than once in the original file. My immediate answer would be to use awk. However if that's not possible or desirable then look at the fileinput module and the string.split function. Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Building an SQL query
> I am building a query to hit a Postgres (8.0.1) database > from Python (4.2.1) on Linux. Here's how I've been doing > it for the past year or so: > ... > query = ''' > SELECT * > FROM my_table > Its a really bad idea to use SELECT * FROM in production code. There are two main reasons: 1) If the database structure changes your code is likely to break since SELECT * does not normally guarantee anything about the order of fields returned, so if the table gets an extra field added you might find the order changing. At the very least there will be an extra item in your tuple ofvalues returned whichj may well break your code. 2) Using * also prevents the database from precompiling your query and caching it, thus you will slow down the processing by forcing a SQL compile step each time. (This is true on Oracle, DB2 and Interbase, I don't know about Postgres but assume it is similar) Of course if you are the only user and the database is small these are not likely to be major issues but if two or more apps use the same database or if many users are hitting it it could be. SELECT * is great for experimenting but in production code its much safer to explicitly list the fields that you want back. > query = ''' > UPDATE my_table > SET state = 'processed' > WHERE id IN ids_to_process > ''' > > This would, of course, set the 'state' column to 'processed' > for all of the ids in the list, but can not figure out how > to get this into a query to pass to the database. What have you tried? What happened? It should just be a case of using variable interpolation as you did for the Select. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Building an SQL query
> > SELECT * does not normally guarantee anything about the order of fields > > returned, so if the table gets an extra field added you might find the order > > I'm using SELECT * specifically for this reason! I have the query and > customer specific data layouts stored in a database and am using ADOpy > to associate the field names to locations in a data segment. Hmm, I dunno ADOpy but assume it somehow miraculously turns your data set into a dictionary of some sort? How it guesses which order the SELECT will return the fields is a mystery to me, but maybe it has knowledge of the Postgres hashing function or somesuch. > Here's what works for me (and a tip-o-the-hat to Bob Gailer for his help) > > query = '''UPDATE my_table SET state = 'processed' WHERE id IN %s''' % > str(ids_to_process) > query = query.replace('[', '(') Why not convert the list to a tuple before applying str(): str(tuple(ids_to_process)) > like to avoid recompiling the query every time this is hit). > It just hit me that we could store the field names to select > in the query right along with everything else... That's what we usually do, so that if we do need to change the data retrieved for multiple queries we only change it in one place, but still keep the predictability of defined foield names. > I think I'll try it to see what sort of increase we get > because we plan on growing our business. Unless ADOpy is very slow I wouldn't expect a huge performance increase since it will only be the compile phase, but if you hit the query a lot then maybe 5-10%. You are more likely to see the benefit in a drop CPU loading on the server. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] interactif or not
> If I invoke it in a shell.. then it can be verbose > > If it is launched from a crontab.. then it is less verbose. You need to check who the process owner is. That can be done on *Nix by reading the USER environment variable. Cron jobs are usually run under the 'cron' user I believe. Hoever that won;t work if the python script is executed in a shell script that is then executed by a user. Its usually better to make verbosity controllable by a flag - traditionally -v. Thus the default is non verbode and verbosity can be switched on(or even given any one of several levels) as desired. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Postgresql+Python -tutorial?
> I've been using MySQL up this day, but would like to convert > my program to use Postgresql. I'm curious. Why? Is there some advantage to Postgres over MySql? The reason I ask is that I am torn between these two for my own use. Up until now I've been a happy user of Intebase on both Windows and Linux but I'd like to move my Linux DB to an Opensource one and although Firebird is the obvious choice one of the big two would offer good experience(*). But which one? Oh, I can install additional modules, but it would be great if Ubuntu had them... Ubuntu??? A linux distro maybe? (*) I'm currently using SqlLite for my online tutorial on database programming but the more I use it the less I like it! To the extent that I might change to one of the others even though it means a re-write of the tutorial topic... Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about "hiding" a function/method in a class
> I haven't done much OO in Python yet. For various web apps we write, we usually > write up a DB schema in a spreadsheet. Wow! How exactly do you represent a schema in a spreadsheet? I confess I cannot conceive of such a thing. Can you send a representative sample to illustrate? > create the tables in the database. I thought it would be neat to save the > spreadsheet as a csv file and have python write the sql script. So I started to > write the Python program. You do know that there are lots of ERD programs that allow you to draw the schema as an ERD and generate the SQL DDL directly? In fact even Visio can do that. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] insering into lists through slices
> I simply fail to understand the semantics of the following piece of code. > #assuming ls=[1,2,3,4] > >>>ls[1:1]=[5,6] > #then ls becomes > >>> ls > [1, 5, 6, 2, 3, 4] > Basically, ls[1:1] returns an empty list and assigning [5,6] to > it, actually inserts the elements... but how? ls[1:1] returns whatever lies between ls item 1 and ls item 1 which is nothing. ls[1:1] = [5.6] inserts the contents of [5,6] between ls item 1 and ls item 1 - in other words at index 1 - which results in [1,5,6,2,3,4] So the behaviour of [1:1] is consistent, it refers to the items between index 1 and 1. Similarly ls[2:3] refers to whats between 2 and 3 which is 3 ls[2,3 = [5,6] replaces whats between 2 and 3 with 5,6 so the result is: [1,2,5,6,4] Note that the numbers in a slice refer to the commas not the list indexes (to take a simplistic view, for a more accurate one read the docs onslicing!) HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about "hiding" a function/method in a class
> Maybe it's not a "schema" exactly. > > |Table Name|Fields |Type |Size|Primary Key|Not Null|Unique|Foreign Key| ... > > |'s represent each cell. It's just a way to organize your thoughts, and have > something a little more readable than an SQ script for a DB schema. There's been > less than 20 tables in a database for most of these applications that we write. > It's clear enough to see the relations(there's another column references). OK, so its just a tabular version of the SQL statements, I see. I guess that works for small schenas, I tend to think in terms of several hundred tables in a schema so I forget not everyone is doing those kinds of things! > > You do know that there are lots of ERD programs that allow you to draw > > the schema as an ERD and generate the SQL DDL directly? In fact even > > Visio > Can you point me to some Open Source/Free ERD programs that work with > Postgres? I've never used Postgres but I've used several commercial tools that generate Oracle, SQL Server, Sybase, Informix, DB2, etc. So I suspect they have postgres DDL drivers too. A couple of tools that spring to mind are Popkins System Architect and ERWin. Both are commercial but ERWin can be had for less than a single day of a contractor, and Popkins for less than a week. For any serious database development they pay back almost immediately. I've used Visio too for a smaller system - about 60-70 tables and it worked OK with Oracle. Again it cost less than a day of a staffer's time never mind a contractor! > (I'll google after I send this message.) I'd certainly would like to > look at ways to do this better. I don't know of any free tools but I'll be surprised if there aren't some at least - even if just demos with limited numbers of tables. The commercial tools are so cheap(relatively) that we've never even looked for freeware... Many of the UML tools (BOrland, iLogix, Rational Rose etc) have free trial versions which might be workable, at least to prove the concept before investing real money... Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to open a telnet session and have the python programwrite to it.
> I am attempting a python program that will open a telnet session and > input the username/password, cd to a certain directory and leave the session > there. I have attempted different combinations of the os.popen etc but as > soon as the telnet window is opened the program cannot be coaxed to write to > the telnet session (window). I have attempted the telnetlib, but the > problem is that the telnet window does not show up. Try pyexpect I think you have to download it though. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Not getting what execl() should be doing...
> I'm trying to call up flac's encoder from a Python program. I believe I > should be doing it ok, but I get completely different results when doing > it by hand and from the python script. Here's the command line: > > $/usr/bin/flac --endian=little --channels=2 --sign=signed --bps=16 > --sample-rate=44100 --delete-input-file /var/data/myfile.raw > > This works fine when done by hand, and flac encodes the file. > > Inside the script, I do a fork() and then, on the child, I do: You should probably try using the popen() family of functions instead, or if on Python 2.4 the new commands(?) module. While your approach can be made to work it needs a fair amount of tweaking of environments and the like. popen otr commands should simplify life significantly. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] interactif or not
> > look to see if stdin is a tty. Unix is usually very careful about who has a > > "controlling tty" and who does not. In Python, file objects have an isatty() > > method that will return True or False. > > > > import sys > > isinteractive = sys.stdin.isatty() > > if isinteractive: > > ... > > else: > > ... > > > > tested and it works ! Aha! I knew about tty on Unix so I looked in the os module for it, I never thought of it being a file method Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] repr()
> Possibly I am missing something, but how do you use the repr() function? THere are several ways of using repr, the most common is at the >>> prompt. >>> x = 5 >>> x 5 >>> when I typed x at the >>> prompt Python called repr(x) to display the result. This can be slightly different to using print which calls str() instead of repr(). Thats why: >>> s = 'hello' >>> s 'hello' >>> print s hello >>> produce different results. The other waybthat you can use repr() is by using the backtick notation >>> print `s` 'hello' >>> Note that the quote signs are back, indicating that repr() has been used. > def myFunc(): print 'hello' > > Then run > > repr( myFunc ) > >Which returns > > '' Just as you would see if you had done: >>> def myfunc(): print 'hello' >>> myfunc '' >>> > s = repr( myFunc() ) > print s Which assigns NOne to s and then prints the repr() of None > 'None' As it should. What did you think it should do? Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] repr()
> The real question is, then, is there a way I can print the code of a > function as a string? Something like > > 'def myFunction: print "hello"' There is a module for doing black magic like that. I think it may be the one with the disassembler in it? Curious as to why you would ever want to though? It may be there's another solution to whatever the problem is. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] OO re-factoring (was Pythonese/Efficiency/Generalesecritique)
> You've certainly given me a mouthful to chew on :~) I was thinking > more in terms of "OOP is about code reuse" Thats not a good approach to OOP. Code reuse is often as easy to achieve using modules and functions. As Javier said OOP is aboiut "things" - objects. You need to build your whole design around objects communicating with each other, each with some responsibility within the program. The methods implement those responsibilities. Inheritance is a way of abstracting up from specific things to higher level things - the fact that it saves some coding sometimes is a bonus side-effect. In a perfect OO design you should be able to describe (and build) the system using entirely abstract classes, then to make it effective simple implement the sub-classes and plug them in. Its rarely as clean as that but its the goal towards which OO designers strive. > I'm not actually looking for the best approach here - rather just > trying to map a concept I'm familiar with to a new (to me) concept. Thats an OK approach, but the way to map to OOP is to: 1) say what are the objects? 2) can I group the objects into super/sub class chunks 3) what are the responsibilities of each class within my problem 4) build one class, the lowest level one, with no dependencies on the others 5) test it (at the >>> prompt?) 6) build another class with no dependencies on as yet unbuilt classes 7) test it at the >>> prompt 8) test it in in conjunction with the other classes it uses. 9) repeat 6-9 until all classes are built and tested (or enough to implement some part of your application - a "use case"). 10) build the driver program/fuinctoion/object that will pull it all together into an application. And ask questions here as you go :-) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] #3 Text problem
> Subject: [Tutor] FW: Tutor Digest, Vol 16, Issue 21, #3 Text problem Its best not to reply to the list digest header mail! If for no other reason than the fact you send the whole digest out with your mail which isn't very friendly for those still using slow dial up! :-) > I tried your suggestion but it does not work for me. I get a syntax > error at use of the first question mark when trying it in Idle. > When I try it from the desktop, it just flashes a black screen and > returns me to the desktop. Try adding a line: raw_input('Hit enter to quit') at the end of your program. It sounds like its running and exiting before you can reads it! > What is the question mark used for? I looked up the use of % and the > glossary says it returns the modulus. Thats one use but its also used for interpolating text into strings as in: s = 'A string with the number %d in it" % 42 s now contains 'A string with the number 42 in it' So the % inserts the 42 at the position marked by %d (where d=decimal digit) You can insert other type values too. This is known as a format string, try searching the help for that. > I don't understand why I would want the modulus of anything. Modulus (ie remainder part of an integer division) is very useful for all sorts ofthings in programming, I'd be surprised if you never found a use for it! :-) Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] finding path to resource files in a GUI application
> The class Goals is in a file called Help.py, located in '/gui_lib/' as > seen from my main script. > > class Goals(wx.Frame): > def __init__(self,parent,frame,title,size,pos=wx.DefaultPosition): > wx.Frame.__init__(self,parent, > -1,title,size,style=wx.DEFAULT_FRAME_STYLE) > self.frame = frame > self.cwd = os.getcwd() > > self.html = HtmlWindow(self,-1) > self.html.LoadPage(os.path.join(self.cwd,'gui_lib/Goals.html')) > Any ideas what I could use instead of os.getcwd to construct a relative > path which will work even if I port the script to an other machine? The normal way to do this on Unix is to use an environment variable. MYAPPHOME or somesuch that points to te root directory for your data. An alternative is to use a resource file .mapprc that lives in each users home directory and can thus be found with ~/.myapprc Within that file you define any settings you need including folder locations. Usually a combination of the above techniques is used, and a default myapprc(no dot) held someplace like /etc/myapp used if no environment variable is set or no valid local user file exists. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Just a Python formatting question
> And all the lines that belong to the statement also. It does not matter if > is a nested sequence. Let me lighten you: > > for i in somelist: > do_something > do_something_else > if x==y: > inside the if clause > all statements go > with 4 spaces after the if line > elif x>y: > the same here While this is good advice Python doesn't mind if the elif uses different indentation to the if. Indeed each elif block could be different, so long as its consistent within the block. But that could lead to very wierd code: if something: do a thing and this elif another : do another thing and that elif what: something here and here else: pass Now visually that's a mess but Python won't complain because each block is consistent. So to please Python be consistent inside a block, but to make it readable be consistent across all blocks! Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] learning how to use python
Hi and welcome. > I am new to programming and this is the first language that I will be > learning. I am trying to get the shell to print "hello world". > I followed all of the steps to save it and then run the file Which tutorial are you following? > to get it to print in the shell. the shell gives me an error and > also says that personal firewall software is blocking the connection. That sounds like a known problem with the latest version of IDLE. I haven't upgraded to 2.4 yet so hopefully someone else can point you at the solution. But in general when you post a message here it's worth including the code - if it's not hundreds of lines long! And also a cut n paste of the actual error message because, although they may not look friendly initially, Python errors are actually very informative once you know how to read them! Take care, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newsreader list name?
> I'm switching over from email digests to a newsreader and I can't > find a reference for this tutor list. > > For example, I have the lists comp.lang.python and > comp.lang.python.announce setup, but can't find something like > comp.lang.python.tutor? > > There must be others on this list using a newsreader and I would > appreciate the list name used. The trick is that you need to set up a new news account not the standard feed your ISP provides. The news server required is news.gmane.org And the news group you need to look for is comp.python.tutor HTH, Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can't figure out syntax error
> frustration to figure out the problem, I just began explicitly > type-casting as many variables as I could, and missed the fact that I Must be something about the mornings but I seem to be pickier then... When you say type-casting that is a C term used to describe a horrible operation that fools the C compiler into treating an arbitrary block of bits in memory as some other type from that by which it was defined. It doesn't actually change the bits at all. What Python provides is type conversion where it actually tries to convert the data into a new value. Very different things. This is best illustrated by a character. char c = '5'; // ascii value 53 int n; n = (int)c; // type cast makes n hold 53 n = atoi(c) // type convert makes n hold 5 Sorry for splitting hairs but clearing the terminology might help someone... Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newsreader list name?
> I'm on OS X 10.4.1 and downloaded Hogwasher to try. Using my ISPs > news server I found the two lists I mentioned, but I can't get > anything nntp://news.gmane.org alone or in combination with a group THe point is that you must add news.gname.org to your list of news servers. It is a new news service not available on your ISP news server. It is not just a new group. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Web browser
> What I need to do is load a web-page, enter a password-protected site > and follow certain links, it needs to have frames and follow the refresh > meta. I'm running winxp, python 2.4 Do you need to do this interactively in a browser? It sounds like scripting the process using urlib might be a better solution? > Then, I thought about using some browser with bindings. I've looked all > over and found about nothing. Mozilla and its xpcom just seems quite > hard and I'm not sure if that does the job I want. I tried finding COM > bindings in other browsers, but I coudn't understand them and make them > work... You can use COM to script IE but navigating the mysteries of COM is not easy, especoially if you haven't done it before. I suggest you look at urlib before going any further, but if you really need to have a real browser open IE may be your best bet. Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Counting MySQL Fields
> I'd like to use the result.numfields() function to count the fields on a > given table, but apparently don't quite grasp how to implement it. Below is > my lame attempt. OK, I've never use the numfields function so have no idea how it works nor why I'd want to use it but... > sql = "SELECT * FROM person order by lst_name" Oh OK, I see why - you are using * instead of named fields... > Cursor.execute(sql) > > # Fetch all results from the cursor into a sequence and close the connection > result = Cursor.fetchone() > Con.close() > > # Count the fields > result.num_fields() First of all this seems odd since, although you call the function, you aren't storing the result anywhere, even if it worked! > -- Relevant info from the resulting Traceback - > result.num_fields() > AttributeError: 'Tuple' object has no attribute 'num_fields' If results is a tuple then presumably the number of fields is just the len() of the tuple? HTH, Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] is this a bug global i ???
class A: def __init__(self,j): self.j = j def something(self): print self.j print i# PROBLEM is here there is no var i in class A but it works ??? if __name__ == '__main__': i = 10 a = A(5) a.something() > I don't define global i but it will takes var i from outside of class A. > Can somebody explain this ??? You only need to declare global if you are modifying data if you only read it there is no need for explicit global statements. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Controlling Where My Program Ends
> >>Never mind. I found it - sys.exit() You can do the same thing by raise SystemExit This avoids the need to import sys... Alan G. > >> > >>Sorry to have wasted the bandwidth/time. > >>-- > > > > > > This was in reference to a post about exiting from a program. I couldn't > > figure out why my program wouldn't let me exit from within a sub-menu of the > > console interface. Since my webmail client goofed up the "from" header, it > > never showed up, and I've cancelled it to avoid wasting everyone's time > > further. I found sys.exit() in the library reference, which allows me to do > > what I want. > > > > Don > > > > If you use the if __name__ == '__main__': idiom, then you can just use return > instead of sys.exit() > > def main(): > lotsa interesting python code > if somethinorother: > # sys.exit() > return > more interesting python code > > if __name__ == '__main__': > main() > > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] can't see emacs timer in action
> buffer/output pane before running my program, so I always do > this to start my program: > ... > ...6 steps listed > ... > This is one cycle of running. > Is that normal ??? I doubt it, I've never user python mode in emacs but I have used SQL and C++ modes and usually you just call C-c C-c from the code window and the rest all happens magically. But even if you do have to do all of that the sionple solution is to record it as a macro C-x ( keys to press here C-x ) You can execute it again with C-x e And you can save it so that it will be available next time you start emacs. You can also bind it to a shortcut of your own - after all this is emacs you can do anything! :-) > I need to make shortcut for starting interpreter do you have any idea. record and save a macro M-x apropos macro is your friend... Alan G. A one time emacs user... ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Clearing the Console Screen
> I haven't found the correct way to do this so far. There is no correct way. Every console is different so you have to adapt. That having been said Fred Lundh has written a console module that tries to hide the diffeent trminal types in a common set of commands - you can download it from his site. The other ways are: Unix/LInux/MacOS/BSD: os.system('clear') DOS/Windows console: os.system('CLS') Generic: print '\n' * 100 # a 100 line screen... Or you could find the control codes for your screen and print them as octal character codes... HTH, Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Clearing the Console Screen
> Don Parris wrote: > > Thanks! I thought there had to be a way to call the OS' clear screen > > command, but was going about it the wrong way. I was trying to use > > sys.clear instead of os.system. Would it be difficult to test the OS, > > store the result in a variable, and call the comand based on the variable > > result? Or would it be simpler to have users edit the script for their OS? You can do that and I think thats what Fred Lundh's console program does but its not as simple as that either. Some terminals won't respond to the os clear - for example som Textronic displays only clear in text mode but when in graphics mode (and many folks use them thus to use nicer fonts) they won't clear with 'clear'. The only way to do it is send the graphics control characters... > beginning to get an idea of the challenges of portability though. ;) Portability is a real pain. You can achieve 95% portability with only minimal effort but complete portability (think Palm, Paper teletype, Mainframe 3270 terminal, embedded browser interpreter etc etc) is a very elusive goal indeed. On Unix(*) you do have one other option however which is to use curses. This is a pseudo windowing system which runs on character terminals. It has a default window of the whole screen and allows accurate cursor placement, character deletion, screen clearing, instant character reading etc etc. Its a bit irksome to set up but once initialised not too hard to use. If your app does a lot of screen control - like vim or emacs say, then curses is probably the right approach. (*) There is a DOS curses available for download but I couldn't get it to work properly. The *nix curses module is part of the standard library. (THere is also an O'Reilly book on ncurses - the C version, and several online tutorials for the C version too. The Python module is a pretty straight translation of the C API to Python.) Alan G. > > Python actually gets a lot of this right, you may find it's easier than you think to write portable Python. > > Kent > > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Clearing the Console Screen
> > That having been said Fred Lundh has written a console module > > that tries to hide the diffeent trminal types in a common set > > of commands - you can download it from his site. > > The only one I can find there is for Windows: > http://www.effbot.org/zone/console-handbook.htm My bad. You are right. I've seen it used for windows console control and was told it worked for "any console", I assumed that included *nix but obviously not! Its not as impressive a feat as I thought in that case. Apologies for the bad steer. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] can't see emacs timer in action
> but I don't understand why xemacs doesn't fix C-c C-c Neither do I. BTW Do you know if this is specific to xemacs? Or does it also apply to python mode in vanilla GNU emacs too? I really should get around to loading python-mode and trying it some day... Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] max(len(item)) for cols
I have a 2D array: >>>[['1', '2 ', '3'], ['longer ', 'longer', 'sort']] > How can I get what is the max(len(item)) for the columns ? > I would like to get a list with the max_col_width values. >>> tda = [['1', '2 ', '3'], ['longer ', 'longer', 'sort']] >>> mcw = [[len(r) for r in c] for c in tda] >>> mcw [[1, 2, 5], [11, 10, 4]] >>> mcw = [max([len(r) for r in c]) for c in tda] >>> mcw [5, 11] >>> widest = max(mcw) >>> widest 11 Is that what you mean? Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Logging stdout and stderr
> I'm trying to log the results of a command that I'm running via the popen2 > module to a file, while at the same time displaying its progress on the > screen. I think you need popen3... > figure out a way to simultaneously display it to the screen, kind of like > how unix's "tee" utility works. Use tee? It's designed for this kind of thing and there are versions for Windoze too. I personally prefer to leave this kind of logging as a user option rather than embed it into my code. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] database app
> database and display customer information on web. ok, easy enough. > heres the trick. the database is MS Access. - ick. ick indeed, but maybe for different reasons... There is an ODBC database driver that you can use to access Access. But you will have to be careful about locking if the traffic is high. Access was designed as a single uuser desktop database and that legacy still shows through. The very latest versions are better but if you have more than 1 simultaneous update going on at a time I'd consider moving the database or using snapshot technology or similar, Access locks by pages (default 2K?) which can mean a lot of data rows being locked by a single update. Make sure as a minimum that you are not locking on reads! HTH, Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Layering Canvas widgets with Tkinter
- def menu(y): main.grid_remove () root.update() if y ==1: menu1() etc/... def menu1(): X=Canvas(root, width=200, height=200, bg="blue") X.grid(row=0,column=0) but2=Button(X,text="back",command=mainmenu) but2.grid() def menu2():... def menu3():... root= Tk() root.geometry('200x200') main=Canvas(root,width=200,height=200,bg="grey") main.grid(row=0,column=0) root.mainloop() I think one problem is that you initially call your canvas main. In menu() you then remove main, but you don't ever replace it. Thus on subsequent calls to menu() you are not actually removing anything! This is partly a result of you using global variables everywhere and partly a result of you mixing the object creation and their positioning in a single function. It would IMHO be better to make the menuN() functions simply return the canvas objects rather than to use grid() internally. That way you can associate them with main... That way the code changes to look something like: def menu(y): main.grid_remove () root.update() if y ==1: main = menu1() main.grid(row=0,column=0) etc/... def menu1(): X=Canvas(root, width=200, height=200, bg="blue") but2=Button(X,text="back",command=mainmenu) but2.grid() return X The other option would e to pass main into menuN() as a parameter and use that instead of X but I prefer the approach above... HTH Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Numbers & Characters As Dictionary Keys
> "raw_input", but I get "H is not defined" when I run the script. > Essentially, I'd like the user to enter a number for most items, > but use letters for "Help", "Quit", and "Back to Main". Are you sure? That kind of inconsistent input is one of the big no-nos of user interface design. It usually confuses the heck out of users! Hoewever to the problem at hand. It should just be a case of changing the keys in the dictionary. Unfortunately you've told us the problem but shown us the code that woreks, not the broken copde. So we can only guess what you might have done! But basically here is a sample program that does approximately what you want: def hello(): print 'hello' def goodbye(): print 'goodbye' menu = { '1' : ('hello', hello), 'Q' : ('goodbye', goodbye)} for m in menu.keys(): print "%s\t%s" % (m,menu[m][0]) cmd = raw_input('pick one ').upper() menu[cmd][1]() Does that help? Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Every Other
> What would be the most Pythonic way THats always going to be subjective but... > of printing (or extracting) every > other element of a list? I'd probably use range with a step of 2. for index in range(0,len(mylist),2): ptint mylist[index] Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Every Other
JOhn, > This is probably it: > >>> arr = range(20) > >>> arr[::2] You are probably right, I forgot that slicing now had a 3rd element... :-) Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] not invoking the shell from python
> input but the shell still expands out certain characters. I noticed > with python2.4. How do I bypass the shell and hand arguments directly > to the program? The first thing I'd do is create the command string before passing it to popen - that way we can debug easier by seeing exactly what is being passed through! > The problematic line in question looks like this: cmd = '''rt create -t ticket set requestor='%s' owner='%s' queue='%s' subject="%s" text="%s" status='%s' ''' % (data['requestor'], data['owner'], data['queue'], re.sub(r'\"',r'\\"',data['subject']), re.sub(r'\"',r'\\"',data['body']), data['status']) # your code was missing the closing parens above but I assume # that was just a posting error? print cmd # for debug only os.popen(cmd) See if the line you are producing is what you think it should be. Try typing it in at the shell and see if you get the same effect? Without knowing the details of your data its hard to say much more. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Numbers & Characters As Dictionary Keys
> >print "%s\t%s" % (m,menu[m][0]) > > > I am curious what the "%" by itself is doing. Its a standard string formatting operation in Python. The % operator basically says substitute the values in the folowing tuple for the marked fields in the foregoing string. The print statement above therefore is roughly equivalent to: print m + '\t' + menu[m][0] But the formatting markers allow you to add formatting data like the minimum number of characters, right/left justification, number of digits after a decimal point, hex or decimal display of numbers etc etc. Take a look in the Python docs for string formatting. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] MySQL Connection Function
> worth. I would like to create a MySQL connection function that I can just > call up whenever I need it from within an other function. Good idea! > ### The Connection Definition ### > # def mysql_Conn(): > # Create a connection object and create a cursor. > # Con = MySQLdb.Connect(host="127.0.0.1", port=3306, user="user", > passwd="password", db="chaddb_test") # email text wrap here > # Cursor = Con.cursor() return Con.cursor() > How do I get mbr_Roster() to recognize the 'Cursor' from mysql_Conn()? > Do I need to declare the cursor as a global variable? No you need to return it from your function. See the topic on modules and functions for more about returning values from functions. You might find you need to clear the cursor before using it too. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] who called the class method?
> Is there a way to test if a class method was called from an instance? I think you'll need to override the __getattr__ method. It will pick up the call and you can test whether its a class mrethod being called. I think... > What I am trying to do is if a method is called from the > class return a commanding proxy with an mock or stub type > object as the proxied object. If it is called from the > instance I want to return a proxy for the instance. I'm not quite sure I understand because you are mixing object oriented terminology with procedural programming terminology. I think you mean you want to have a class with various methods. You may or may not have instances of the class. You want to know when a method is invoked whether this was via a direct call of the class's method or via a message being sent to an instance? OR do you mean you will have an actual class method (ie static in C++/Java speak) and want to know if the activating message was sent to the class object or to an instance of the class? Or do you want to know if the class method was invoked from within another method of the same class or invoked by a message sent from an instance of another class? Those are all different scenarios which could be described by your paragraph above, which do you mean? Or is it something different again? Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Built-in modules
> nested list C# like) and I want to be able to call the class List (which is > inside the List.py) without having to copy it in every folder where I have a > script that needs this module > > Can I do that? Yes. See Kent's reply to a similar post about creating a package. You can also just copy the module file List.py into a folder that's in your search path. That works too. But calling it List is probably bad since Python already has Lists. Maybe you could rename it something like NestedList? (Whatever that is!) HTH, Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Class vs. Static Methods
> Sorry for the elementary question: I was wondering if someone could > explain the difference to me between class and static methods. Coming > from other languages, I'm used to static methods, but not "class > methods". Thanks. There probably is a deep and subtle difference in Python but to all intents and purposes they are the same thing. class method is the original and logically correct name and has been around in Smalltalk, Objective C, Lisp and most early OOP languages for a long time. It means a method of the class itself rather than of an instance and is typically used to perform an operation on the entire class - ie all the existing instances. The term 'static' comes from C++ where it refers to the fact that the code for static methods lives on the heap rather than the stack and so is persistent and the variables effectively shared - this echos C's use of 'static' variables. Java and Object Pascal copied the name from C++ and now Python seems to have adopted both names just to accomodate all tastes! Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Class vs. Static Methods
- Original Message - From: "Kent Johnson" <[EMAIL PROTECTED]> > No, a classmethod is passed the class that it is called on. > If you have an inheritance tree you don't know this with a staticmethod. Aha! Like the OP I was aware of the class/no class distinction but couldn't see how this helped since a static method implicitly knows hich class it is in. But this example shows the big difference, the static method knows its in T1 but is not aware of inheritance so will always respond as a T1. The classmethod is aware of inheritance and will respond as whatever class is being accessed. So If I have a heirarchy of shapes and want a class method that only operates on the shape class itself, not on all the subclasses then I have to use staticmethod whereas if I want the class method to act on shape and each of its sub classes I must use a classmethod. The canonical example being counting instances. staticmethod would only allow me to count shapes but class method would allow me to count all the sub classes separately. Mind you this would require reprogramming the class method for each new shape which is probably a bad idea - overriding would be a better approach IMHO... Neat, I understand, I think... Thanks Kent. Alan G. > >>> class Test(object): > ... @staticmethod > ... def static(): # no args > ... print 'I have no clue how I was called' > ... @classmethod > ... def cls(cls): > ... print 'I was called on class', cls > ... > >>> class T2(Test): > ... pass > ... > >>> t2=T2() > >>> t2.static() > I have no clue how I was called > >>> t2.cls() > I was called on class > >>> T2.cls() > I was called on class ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] List of regular expressions
> for pattern in thelist: >regex=re.compile(pattern) >if regex.match('24110'): >the_pattern = pattern >. >. >sys.exit(0) > > but in this case it will pick thelist[2] and not the list[3] as I wanted to, > how can I have it pick the pattern that describes it better from the list. Define 'better'. Both regex describe it equally well, how is Python supposed to know which one is 'better'? You have to tell it by ordering your list according to your idea of better, usually meaning most specific test first. Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Class vs. Static Methods
> class Shape(object): > _count = 0 > > @classmethod > def count(cls): > try: > cls._count += 1 > except AttributeError: > cls._count = 1 Ah, clever. This is where I thought I'd need an if/elif chain, adding a new clause for each subclass. i never thought of using a try/except to add an attribute to subclasses based on cls. I like it. Thanks again Kent. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Changing what you've already printed
> Is it possible (and easy) to change something you've already printed > rather than print again? Its possible. How easy depends on where you are printing. Using curses in a character based terminal its easy, just define the window within the screen that you want to change. Similarly any GUI toolkit will likewise be easy. But if you are uising a teletype interface you are reduced to using backspace characters and it gets messy, even with a cursor addressable screen (such as a 3270 or ANSI terminal) it still gets very hard to keep track of exactly what to erase and when. > For example, if I'm making a little noughts and crosses > game and I print the board: I'd use curses for this. Or better still a GUI. > I've programs do this on the command line in Linux, so > I assume it must be possible. Curses comes as standard on linux... Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about programmers
> What's the average age of a python user? This is my only question about > programmers themselves. > There was a thread on this on comp.lang.python recently. Try searching google groups and you should find literally hundreds of replies! >From memory average was around 30 but with a distribution from about 10 to over 70... Be really keen and write a python program to collect the answers parse out the ages and do the sums... :-) Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Changing what you've already printed
> BTW, if you happen to need this while drawing only a single line, the > "\r" char gets you at the beginning of the current line ! And '\h' should delete back one char. Between the two techniques you can control a single line, but not, sadly, a noughts and crosses board! Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Class vs. Static Methods
> This is a neat trick. But can't this also be done with a static method > that accesses a static data attribute the same way? I don't think so because the static mehod can only see the attributes of Shape not of Line. It doesn't have access to the cls value in Kent's code below... > >> @classmethod > >> def count(cls): > >>try: > >> cls._count += 1 > >>except AttributeError: > >> cls._count = 1 So if it tried to incremet count every instance of every kind of shape would increment the shape counter - which may be what you want under some circumstances, but it wouldn't know which of the subclasses was calling it so couldn't access their counters. I think thats right!? Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Changing what you've already printed
> > Curses comes as standard on linux... > > > > More seriously, I seem to recall that on the contrary, the > Windows Python distribution does not include the curses module That's correct. > have to use msvcrt[?] instead). I wonder why, because I'm pretty sure > I saw (C) curses-based applications running on Windows (NetHack is > one, AFAIK). There is a DOS implementation but a) it is not complete and b) it doesn't always work well. But the problem for Python is that until someone builds a reliable and complete C version for windoze the Python wrapper won't work... I suspect part of the problem is that the DOS terminal, even with ANSI mode switched on, which is not common nowadays, is still pretty limited compared to a VT100/200 terminal in terms of cursor control. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] samples
> What I *am* looking for, if you have it or know of anyone who does, is > *simple* source code files (preferrably the entire game's code is in > one .py file), Thats unlikely to happen because its very bad practice and Python tries to make it easy NOT to do that. Breaking code into modules makes it easier to maintain and easier to reuse. But the downside is trying to navigate it can be tricky - especially when you don;t know which one is main... Try a grep for __main__ to see if you can find the if "__name__ === " trick. Or try grep for a def main. In mainstream languages like C/Java you can use a feature of vim/emacs called tags to navigate code across multiple files, some IDEs have similar menu options, where you highlight a function call and say 'go to source' and the IDE finds the file with the definition... Makes browsing code much easier. Of course better still is a design document! > Does anyone have any little "gamelets" like these, There are several games on Useless Python, including my guessing games framework (which is from my book) and the heavily commented code is zipped up on Useless (hmgui.zip). But most of them don't use the pygame framework. HTH, Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Interesting problem
> Consider a class with a lt of properties. I would like a member > function which generates a dictionary where the keys are the property > names and the values are the property values? Use the force... :-) Since Python uses dictionaries to store all those things already there must be a suitable bit of black magic that will serve it up on a plate. Doing some reading around the innards of classes should shed light on it. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with Tkinter teachers' report program?
> suggest a way of implementing many more statements? Tabbed frames > would be a good way forward (where each tab is a school subject) but > under Tkinter they don't appear to be that easy. Faking tabbed frames is fairly easy. Baasically its two frames one on top of the other, the top one is the tab set and the bottom the tab content selected. As you click a button simply unpack the current frame an pack the new one. Remember to change the highlighting of the selected tab by changing button appearance in some way. The principle is easy even if requiring a little bit of effort. We did this with an Oracle Forms application about 12 years ago when tabbed displays were very new and very sexy! :-) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] fileinput problem
> Traceback (most recent call last): > File "./Python/fileinput.py", line 1, in ? > import sys, string, fileinput You are importing fileinput from a file called fileinput. It therefore reads your file and notices that you have no input method... Don't call your program the same name as the module! HTH, Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] MineSweeper
> How do I know which button did I click when all buttons have the same name? Put them in a matrix. ie a list of lists. Then refer to them by their position inthe lists so that the top left button is "buttons[0][0]" etc This is also how you dynamically create your screen, just iterate over the list to create and pack/grid/place each button. HTH, Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Alternative File I/O for Tuples
> arranged more like it is on the console screen - in tabbed columns. None of > the tutorial type stuff I've seen even mentions printing files, One reason is that printing is one of those things that is different on evry operating system. So tutorials (including mine) tend to steer clear of it. If you are on Unix its fairly easy to print stuff just by piping stdout to the lpr or pr commands. On Windows I tend to print by creating an HTML file and then using os.system() to print the file using my browser... On Mac tyou can use the Unix trick or convert to PDF. To do proper formatted printing on windows is inordinately difficult and involves effectively printing your page as a graphic to a printer "device context". I seem to recall someone pointing out a printer module which I meant to investigate but never got round to it, maybe trawling the archives would throw it up. > Here is some sample data from the resulting file: > > ((S'Everybody' > S'Anonymous' > Nt(S'James' > S'Austin' > S'704-111-1234' > t(S'Janet' > S'Austin' > S'704-111-1234' > > I would like to see something more like when the file is printed: > > AustinJames704-111-1234 > AustinJanet704-111-1234 > etc. This is to do with formatting the data into strings before you print it. You can use a format string to define the layout(column widths, justification, number of decimal places etc) andthen send those lines to the printer as described above. If using the HTML trick you need to add the HTML codes too, in this case you would format each row like: fmt = "%10s%10s%3d-%3d-%4d" And then print a table header followed by a loop printing each line of data followed by a close table tag, something like this: text = ''' LastFirstPhone''' for data in people: #substitute your data here text += fmt % (data[0],data[1],data[2],data[3],data[4]) text += '' prtfile = open('temp.html','w') prtfile.write(text) prtfile.close() os.system('lynx -p ./temp.html') > Is this a simple task, or am I jumping into deep water? :) > evangelinuxGNU Evangelist Given your signature its probably not too difficult, you can just send the basic text string to lpr, or use the html trick above. You might even like to investigate the use of groff to format the text instead of html - that's much nicer and the technique I actually use on Unix. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] super() and inherited attributes?
|class Parent(object): | def __init__(self, name="I am a parent"): | self.name = name | |class Child(Parent): | def __init__(self, number): | super(Parent, self).__init__("I am a child") | self.number = number | |# I would like it to produce the following: |>> c = Child(23) |>> c.name |"I am a child" I don't know the direct answer but the more common way of doing that in Python is not to use super() but just call the inherited constructor directly: Parent.__init__(self,'I am a child') SO if you just want to fix the itch use that, if you want to understand super() then that won't help and its over to someone else! :-) HTH, Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] mscvrt module question
>File "C:\Documents and Settings\Tom C\My Documents\Python projects - > Toms\quiz\quiz.py", line 13, in __main__ > KeyIn = getch() > NameError: name 'getch' is not defined > Have you actually imported the msvcrt module? And if so did you import kbhit and getch since you aren't prefixing the names with the module? Normally I'd expect to see Keyln = msvcrt.getch() > a=kbhit() > > Traceback (most recent call last): > [snip] > File "", line 0, in __main__ > NameError: name 'defined' is not defined That looks more like you tried to execute an error message by mistake! Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] HANDLING ERRORS
> numbers = {} > menu_choice = 0 > print_menu() > while menu_choice != 5: > > try: > > menu_choice = input("Type in a number (1-5):") > if menu_choice == 1: > print "Telephone Numbers:" > > except ValueError: > print "Oops! That was no valid number. Try again..." The except should align with the 'try' not the 'if' Does that help? Otherwise you need to give us a clue as to how it doesn't work. Do you get an error message? What happens? Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor