Re: [Tutor] Accuracy of time.sleep()
At 07:24 AM 12/4/2004, Dave S wrote: OK I may be pushing it, ;-) I need a script to sleep from any point to 8:05AM when in needs to re-start. [snip] If you're running on a version of windows that supports the AT command that gives you another way to do this. At a DOS prompt try AT. If you get something other than a command not found kind of error then we can do something. Let us know. Bob Gailer [EMAIL PROTECTED] 303 442 2625 home 720 938 2625 cell ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple RPN calculator
At 04:45 PM 12/4/2004, Max Noel wrote: On Dec 4, 2004, at 23:30, Alan Gauld wrote: to make it request for input(s) of say a simple math like "1 2 3 4 5 + - * /". Look at raw_input() But if you are that much of a beginner you need to take several steps back and try one of the tutorials, they all cover raw_input fairly early on... And finally doesn't RPN put the operators first? Or is it me thats getting confused fromtoo much Lisping recently?... Nope, RPN calculators (such as the HP48GX, IMHO the best calculator ever made) require you to input the operands first, then the operators. It's both easier to implement and more intuitive (not to mention way faster to both input and compute) once you've gotten the hang of it. You can probably do a very basic RPN calculator in less than a hundred lines of code, using raw_input() and a stack (well, a list's append() and pop() methods). For grins I just wrote one that takes '1 2.3 - 3 4 5 + * /' as input and prints -0.0481481 8 lines of Python. That indeed is less than 100. Took about 7 minutes to code and test. Bob Gailer [EMAIL PROTECTED] 303 442 2625 home 720 938 2625 cell ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
[Tutor] Re: Can I see it?
At 03:36 AM 12/5/2004, you wrote: Hi Bob, That is what I am looking for! A simple RPN calculator program! Can I see what you have please? That depends. Are you are working on a homework assignment? I ask because when we see several posts of a similar question we suspect it is an assignment given to a class, and our hope is to support education with guidance rather than answers. Assuming for the moment that this is homework I'd like to see what you have done so far, and where you are stuck. Then I'll give some pointers. Hints: my program uses lists, a dictionary, and imports a module named operators Bob Gailer [EMAIL PROTECTED] 303 442 2625 home 720 938 2625 cell ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
[Tutor] Re: Can I see it?
uot; command' def help_clrx(self): print 'Clear X register' def help_divide(self): print 'Divide X by Y register. Use "/" key or "divide" command' def help_enter(self): print 'Push stack up by one, last register is lost' def help_help(self): print 'Prints list of commands' def help_lastx(self): print 'Retrieves value of the X register from before the last' print 'operation and pushes it in the X register, lifting the' print 'stack.' def help_multiply(self): print 'Multiply X by Y register. Use "*" key or "subtract" command' def help_power(self): print 'Take Y to the Xth power. Use "^" key or "power" command' def help_print(self): print 'Print stack. Used mostly for debugging' def help_rdown(self): print 'Rolls stack downwards' def help_rup(self): print 'Rolls stack upwards' def help_quit(self): print 'Quit program' def help_subtract(self): print 'Subtract X from Y register. Use "-" key or "subtract" cmd' def help_xy(self): print 'Swaps X and Y registers' Bob Gailer [EMAIL PROTECTED] 303 442 2625 home 720 938 2625 cell ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Printing two elements in a list
At 08:22 AM 12/7/2004, kumar s wrote: Dear group, I have two lists names x and seq. I am trying to find element of x in element of seq. I find them. However, I want to print element in seq that contains element of x and also the next element in seq. So I tried this piece of code and get and error that str and int cannot be concatenated >>> for ele1 in x: for ele2 in seq: if ele1 in ele2: print (seq[ele1+1]) The problem here is that ele1 is a string, not an index into the list. There are a couple ways to fix this. match = False for ele1 in x: for ele2 in seq: if match: print ele2 match = False if ele1 in ele2: print ele2 match = True OR for ele1 in x: for index, ele2 in enumerate(seq): if ele1 in ele2: print ele2, seq[index+1] [snip] Bob Gailer [EMAIL PROTECTED] 303 442 2625 home 720 938 2625 cell ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] "TypeError: 'int' object is not callable"??
At 11:27 AM 12/8/2004, Dick Moores wrote: My thanks to both Max and Kent. So Python tries, and fails, to see 2() as a function! I also got some help from <http://www.pcwebopedia.com/TERM/c/call.html> Note that SOME languages use () for call. There are other call constructs, such as: DO function WITH parameters (FoxPro, similar in COBOL) function parameter or parameter1 function parameter2 (APL) Bob Gailer [EMAIL PROTECTED] 303 442 2625 home 720 938 2625 cell ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] "TypeError: 'int' object is not callable"??
At 12:39 PM 12/8/2004, Bob Gailer wrote: At 11:27 AM 12/8/2004, Dick Moores wrote: My thanks to both Max and Kent. So Python tries, and fails, to see 2() as a function! I also got some help from <http://www.pcwebopedia.com/TERM/c/call.html> Note that SOME languages use () for call. There are other call constructs, such as: DO function WITH parameters (FoxPro, similar in COBOL) function parameter or parameter1 function parameter2 (APL) I should add the Python builtin function apply: apply(function, parameters...) Bob Gailer [EMAIL PROTECTED] 303 442 2625 home 720 938 2625 cell ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Please help matching elements from two lists and printing them
At 02:51 PM 12/8/2004, kumar s wrote: Dear group, I have two tables: First table: spot_cor: 432 117 499 631 10 0 326 83 62 197 0 0 37 551 Second table: spot_int 0 0 98 1 0 5470 2 0 113 3 0 5240 4 0 82.5 5 0 92 6 0 5012 7 0 111 8 0 4612 9 0 115 10 0 4676.5 I stored these two tables as lists: >>> spot_cor[0:5] ['432\t117', '499\t631', 10\t0', '326\t83', '62\t197'] Note there is no ' before the 10. That won't fly' >>> spot_int[0:5] [' 0\t 0\t18.9', ' 1\t 0\t649.4', ' 10\t 0\t37.3', ' 3\t 0\t901.6', ' 4\t 0\t14.9'] It would be a lot easier to work with if the lists looked like (assumes all data are numeric): [(432,117), (499,631), (10,0), (326,83), (62,197)] [(0,0,18.9), (1,0,649.4), (10,0,37.3), (3,0,901.6), (4,0,14.9)] What is the source for this data? Is it a tab-delimited file? If so the CSV module can help make this translation. I also assume that you want the first 2 elements of a spot_int element to match a spot_cor element. Then (for the subset of data you've provided): >>> for ele1 in spot_cor: ... for ele2 in spot_int: ... if ele1 == ele2[:2]: ... print "%8s %8s %8s" % ele2 ... 100 37.3 I want to write all the three columns of spot_int. [snip] Hope that helps. Bob Gailer [EMAIL PROTECTED] 303 442 2625 home 720 938 2625 cell ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple RPN calculator
At 06:05 AM 12/6/2004, you wrote: Bob Gailer wrote: > For grins I just wrote one that takes '1 2.3 - 3 4 5 + * /' as input > and prints -0.0481481 8 lines of Python. That indeed is less than > 100. Took about 7 minutes to code and test. I'm quite interested in seeing the sourcecode for that. I've made it interactive (enter an operand or operator and hit enter); it displays the top of the stack. I added . ^ and %. No error checking. import operator as op def rpn(o,stack = [],d = {'*':op.mul, '+':op.add, '/':op.truediv, '%':op.mod, '-':op.sub, '^':op.pow, '.':lambda x,y:x+.1*y}): if o in d: stack[-2:] = [d[o](stack[-2], stack[-1])] elif o: stack.append(float(o)) # could bomb here if input not floatable! else: return 1 print stack[-1] while 1: if rpn(raw_input('>')): break Let me know what you think. Bob Gailer [EMAIL PROTECTED] 303 442 2625 home 720 938 2625 cell ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Difference between for i in range(len(object)) and for i in object
At 09:50 AM 12/9/2004, kumar s wrote: [snip] Personally I am getting weary of a lot of requests that to me seem to come from a lack of understanding of Python.. Would you be willing to take a good tutorial so you understand basic Python concepts and apply them to your code. I also despair that you don't seem to benefit from some of our suggestions. Bob Gailer [EMAIL PROTECTED] 303 442 2625 home 720 938 2625 cell ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Difference between for i in range(len(object)) andfor i in object
At 08:27 AM 12/12/2004, kumar s wrote: Thank you for clearing up some mist here. In fact I was depressed by that e-mail I appreciate Alan's response and yours. I forgot that this was the Tutor list, as I see so many Python e-mails it is easy to get confused. Please resume seeing this list and me as resources. I regret my comments that led to your depression. because there are not many tutorials that clearly explains the issues that one faces while trying to code in python. So what can we do as a community to provide tutorials that help students like you to more easily "get it". Can you give us some ideas as to what is missing? Also I 'd be interested in knowing a bit about your academic background and field of study. Would you give us a brief CV? I taught programming for the Boeing Company. I always wondered "what are these students doing here? Why don't they just read the book?" That's how I learned almost everything I know about programming. So it can be hard for me to understand your struggle. Nuf said for now... [snip] Bob Gailer [EMAIL PROTECTED] 303 442 2625 home 720 938 2625 cell ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Leading zero for hex numbers
At 06:47 PM 12/15/2004, Tony Cappellini wrote: I'm trying to get Python to automatically print a leading 0 for hex numbers, but it only seems to work for for decimal numbers. Oh? print "%0d" % 12345 gives me 12345 - no leading 0 print "0x%0X" % 12345 displays 0x3039 which it should instead of 0x03039 and print "0x%05X" % 12345 displays 0x03039 The Python docs state The conversion will be zero padded for numeric values, when a 0 is used as a flag between the % and the conversion type. If you continue in the documentation right after 3 Conversion flags comes 4 Minimum field width Bob Gailer [EMAIL PROTECTED] 303 442 2625 home 720 938 2625 cell ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] am I missing another simpler structure?
At 09:14 PM 12/15/2004, Tim Peters wrote: [Brian van den Broek] > in Marc's check_range thread, I had proposed: > > def check_in_range(value): > > in_range = False > if 9 < value < 90: > in_range = True > return in_range > > and DogWalker suggested the better: > > def check_in_range(value): > return 9 < value < 90 > > As I mentioned, I feel as though I have a mental block getting in the > way of coming up with code in the smoother fashion of the second snippet > above. Don't feel frustrated -- using Boolean expressions idiomatically is very much a learned skill. So is adding integers, but *that* got drilled into you over years, and years, and years. It won't take quite as long to sling bools . The worst abuse is one you're perhaps not prone to: having a Boolean expression e, and then writing if e == True: instead of if e: For some reason, that's extremely common in code written by newcomers to Pascal. Not to mention coding examples provided by Microsoft in some help topics! [snip] Bob Gailer [EMAIL PROTECTED] 303 442 2625 home 720 938 2625 cell ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question on "import foobar" vs "from foobar import *"
Eric Pavey wrote: I should add (that as I understand it), when you do a 'from foo import blah', or 'from foo import *', this is doing a /copy/ (effectively) of that module's attributes into the current namespace. Not a copy (which means duplicating the attribute) but a new reference to the original attribute. Example >>> import sys >>> from sys import modules >>> sys.modules is modules True >>> m = dict(sys.modules) # create a copy >>> m is modules False -- Bob Gailer Chapel Hill NC 919-636-4239 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with random.randint
David wrote: Hello list, I thought this was easy even for me, but I was wrong, I guess. Here is what I want to do: take two random numbers between 1 and 99, and put them into a list. [snip] Or you can use list comprehension: terms = [random.randint(1, 99) for i in range(2)] or if you seek terseness: terms = [random.randint(1, 99) for i in 'ab'] -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with random.randint (cont. -- now: pseudo code)
David wrote: [snip] My suggestion (untested): MAX = 12 NQ = 20 # of questions to ask # create a 2 dimensional array of 1's row = [1]*MAX pool = [row[:] for i in range(MAX)] incorrect = [] # store incorrectly answered combos here def askQuestions(): # generate and ask questions: for i in range(NQ): while 1: # loop till we get an unused combo x, y = [random.randint(1,MAX) for i in 'ab'] if mtable[x][y] == 1: # combo is available break askQuestion(x,y) # indicate asked mtable[x][y] = 0 mtable[y][x] = 0 showStats() def askQuestion(x,y): solution = x*y # take answer from user ok = user answer == solution if ok: correct += 1 else: incorrect.append((x,y)) return ok def askFaultyAnswers(): answer = raw_input("Try again the incorrect questions? (y/n) ") if answer == "y": correct = 0 for x,y in incorrect: ok = askQuestion(x,y) # could use ok to remove combo from incorrect list. showStats() askQuestions() askFaultyAnswers() print "good-bye!" I think it is sensible to * first create all possible solutions, then * kick out doublettes, and only then * ask questions I have some questions though: Is the overall structure and flow of this program okay? What are the main problems you can spot immediately Calculating kicking randomizing is overkill. My code uses a 2 dimension array to track which x,y combos are available. break is only valid within a loop. Recursively calling askQuestions is not a good idea. Save recursion for when it is is meaningful. Use a loop instead. There is no need for an incorrect counter. we can calculate it later (incorrect = NQ -correct) In the very end I would like to take this code as a basis for a wxPython program. Are there any structural requirements I am violating here? Not that I can see. It is common practice to separate logic from display. If I want to limit the number of questions asked, say to 20, would I operate with slicing methods on the randomised pool? My solution does not use a randomized pool. Just a loop over range(NQ) How would you go about showing stats for the second run (i.e. the FaultyAnswers)? Right now I am thinking of setting the global variables correct and incorrect to 0 from _within_ askFaultyAnswers; then I would run showStats() also from _within_ askFaultyAnswers. Good idea? Yes indeed. That is what I did before reading your comment! Great minds think alike. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] rstrip in list?
Ken G. wrote: I printed out some random numbers to a list and use 'print mylist' and they came out like this: ['102\n', '231\n', '463\n', '487\n', '555\n', '961\n'] I was using 'print mylist.rstrip()' to strip off the '\n' but kept getting an error of : AttributeError: 'list' object has no attribute 'rstrip' rstrip is a string method, not a list method. You must apply it to each element in the list. One way is: print [item.rstrip() for iten in mylist] -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Defining operators for custom types
Mark Young wrote: I created a custom vector type, inheriting from object, and defined __mul__, __add__, etc. Unfortunately, the operators only work if I type "vector * (int/float/number)", in that exact order. My program produces an error if I instead type "number * vector". Use __rmul__, __radd__, etc. This makes sense to me, because I haven't told the number (int, float, whatever) how to deal with an object of type vector, (At least, I think that's why it doesn't work.). Is there any way to allow "number (operator) vector", short of modifying the standard types' behavior? Here's an example of the error. vec1 = vector(5,6,7) >>> vec1 * 2 (10, 12, 14) >>> 2 * vec1 Traceback (most recent call last): File "", line 1, in 2 * vec1 TypeError: unsupported operand type(s) for *: 'int' and 'vector' I'm using python 3.1. Thanks. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Input() is not working as expected in Python 3.1
Yaraslau Shanhin wrote: > Hello All, Hello. Suggestion for future questions - just include enough to identify the problem. We don't need to know that this is from a tutorial or what the exercise is. Also (at least I prefer) plain text without formatting or color. Sufficient therefore is: --- using Python 3.1: text = str(input("Type in some text: ")) number = int(input("How many times should it be printed? ")) Traceback (most recent call last): File "test4.py", line 2, in number = int(input("How many times should it be printed? ")) ValueError: invalid literal for int() with base 10: --- Now carefully read the message "invalid literal for int()". This tells you the argument to int is not a string representation of an integer. There is nothing wrong with input()! Since we don't know what you typed at the input() prompt we can't diagnose it further. One way to solve problems like these is to capture and print the output of input(): text = str(input("Type in some text: ")) snumber = input("How many times should it be printed?") print snumber A good robust alternative is to try int() and capture / report the failure: text = str(input("Type in some text: ")) snumber = input("How many times should it be printed?") try: number = int(snumber) except ValueError: print(number, "is not an integer.") else: print (text * number) -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python 3.0
On 2/20/2010 5:52 AM, Paul Whittaker wrote: Using the following script, the (Windows 7) PC echoes the key presses but doesn't quit (ever!) import msvcrt print('Press SPACE to stop...') while True: k = msvcrt.getch() # Strangely, this echoes to the IDLE window if k == ' ': # Not recognized break According to the docs: "msvcrt.getch() - Read a keypress and return the resulting characterThis call will block if a keypress is not already available, but will not wait for Enter to be pressed. If the pressed key was a special function key, this will return '\000' or '\xe0'; the next call will return the keycode. The Control-C keypress cannot be read with this function." IOW - getch always returns 1 character. You are testing for a 0 length string. Will never happen. What keystroke do you want to break the loop? -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] List append method: St Petersburg Game
On 2/20/2010 7:43 AM, AG wrote: Hi Pythonistas I am having difficulty with applying the list.append(x) method to produce a list that will contain outputs which will become coordinates for a later call to Matplotlib. Perhaps someone here can help me figure this out? Please let me know how I can clarify my question 1 - You are giving way too much information. We do not need to know the rules of the game or all the code. Our time to read email is limited. The less you tell us that is not relevant the better. Also you don't show the code for the "next level of complexity". What you should show us is: for i in range( 0, 10 ): some lists are initialized and appended to. What are they and how are they appended? #Main function: def flipCoin(): coinToss = random.randrange(1, 3) return coinToss # Storage of output toss_list = [] # Get things going flipCoin() # Want to capture the coin lands heads (2) while flipCoin() != 2: toss_list.append("Tails") flipCoin() 2 - The most obvious problem is here: flipCoin() while flipCoin() != 2: toss_list.append("Tails") flipCoin() The result of the first call to flipCoin is ignored. Each cycle of the loop results in 2 calls to flipCoin. The result of the 2nd call is ignored. The overall purpose of the game is, for this discussion, irrelevant, but some background info will be helpful I think. The above program will give one run only and produces the output I expect. Then your expectation is misguided, given my comments regarding multiple calls to flipCoin! You don't actually know how many tosses were made! [snip] -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Understanding (Complex) Modules
Clarifications: A module is a file. It may or may not contain python code. If it does not an exception will be raised when importing. Import executes the module's code exactly the same as if the module had been run as a script (main program). References to module objects are stored in a dict (sys.modules)s. You will notice many modules that have been "pre-imported": >>> import sys >>> for x in sys.modules.keys(): print x ... 'copy_reg' 'sre_compile' 'locale' '_sre' 'functools' 'encodings' 'site' '__builtin__' 'operator' '__main__' 'types' 'encodings.encodings' 'abc' 'encodings.cp437' 'errno' 'encodings.codecs' 'sre_constants' 're' '_abcoll' 'ntpath' '_codecs' 'nt' '_warnings' 'genericpath' 'stat' 'zipimport' 'encodings.__builtin__' 'warnings' 'UserDict' 'encodings.cp1252' 'sys' 'codecs' 'os.path' '_functools' '_locale' 'signal' 'linecache' 'encodings.aliases' 'exceptions' 'sre_parse' 'os' >>> So all import sys does is: sys = sys.modules['sys'] Whereas import foo (assuming we refer to foo.py): if 'foo' in sys.modules: foo = sys.modules['foo'] else: compile foo.py if successful: execute the compiled code thus creating a module object if successful: sys.modules['foo'] = the new module object foo = sys.modules['foo'] Herelin lies a gotcha: import foo again does NOT recompile; it just reassigns foo = sys.modules['foo']. reload(foo) will go thru the compile execute assign sequence again. Notice __main__ - that is the module of the main program. >>> sys.modules['__main__'] >>> dir(sys.modules['__main__']) ['__builtins__', '__doc__', '__name__', '__package__', 'sys', 'x'] >>> -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] difflib context to string-object?
On 3/19/2010 6:55 AM, Karjer Jdfjdf wrote: With difflib.context_diff it is possible to write the context to files. difflib.context_diff(/a/, /b/[, /fromfile/][, /tofile/][, /fromfiledate/][, /tofiledate/][, /n/][, /lineterm/]) Is it also possible to do this to seperate string-objects instead of writing them to files? Take a look at the stringIO module. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Press Enter to quit. Silently maybe.
On 3/23/2010 4:47 PM, Wayne Watson wrote: I use this code to quit a completed program. If no is selected for the yes/no prompt, warning messages appear in the shell window. What is the yes/no prompt? Is it in your program or is it a feature of IDLE? What are the warning messages? I'm executing from IDLE. Is there a way to just return to the >>> prompt there? def finish(): print; print "Bye" print raw_input('Press Enter to quit') sys.exit() -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] a bug I cannot solve myself ;-)
On 3/25/2010 5:39 AM, spir ☣ wrote: Hello, I'm writing a kind of language simulation. Here, an expression like "a#3.b" maps to a NamedData node, with an attribute terms=[('.','a'),('#',3),('.'''b')]. (The lang uses '#' instead of "[...]" for item indexing.) When this node is "run", the source code maps to a name lookup operation in current scope, passing the terms attr as argument. Below the code with debug prints and the error I get and cannot understand: == class Scope(Code): ... @staticmethod def lookup(scope, terms): ''' actual data refered to by name (or context) terms''' data = scope# actually, initial container for term in terms: (sign,key) = term print data, (sign,ATTR,sign==ATTR,sign is ATTR), key if sign == "ATTR":# sign == ATTR='.' print "getAttr" data = data.getAttr(key) else: # sign == ITEM='#' print "getItem" data = data.getItem(key) ### line 82 ### return data === output === currentScope ('.', '.', True, True) a getItem ... traceback ... File "/home/spir/prog/python/claro/scope.py", line 82, in lookup data = data.getItem(key) AttributeError: 'Scope' object has no attribute 'getItem' == (Scopes actually have no getIem, they're plain symbol (attribute) containers.) There must be something such obvious I'm too stupid to see it! What do I overlook? First you assign data = scope Then you reassign data = data.getAttr(key) OR data = data.getItem(key) data no longer refers to scope! Hence the error. How can it branch to the "getItem" side of the choice? Denis ________ vit esse estrany ☣ spir.wikidot.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with loops
On 3/25/2010 11:34 AM, kumar s wrote: Dear group: I need some tips/help from experts. I have two files tab-delimted. One file is 4K lines. The other files is 40K lines. I want to search contents of a file to other and print those lines that satisfy. File 1: chr X Y chr18337733 8337767 NM_001042682_cds_0_0_chr1_8337734_r 0 - RERE chr18338065 8338246 NM_001042682_cds_1_0_chr1_8338066_r 0 - RERE chr18338746 8338893 NM_001042682_cds_2_0_chr1_8338747_r 0 - RERE chr18340842 8341563 NM_001042682_cds_3_0_chr1_8340843_r 0 - RERE chr18342410 8342633 NM_001042682_cds_4_0_chr1_8342411_r 0 - RERE File 2: Chr X Y chr1871490 871491 chr1925085 925086 chr1980143 980144 chr11548655 1548656 chr11589675 1589676 chr11977853 1977854 chr13384899 3384900 chr13406309 3406310 chr13732274 3732275 I want to search if file 2 X is greater or less then X and Y and print line of file 2 and last column of file 1: I don't understand your desired result. Could you post a very simplified example of file1 and 2 and the desired result. for j in file2: col = j.split('\t') for k in file1: Note that the first time this loop is executed it will leave file2 at eof. Subsequent executions of this loop will process no lines as file2 is at eof. cols = k.split('\t') if col[1]> cols[1]: Note that this compares 2 strings; which may not give the same result as integer comparison. if col[1]< cols[2]: print j +'\t'+cols[6] This prints a lot of duplicate lines and is slow. Is there any other way I can make it fast. In file 1, how a dictionary can be made. I mean unique keys that are common to file 1 and 2. thanks Kumar. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] inter-module global variable
On 3/28/2010 5:31 AM, spir ☣ wrote: Hello, I have a main module importing other modules and defining a top-level variable, call it 'w' [1]. I naively thought that the code from an imported module, when called from main, would know about w, but I have name errors. The initial trial looks as follows (this is just a sketch, the original is too big and complicated): # imported "code" module __all__ = ["NameLookup", "Literal", "Assignment", ...] # main module from parser import parser from code import * from scope import Scope, World w = World() This pattern failed as said above. So, I tried to "export" w: I have read the above several times. I do not comprehend your problem. Perhaps someone else will. If not please try to explain it in a different way. ALWAYS post the traceback. # imported "code" module __all__ = ["NameLookup", "Literal", "Assignment", ...] # main module from parser import parser from scope import Scope, World w = World() import code #new code.w = w ### "export" from code import * And this works. I had the impression that the alteration of the "code" module object would not propagate to objects imported from "code". But it works. But I find this terribly unclear, fragile, and dangerous, for any reason. (I find this "dark", in fact ;-) Would someone try to explain what actually happens in such case? Also, why is a global variable not actually global, but in fact only "locally" global (at the module level)? It's the first time I meet such an issue. What's wrong in my design to raise such a problem, if any? My view is a follow: From the transparency point of view (like for function transparency), the classes in "code" should _receive_ as general parameter a pointer to 'w', before they do anything. In other words, the whole "code" module is like a python code chunk parameterized with w. If it would be a program, it would get w as command-line parameter, or from the user, or from a config file. Then, all instanciations should be done using this pointer to w. Meaning, as a consequence, all code objects should hold a reference to 'w'. This could be made as follows: # main module import code code.Code.w = w from code import * # "code" module class Code(object): w = None ### to be exported from importing module def __init__(self, w=Code.w): # the param allows having a different w eg for testing self.w = w # for each kind of code things class CodeThing(Code): def __init__(self, args): Code.__init__(self) ... use args ... def do(self, args): ... use args and self.w ... But the '###' line looks like an ugly trick to me. (Not the fact that it's a class attribute; as a contrary, I often use them eg for config, and find them a nice tool for clarity.) The issue is that Code.w has to be exported. Also, this scheme is heavy (all these pointers in every living object.) Actually, code objects could read Code.w directly but this does not change much (and I lose transparency). It's hard for me to be lucid on this topic. Is there a pythonic way? Denis [1] The app is a kind of interpreter for a custom language. Imported modules define classes for objects representing elements of code (literal, assignment, ...). Such objects are instanciated from parse tree nodes (conceptually, they *are* code nodes). 'w' is a kind of global scope -- say the state of the running program. Indeed, most code objects need to read/write in w. Any comments on this model welcome. I have few knowledge on implementation of languages. ________ vit esse estrany ☣ spir.wikidot.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help
On 3/28/2010 10:00 PM, Oshan Modi wrote: i am only a novice and just started programming.. i am having trouble running a .py file in the command prompt.. if anyone of you could help? Please learn how to ask questions. In a situation like this we'd like to know what operating system you are using, which version of Python, what you are typing at the command prompt, and what happens. Otherwise we must guess, as several of us have already done. This wastes all our time. Please post answers to: operating system version of Python what you type at the command prompt what happens -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help
Thank you for specifics. Please always reply-all so a copy goes to the list. On 3/30/2010 3:41 PM, Oshan Modi wrote: I have windows 7 (ultimate), python 2.6.3... when i try to run the file echoinput.py Please post a copy of this file. it doesnt respond to the request Actually you should say "I don't get the result I expected." Since there is no Windows error message we must conclude that the program ran. .. and here's what the output is.. Microsoft Windows [Version 6.1.7600] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Users\doggie>python echoinput.py C:\Users\doggie> and i have a couple of more files in that folder and when i try to run them this is what the error looks like.. Microsoft Windows [Version 6.1.7600] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Users\doggie>python class.py python: can't open file 'class.py': [Errno 2] No such file or directory C:\Users\doggie> The message seems pretty self-evident. There is no file named class.py in c:\Users\doggie. the list does show up when i use IDLE and it is like this ** ** IDLE 2.6.3 >>> import sys >>> for i in sys.path: print i C:\Python26\Lib\idlelib C:\Windows\system32\python26.zip C:\Python26\DLLs C:\Python26\lib C:\Python26\lib\plat-win C:\Python26\lib\lib-tk C:\Python26 C:\Python26\lib\site-packages -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] what's wrong in my command?
On 3/31/2010 4:33 PM, Shurui Liu (Aaron Liu) wrote: # geek_translator3.py # Pickle import pickle # Open Dictionary geekfile = open('geekdictionary3.txt', 'r+') new_geeks = pickle.load(geekfile) geekterms = new_geeks.keys() geekterms.sort() # start choice = None while choice != "0": print \ """ Geek Translator 0 - Quit 1 - Look Up a Geek Term 2 - Add a Geek Term 3 - Redefine a Geek Term 4 - Delete a Geek Term 5 - List of Terms """ choice = raw_input("Choice: ") print # exit if choice == "0": print "Good-bye." # get a definition elif choice == "1": term = raw_input("What term do you want me to translate?: ") if term in new_geeks: definition = new_geeks[term] print "\n", term, "means", definition else: print "\nSorry, I don't know", term # add a term-definition pair elif choice == "2": term = raw_input("What term do you want me to add?: ") if term not in new_geeks: definition = raw_input("\nWhat's the definition?: ") new_geeks[term] = definition geekterms.append(term) geekterms.sort() print "\n", term, "has been added." else: print "\nThat term already exists! Try redefining it." # redefine an existing term elif choice == "3": term = raw_input("What term do you want me to redefine?: ") if term in new_geeks: definition = raw_input("What's the new definition?: ") new_geeks[term] = definition print "\n", term, "has been redefined." else: print "\nThat term doesn't exist! Try adding it." # delete a term-definition pair elif choice == "4": term = raw_input("What term do you want me to delete?: ") if term in new_geeks: del new_geeks[term] geekterms.remove(term) print "\nOkay, I deleted", term else: print "\nI can't do that!", term, "doesn't exist in the dictionary." # list of terms elif choice == "5": print geekterms # some unknown choice else: print "\nSorry, but", choice, "isn't a valid choice." # geek speak link print "\tTo learn to speak geek visit" print "\n\t\thttp://www.youtube.com/watch?v=7BpsXZpAARk"; # 133t speak links print "\n\n\tTo learn to 1337 speak visit" print "\n\t\thttp://linuxreviews.org/howtos/l33t/"; print "\n\t\t\t\tor" print "\n\t\thttp://textozor.com/hacker-text/"; # save dictionary pickle.dump(ldict, open('geekdictionary.txt', 'r+')) # close file geekfile.close() raw_input("\n\nPress the enter key to exit.") When I run it, the system gave me the feedback below: Traceback (most recent call last): File "geek_translator3.py", line 4, in import pickle File "/usr/local/lib/python2.5/pickle.py", line 13, in AttributeError: 'module' object has no attribute 'dump' I suspect that file is not the one packaged with Python. Try renaming it and rerun the program. I don't understand, I don't write anything about pickle.py, why it mentioned? what's wrong with "import pickle"? I read many examples online whose has "import pickle", they all run very well. Thank you! -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Matching zipcode in address file
On 4/4/2010 5:18 PM, TGW wrote: I wrote a script that compares two text files (one zip code file, and one address file) and tries to output records that match the zipcodes. Here is what I have so far: #!/usr/bin/env python # Find records that match zipcodes in zips.txt def main(): infile = open("/Users/tgw/NM_2010/NM_APR.txt", "r") outfile = open("zip_match_apr_2010.txt", "w") match_zips = open("zips.txt", "r") lines = [line for line in infile if line[149:154] in match_zips] # *** I think the problem is here *** Yep. You are right. Try a very simple test case; see if you can figure out what's happening: infile: 123 234 345 match_zips: 123 234 345 infile = open("infile") match_zips = open("match_zips") [line for line in infile if line in match_zips] Now change infile: 123 244 345 and run the program again. Interesting, no. Does that give you any insights? outfile.write(''.join(lines)) infile.close() outfile.close() main() I go the program functioning with lines = [line for line in infile if line[149:154] not in match_zips] But this matches records that do NOT match zipcodes. How do I get this running so that it matches zips? Thanks -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Matching zipcode in address file
Please reply-all so a copy goes to the list. On 4/4/2010 10:02 PM, TGW wrote: >/ I wrote a script that compares two text files (one zip code file, and />/ one address file) and tries to output records that match the />/ zipcodes. Here is what I have so far: />/ />/ #!/usr/bin/env python />/ # Find records that match zipcodes in zips.txt />/ />/ def main(): />/ infile = open("/Users/tgw/NM_2010/NM_APR.txt", "r") />/ outfile = open("zip_match_apr_2010.txt", "w") />/ match_zips = open("zips.txt", "r") />/ />/ lines = [line for line in infile if line[149:154] in match_zips] # />/ *** I think the problem is here *** / Yep. You are right. Try a very simple test case; see if you can figure out what's happening: infile: 123 234 345 match_zips: 123 234 345 infile = open("infile") match_zips = open("match_zips") [line for line in infile if line in match_zips] Now change infile: 123 244 345 and run the program again. Interesting, no. Does that give you any insights? I think I am just lost on this one. I have no new insights. What is the exact program that you want me to run? #!/usr/bin/env python infile = open("filex") match_zips = open("zippys") [line for line in infile if line in match_zips] print line I did what you said and I get '345' output both times. Sorry - my mistake - try: infile = open("filex") match_zips = open("zippys") result = [line for line in infile if line in match_zips] print result -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Matching zipcode in address file
On 4/5/2010 1:15 AM, TGW wrote: Sorry - my mistake - try: infile = open("filex") match_zips = open("zippys") result = [line for line in infile if line in match_zips] print result When I apply the readlines to the original file, It is taking a lot longer to process and the outfile still remains blank. Any suggestions? OK - you handled the problem regarding reading to end-of-file. Yes it takes a lot longer, because now you are actually iterating through match_zips for each line. How large are these files? Consider creating a set from match_zips. As lists get longer, set membership test become faster than list membership test. If the outfile is empty that means that line[149:154] is never in match_zips. I suggest you take a look at match_zips. You will find a list of strings of length 6, which cannot match line[149:154], a string of length 5. #!/usr/bin/env python # Find records that match zipcodes in zips.txt import os import sys def main(): infile = open("/Users/tgw/NM_2010/NM_APR.txt", "r") outfile = open("zip_match_apr_2010.txt", "w") zips = open("zips.txt", "r") match_zips = zips.readlines() lines = [ line for line in infile if line[149:154] in match_zips ] outfile.write(''.join(lines)) #print line[149:154] print lines infile.close() outfile.close() main() -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Extracting lines in a file
On 4/6/2010 2:16 AM, ranjan das wrote: Hi, I am new to python, and specially to file handling. I need to write a program which reads a unique string in a file and corresponding to the unique string, extracts/reads the n-th line (from the line in which the unique string occurs). I say 'n-th line' as I seek a generalized way of doing it. For instance lets say the unique string is "documentation" (and "documentation" occurs more than once in the file). Now, on each instance that the string "documentation" occurs in the file, I want to read the 25th line (from the line in which the string "documentation" occurs) Is there a goto kind of function in python? Others have offered linecache and seek. The simplest generic solution is: lines_to_be_read = [] for lineno, line in enumerate(open(filename)): if "documentation" in line: lines_to_be_read.append(lineno + 25) if lineno in lines_to_be_read: # process this line lines_to_be_read.pop(0) -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ask-why I cannot run it, and I am so confused about the traceback
You have the solution. Good. I beg you to avoid colored text. I find it hard to read. Just use good old plain text. No fancy fonts, sizes, colors. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Problems with creating XML-documents
On 4/14/2010 4:16 PM, Karjer Jdfjdf wrote: I'm having problems with creating XML-documents, because I don't seem to write it to a document correctly. I have to write the document from a loop: doc.write('\n') for instance in query: if doc != None: text = str('\n' + \ ' ' + str(instance.datetime) + ' \n' + \ ' ' + instance.order + ' \n' + \ '\n') doc.write(text) When I try to parse it, it keeps giving errors. I am frustrated with the lack of clarity and completeness. Please respect our time as volunteers by giving complete explicit informaion. Show us the resultant file. Tell us what parsing tool you are using. Show us the exact errors. [snip] -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Raw string
On 4/18/2010 5:49 PM, Neven Goršić wrote: Hi! When I get file path from DirDialog, I get in a (path) variable. Sometimes that string (path) contains special escape sequences, such as \x, \r and so on. 'C:\Python25\Programs\rating' When I try to open that file (whose name contains escape sequences) it doesn't work. "It doesn't work" is too vague. Please show us a code snippet that includes obtaining the file path, attempt to open and what happens. Do you get a traceback (error message)? If so, please post it with the code. Please also reply-all so a copy goes to the list. I know that raw string marker 'r' in front of string leaves char '\' as character and not as start of escape sequences, but I can not apply it to a variable name which contains file path. Is there a function with same effect as raw string marker, as my problem must be solved differently? Can you help me? Kind regards, Neven -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] List index usage: is there a more pythonesque way?
On 4/18/2010 6:53 PM, C M Caine wrote: # Example data for forms and timetable: forms = ["P7", "P8", "P9", "P10", "P11", "S7", "S8", "S9", "S10", "S11", "IMA", "CAT", "FOR", "RLS", "EMPTY"] timetable = ['CAT', 'P10', 'P8', 'EMPTY', 'EMPTY', 'EMPTY', 'S10', 'S8', 'IMA', 'EMPTY', 'S7', 'S10', 'P9', 'EMPTY', 'EMPTY', 'EMPTY', 'S7', 'EMPTY', 'EMPTY', 'RLS', 'FOR', 'EMPTY', 'EMPTY', 'EMPTY', 'S9', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'S8', 'IMA', 'S11', 'P8', 'EMPTY', 'IMA', 'EMPTY', 'EMPTY', 'S11', 'S11', 'EMPTY', 'EMPTY', 'EMPTY', 'P7', 'S9', 'P11', 'P11', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'P9', 'EMPTY', 'EMPTY', 'P8', 'FOR', 'S10', 'S11', 'S7', 'P7', 'EMPTY', 'EMPTY', 'IMA', 'EMPTY', 'S9', 'P10', 'P11', 'CAT', 'S8', 'P9', 'RLS'] def analyseTimetable(): "Find number of and spaces between each form." Consider using defaultdict in the collections module. The first time a key is referenced it is automatically added with a specified value. import collections numDict = collections.defaultdict(0) spaceDict = collections.defaultdict(0) adjustedSpaceDict = {} If you use enumerate then you can replace timetable[i] with key for i, key in enumerate(timetable): numDict[key] += 1 Something is wrong in the following if statement, as both paths execute the same code. if spaceDict['1st'+key] == 0: spaceDict['nth'+key] = i else: spaceDict['nth'+key] = i for form in forms: adjustedSpaceDict[form] = spaceDict['nth'+form] - \ spaceDict['1st'+form] return (numDict, adjustedSpaceDict) # End example This function works fine, but I think that using range(len(timetable)) is clumsy. On the other hand, I need the indexes to track the number of spaces between instances of each form. Without using another loop (so not using list.index), is there a way of getting the index of the list entries? -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] set and sets.Set
On 4/21/2010 12:28 PM, Bala subramanian wrote: Friends, Someone please write me the difference between creating set with set() and a sets.Set(). When sets were introduced to Python in version 2.3. they came as a separate "sets" module. In version 2.6 built-in set/frozenset types replaced this module. So either way is OK for now, but the sets module might go away in a newer version. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] sqrt?
On 4/24/2010 11:00 PM, Kirk Z Bailey wrote: ok gang, My desktop runs 2.5, and for my college algebra I needed to do som quadratic equation work. This involves squareroots. So I fired uop the interactive idle and imported math. I then tried to play with sqrt. Nothing. As Hugo pointed out - asking good questions is important. That includes being really specific. "play" and "nothing" are not specific. We can guess - we might even be right - but that is costly for all of us in time. Python rarely gives "nothing". You usually get some result (perhaps you don't agree with it) or some error (traceback). Sometimes there is no visible result, as the case with import. So if I were willing to spend some time guessing I'd guess that you did and got something like: >>> import math >>> sqrt Traceback (most recent call last): File "", line 1, in NameError: name 'sqrt' is not defined >>> Please either confirm or alter the above. IOW show us what you entered and what you got. Did you read the Python Manual's explanation of import? Importing math does not import a sqrt function. Not under that name, as a global variable. It did create a global name math. Math has attributes, one of which is sqrt. Now riddle me this: if string.foo makes it do a function FOO on a string Wow - so many assumptions, errors and generalities. Where would I even begin? , whyfore and howcome does math.sqrt not do square roots on a simple number like 4??? O but it does, as others have pointed out >>> math.sqrt(4) 2.0 I am now officiciously pissed. Help? -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] module import problems
On 4/25/2010 9:56 PM, Rayon wrote: I have a module with the name _table in the same directory I have another by the name of _module I would like to import _table into _module What exactly does that mean? The import statement, when executed, imports a module into the module containing the import statement. And what is the purpose of the following line? from tables.report_db_engine import * -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] For loop breaking string methods
On 4/26/2010 3:38 PM, C M Caine wrote: Why does this not work: By "work" you mean "do what I want it to do". >>> L = [' foo ','bar '] >>> for i in L: i = i.strip() This creates a new local variable named i. It does not affect L. This has nothing to do with loops nor is it strange behavior - it is expected behavior. Consider the loopless equivalent: >>> i = L[0] >>> i = i.strip() >>> L [' foo ', 'bar '] >>> L [' foo ', 'bar '] >>> # note the leading whitespace that has not been removed. But this does: >>> L = [i.strip() for i in L] >>> L ['foo', 'bar'] What other strange behaviour should I expect from for loops? None - loops do not have "strange" behaviors. Perhaps "unexpected" but that is a result of not understanding an aspect of the language. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] For loop breaking string methods
On 4/26/2010 10:19 PM, Dave Angel wrote: Note also that if you insert or delete from the list while you're looping, you can get undefined results. The results are not undefined. They m,ight be unexpected, but that is due to an invalid assumption. The behavior is explained in section 7.3 of The Python Language Reference. Note especially: """ There is a subtlety when the sequence is being modified by the loop (this can only occur for mutable sequences, i.e. lists). An internal counter is used to keep track of which item is used next, and this is incremented on each iteration. When this counter has reached the length of the sequence the loop terminates. This means that if the suite deletes the current (or a previous) item from the sequence, the next item will be skipped (since it gets the index of the current item which has already been treated). Likewise, if the suite inserts an item in the sequence before the current item, the current item will be treated again the next time through the loop. This can lead to nasty bugs that can be avoided by making a temporary copy using a slice of the whole sequence, e.g., for x in a[:]: if x < 0: a.remove(x) """ -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about Python being object oriented
On 5/8/2010 12:19 PM, Tino Dai wrote: Hi Everybody, My friend and I were having a disagreement about Python. Has Python always been an OO language or was it at one point a procedural language like C? Thanks! OO and procedural are not mutually exclusive! From http://en.wikipedia.org/wiki/Imperative_programming: "Procedural programming is imperative programming in which the program is built from one or more procedures (also known as subroutines or functions). The terms are often used as synonyms, but the use of procedures has a dramatic effect on how imperative programs appear and how they are constructed. Heavily procedural programming, in which state changes are localized to procedures or restricted to explicit arguments and returns from procedures, is known as structured programming. From the 1960s onwards, structured programming and modular programming in general, have been promoted as techniques to improve the maintainability and overall quality of imperative programs. Object-oriented programming extends this approach." -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Find Elements in List That Equal A Specific Value
On 5/12/2010 1:58 PM, Su Chu wrote: I have three lists, one with unique values (list 1), one a sequence of values that are not necessarily unique (list2), and a shorter list with the unique values of list 2 (list 3). List 1 and List 2 are of equal lengths. An example: list1 = [ 1, 2, 3, 4, 5, 6 ] list2 = [ 2, 2, 2, 5, 6, 6 ] list3 = [2, 5, 6] What I would like to do is find and sum the elements of list 1 given its corresponding element in list 2 is equal to some element in list 3. For example, the sum of the values in list1 given list2[i]==2 would be 1 + 2 + 3 = 6. the sum of the values in list1 given list2[i]==5 would be 4 the sum of the values in list1 given list2[i]==6 would be 5 + 6 = 11 and so on. Obtaining these values, I'd like to store them in a vector. result = [] for n in list3: result.append(sum(list1[x] for x in range(len(list1)) if list2[x] = n) This seems pretty simple if a 'which' statement exists e.g. (which values in list 1 == list3[k], and looping through k), but I can't find one. To write one seems to require a loop. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Trying to get this to work - attached is the source code
On 5/17/2010 10:29 AM, Peter wrote: Attached is the source code which accompanies the book and lessons. When I type it in I do not get the same result. I do not get the block lettering, or am I supposed to? Peter --- Hello, I am at the very beginning of learning Python. If anyone is familiar with Michael Dawson's book: "Python Programming for the Absolute Beginner" The following script (according to the book) should create "block lettering" created by dashes and vertical lines. If I could show a picture of it I would. -- Below I have copied and pasted what appears after running the accompanied source code. When I type it manually, I cant get it to work. What does "type it manually" mean? What does can't get it to work" mean? # Game Over - Version 2 # Demonstrates the use of quotes in strings print("Program 'Peter Stein' 2.0") print("Same", "message", "as before") print("Just", "a bit", "smaller") print("Here", end=" ") print("it is...") print( """ _ ___ ___ ___ _ / ___| / | / |/ | | ___| | |/ /| |/ /| /| | | |__ | | _/ ___ | / / |__/ | | | __| | |_| | / / | | / / | | | |___ \_/ /_/ |_| /_/|_| |_| _ _ _ _ _ / _ \ | | / / | ___| | _ \ | | | | | | / / | |__ | |_| | | | | | | | / / | __| | _ / | |_| | | |/ /| |___ | | \ \ \_/ |___/ |_| |_| \_\ """ ) input("\n\nPress the enter key to exit.") ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] what is wrong with this syntax?
On 5/18/2010 11:23 AM, Steven D'Aprano wrote: Others have already given you the answer, but more important is for you to learn *how* to get the answer. Look at the error message Python prints: for i in the range(10): File "", line 1 for i in the range(10): ^ SyntaxError: invalid syntax You get a SyntaxError, which tells you that what you've written makes no sense to the Python compiler. It also tells you that the error has nothing to do with either of the print lines. Unfortunately Python isn't smart enough to recognise that the problem is with "the" rather than "range(10)" To be more specific - Python is "happy" with "for i in the ". It is "expecting"either : or some operator. "range" is neither - so that is where the error pointer is. Example: the = [1,2,3] for i in the: print(i) for i in the + [4]: print(i) -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] loop raw input
On 5/21/2010 5:35 AM, Norman Khine wrote: hello, i have this script, but i am stuck at the loop, if the user types an incorrect database id: http://paste.lisp.org/+25D3 how would i write the exception correctly? Which line of code could raise the ValueError exception? That line should be in the try block. I also suggest unique error messages. If the user does not enter a number tell him so. Also you need a way to break out of the loop once user enters a valid key. Consider using the isdigit function to test the input instead of an exception. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] loop raw input
Also note that the database function creates a local variable "database" but does nothing with it. When the function terminates that variable is lost. Did you intend to return it? Also it is not good practice to use the same name for a function and a variable. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] parse text file
On 6/1/2010 5:40 PM, Colin Talbert wrote: I am also experiencing this same problem. (Also on a OSM bz2 file). It appears to be working but then partway through reading a file it simple ends. I did track down that file length is always 90 so it appears to be related to some sort of buffer constraint. Any other ideas? How big is the file? Is it necessary to read the entire thing at once? Try opening with mode rb import bz2 input_file = bz2.BZ2File(r"C:\temp\planet-latest.osm.bz2","r") try: all_data = input_file.read() print str(len(all_data)) finally: input_file.close() -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] parse text file
Please always reply-all so a copy goes to the list. On 6/1/2010 6:49 PM, Colin Talbert wrote: Bob thanks for your response, The file is about 9.3 gig and no I don't want read the whole thing at once. I want to read it in line by line. Still it will read in to the same point (90 characters) and then act as if it came to the end of the file. Below is the code I using for this: import bz2 input_file = bz2.BZ2File(r"C:\temp\planet-latest.osm.bz2","rb") for uline in input_file: print linecount linecount+=1 Colin Talbert GIS Specialist US Geological Survey - Fort Collins Science Center 2150 Centre Ave. Bldg. C Fort Collins, CO 80526 (970) 226-9425 talbe...@usgs.gov From: bob gailer To: Colin Talbert Cc: tutor@python.org Date: 06/01/2010 04:43 PM Subject:Re: [Tutor] parse text file On 6/1/2010 5:40 PM, Colin Talbert wrote: I am also experiencing this same problem. (Also on a OSM bz2 file). It appears to be working but then partway through reading a file it simple ends. I did track down that file length is always 90 so it appears to be related to some sort of buffer constraint. Any other ideas? How big is the file? Is it necessary to read the entire thing at once? Try opening with mode rb import bz2 input_file = bz2.BZ2File(r"C:\temp\planet-latest.osm.bz2","r") try: all_data = input_file.read() print str(len(all_data)) finally: input_file.close() -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Misc question about scoping
On 6/3/2010 11:50 AM, Tino Dai wrote: Hi All, Is there a way to express this: isThumbnail = False if size == "thumbnail": isThumbnail = True How I do that is: isThumbnail = size == "thumbnail": like this: [ isThumbnail = True if size == "thumbnail" isThumbnail = False ] and the scoping extending to one level above without resorting to the global keyword? I have no idea what you mean by that. Please provide context. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] JS for location detection
On 6/6/2010 2:29 PM, Gaurav Kalra wrote: Hi all, I was trying to get the user location based on 4 levels. 1. Try for Navigator telling the location (W3C recommendations followed) 2. In case the location is not available, fallback on Google Gears 3. Again if not available, fall back on Google Ajax API's (only for US) 4. Again if not available, use IP to location using Max-Mind Database The code that I have written is here: http://github.com/gvkalra/random/blob/master/static/js/map.js The problem I am facing: If the navigator supports location sharing, it will ask the user whether it wants to approve or not (that's okay!). If the user says NO, it is giving me the right result by falling back on 3/4 step. But, in case the user approves, the results are not being populated. Please check the code for more details (commented inline). Any suggestions ? Your question reached the Python Tutor list. This is not the appropriate place for a JavsScript question. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] JS for location detection
On 6/6/2010 6:59 PM, Alan Gauld wrote: "Gaurav Kalra" wrote The list was suggested to me by a friend and he said that it's for General Programming discussions as well. Am sorry if I broke the laws of the list. But since I have already posted, if anyone up here is with a solution; please PM me. There are no laws. By "inappropriate" I meant that 1 - you would be less likely to get an answer here. 2 - my preference is that only Python questions be asked, as it takes my time to decipher a question. I examined your code to see if it were Python related. That takes time. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] while loops causing python.exe to crash on windows
On 6/6/2010 8:44 PM, Alex Hall wrote: -- Have a great day, Alex (msg sent from GMail website) mehg...@gmail.com;http://www.facebook.com/mehgcap What is your question? -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] while loops causing python.exe to crash on windows
On 6/6/2010 9:37 PM, Alex Hall wrote: On 6/6/10, Lie Ryan wrote: On 06/07/10 11:08, Alex Hall wrote: On 6/6/10, bob gailer wrote: On 6/6/2010 8:44 PM, Alex Hall wrote: -- Have a great day, Alex (msg sent from GMail website) mehg...@gmail.com;http://www.facebook.com/mehgcap What is your question? -- Bob Gailer 919-636-4239 Chapel Hill NC Why would that code What code. I don't see any! cause Windows to consider the process "not responding", and how can I fix this so I can have a sort of "listener" in place, awaiting a change in the "grid.turnOver" variable inside Player.takeTurn() so that the main while loop can switch to the other player once the one player's turn is over? I thought while loops would do it, but Windows sees them as making python.exe unresponsive. Would you buy me a crystal ball to foresee what you're talking about? I am not sure how else to explain it. I want to loop until the value of a variable changes, but while that loop is taking place, the user should be able to perform actions set up in a wx.AcceleratorTable. Looping, though, causes Windows to tell me that python.exe is not responding, so I have to close the entire thing. I guess I am looking for a "listener", which will sit in the background and only perform an action when it detects a certain thing. In this case, a listener to watch for a variable to turn from False to True, then to act when it sees that change. We are complaining because you first send a post with no content, then one with a question but no code. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] a class query
On 6/7/2010 10:01 AM, Payal wrote: Hi all, I know the difference between class Parent : class Parent(object) : But in some softwares i recall seeing, class Parent() : Is this legal syntax? Teach: To answer that question, just try it at the interactive prompt. If it is not legal syntax you will get a syntax error! Feed: Yes Originally it was not legal. Then in some version it became legal. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Better construct? (was no subject)
On 6/11/2010 5:12 PM, Advertising Department wrote: Please supply a meaningful subject. #!/Library/Frameworks/Python.framework/Versions/Current/bin/pythonw """still thinking in imperative" """ ## obviously this is a bad construct. Why is it "obvious"? What is "this"? Are you referring to the function, to the mainline program, or what? ## Can someone suggest a pythonesque way of doing this? def getid(): response = raw_input('prompt') if response not in [ "", "y", "Y", "yes"] : getid()# ouch print "continue working" # do more stuff # do more stuff getid() dosomething() getid() dosomethingelse() ## obviously this is a bad construct. ## Can someone give me a pythonesque way of doing this? One improvement - response.lower().startswith("yes") will cover all your cases. You can collect functions in a sequence, then iterate over it. This allows for easy expansion (when you decide to add another function). funcs = (dosomething(), dosomethingelse()) for func in funcs: getid() func() -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Better construct? (was no subject)
On 6/12/2010 3:59 PM, Alan Gauld wrote: "bob gailer" wrote You can collect functions in a sequence, then iterate over it. This allows for easy expansion (when you decide to add another function). funcs = (dosomething(), dosomethingelse()) I suspect Bob meant to leave off the (). Yep. Thank you for the correction. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] large file
On 6/13/2010 5:45 PM, Hs Hs wrote: hi: I have a very large file 15Gb. Starting from 15th line this file shows the following lines: HWUSI-EAS1211_0001:1:1:977:20764#0 HWUSI-EAS1211_0001:1:1:977:20764#0 HWUSI-EAS1521_0001:1:1:978:13435#0 HWUSI-EAS1521_0001:1:1:978:13435#0 Every two lines are part of one readgroup. I want to add two variables to every line. First variable goes to all lines with odd numbers. Second variable should be appended to all even number lines. like the following: HWUSI-EAS1211_0001:1:1:977:20764#0 RG:Z:2301 HWUSI-EAS1211_0001:1:1:977:20764#0RG:Z:2302 HWUSI-EAS1521_0001:1:1:978:13435#0 RG:Z:2301 HWUSI-EAS1521_0001:1:1:978:13435#0 RG:Z:2302 Since I cannot read the entire file, I wanted to cat the file something like this: cat myfile | python myscript.py > myfile.sam I do not know how to execute my logic after I read the line, althought I tried: myscript.py: while True: second = raw_input() x = second.split('\t') # do something with first 14 lines? while True: line = raw_input().rstrip() if not line: break print line + " RG:Z:2301" line = raw_input().rstrip() if not line: break print line + " RG:Z:2302" -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Structuring a class
On 6/14/2010 8:08 PM, Lang Hurst wrote: I'm trying to figure out how to deal with data which will look something like: Student:Bob Hurley ID: 123456 Period:4 Grad_class: 2012 Credits: Algebra C (20P) Chapter 1 Date: September 14, 2010 Grade: 87 Credits:1.5 Notes: Probably cheated on final. Really watch on next quiz/test. Chapter 2 Date: October 31, 2010 . . **and so on** . Consumer Math (24G) Module 2 . . **more information like above** . Before deciding on data structures I suggest you give the big picture. Where will data come from? What do you plan to do with it? Often a case like this is better handled using a relational database. Python happens to come with the sqlite3 module which makes database work quite easy. So, I just figured that I would have a couple of nested dictionaries. bob = Student('123456','Bob Hurley') bob.period = 4 bob.grad_class = 2010 bob['credits']['Algebra C (20P)']={'Chapter 1':{'Date':'September 12, 2010', 'Grade':'87', **and so on**}} This works, for the most part, from the command line. So I decided to set up a class and see if I could work it from that standpoint (I'm doing this to scratch an itch, and try to learn). My preliminary class looks like: class Student: def __init__(self, ident=' ', name=' ', period=' ', grad_class=' ', subject=' ', notes=' ', credit=' '): self.name = name self.ident = ident self.period = period self.notes = notes self.grad_class = grad_class # self.credit = {{}} <--- BAD self.credit = {} I'm sure that someone will enlighten me as to where my poor coding skills are especially weak. It's the last line there (self.credit...) which I can't figure out. The credits may be in any of about 30 different subjects (teaching at a continuation high school makes for interesting times). You should define a class for Credit, which will hold the credit attributes, just like you did for Student. Then assign instances of Credit to entries in self.credit. If I don't set it to anything, ie, like it is, I get an error Stud instance has no attribute '__getitem__' If I try to leave it available for adding to somewhat dynamically, I get a 'wtf' from python. Sorry I don't understand these. It is a good idea to post full tracebacks and the code that raises the exception. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Trouble with sockets...
On 6/17/2010 5:25 AM, Modulok wrote: List, I'm new to sockets and having trouble. I tried to write a simple client/server program (see code below). The client would send a string to the server. The server would echo that back to the client. PROBLEM: I can send data to the server, and get data back, but only for the first call to the 'sendall()' method. If I try to call it in a loop on the client, to print a count-down, only the first call gets echoed. Clearly, I'm missing something. EXAMPLE: (They're on the same physical machine.) Shell on the server: modu...@modunix> ./socket_server.py Listening for clients... Got connection from 192.168.1.1 Shell on the client: modu...@modunix> ./latency_client.py 192.168.1.1 2554 0 What I wanted: [-]modu...@modunix> ./latency_client.py 192.168.1.1 2554 0 1 2 CODE: # The client program: import socket import sys def main(): '''Send data to a server and receive the data echoed back to us.''' s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect( ('192.168.1.1', 2554) ) for i in range(3): s.sendall(str(i)) print s.recv(1024) s.close() # Execution starts here: try: main() except KeyboardInterrupt: sys.exit("Aborting.") # The server program: import socket import sys def main(): '''Listen for a client and echo data back to them.''' s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind( ('192.168.1.1', 2554) ) s.listen(5) print "Listening for clients..." while True: channel, client = s.accept() print "Got connection from %s" % client[0] message = channel.recv(1024) channel.send(message) channel.close() Problem is you close the channel after one string is processed. That in turn closes the client socket. Either keep the channel open or put the client connect in the loop. # Execution starts here: try: main() except KeyboardInterrupt: sys.exit("Aborting.") ___________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] pydoc?
On 6/18/2010 1:53 PM, Andrew Martin wrote: Hey, everyone, I am new to programming and just downloaded Python 2.6 onto my windows vista laptop. I am attempting to follow 4.11 of the tutorial called "How to Think Like a Computer Scientist: Learning with Python v2nd Edition documentation" (http://openbookproject.net/thinkcs/python/english2e/ch04.html). However, I am having some trouble. I am trying to use pydoc to search through the python libraries installed on my computer but keep getting an error involving the $ symbol. It is good that you keep getting it. Consistency is valuable. $ pydoc -g SyntaxError: invalid syntax Where are you typing this? Where did you get the idea that $ pydoc -g is a valid thing to do? In what way does this relate to the tutorial? What OS are you using? Please learn to ask "good" questions - which in this case means to tell us a lot more about what you are doing. Please also reply-all so a copy of your reply goes to the tutor list. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] pydoc?
On 6/18/2010 1:53 PM, Andrew Martin wrote: Hey, everyone, I am new to programming and just downloaded Python 2.6 onto my windows vista laptop. I am attempting to follow 4.11 of the tutorial called "How to Think Like a Computer Scientist: Learning with Python v2nd Edition documentation" (http://openbookproject.net/thinkcs/python/english2e/ch04.html). However, I am having some trouble. I am trying to use pydoc to search through the python libraries installed on my computer but keep getting an error involving the $ symbol. $ pydoc -g SyntaxError: invalid syntax I make a guess - that you are typing $ pydoc -g at the Python Interpreter prompt (>>>) The manual recommends typing it a the shell prompt. In which case the $ represents the prompt and you should just type pydoc -g. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question
6/19/2010 11:51 AM, Steve Bricker wrote: Back in ancient days, my college training began with FORTRAN the first semester, then COBOL, ALC (BAL), and RPG in the second semester. Back in even more ancient days, my college training began with IBM 650 machine language, then ALC (SOAP), then CLASSMATE all of which which we fed into the computer via a card reader That was all a subset of a logic class. That was all the school offered computer-wise then. //I also reacted to introducing programming via pseudo-code. Might just as well ue Python (since it is like pseudo code) and at least see some results. It also reminds me of a FORTRAN course I was asked to teach. The students spent the first morning learning how to write expressions (e.g. operators and precedence). They had no contetxt for why they would do that or what a FORTRAN program looked like. As soon at I could I rewrote the entire course, starting them with a program that read 2 numbers, added them and printed the result. In those days students sat at terminals, edited program files, submitted them to the resident HP 3000 computer and shortly received printouts. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question
On 6/20/2010 5:59 AM, Payal wrote: On Sat, Jun 19, 2010 at 11:24:44AM +, ALAN GAULD wrote: Actually that's a point. I favour learning two languages that are semantically similar buut syntactically different. Thats why I chose JavaScript and VBScript as my tutorial languages, because the syntax of each is so different you are less likely to get confused, but the underlying programming model is very similar in each case. Hijacking the thread a bit. What about learning Jython and Python? Do I need to know Java to learn Jython? No. Jython is "just" a Python interpreter written in Java. It allows you to use Java classes in your Python code. You might want to learn Java to take advantage of that. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] finally
On 6/23/2010 7:36 PM, Christopher King wrote: In a try except clause, you can end with finally block. I know it runs after the try and except blocks regardless of the outcome, but why use it. Couldn't you just put the code after the try and except block without using a finally block. Does the finally command do something I don't know about. Does it make your program more understandable in some way? Did you read the manual? "If finally <#finally> is present, it specifies a 'cleanup' handler. The try <#try> clause is executed, including any except <#except> and else <#else> clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally <#finally> clause is executed. If there is a saved exception, it is re-raised at the end of the finally <#finally> clause. If the finally <#finally> clause raises another exception or executes a return or break statement, the saved exception is lost. The exception information is not available to the program during execution of the finally <#finally> clause. "When a return , break or continue statement is executed in the try <#try> suite of a try <#try>...finally <#finally> statement, the finally <#finally> clause is also executed 'on the way out.' A continue statement is illegal in the finally <#finally> clause. (The reason is a problem with the current implementation --- this restriction may be lifted in the future)." -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unsubscribe
On 6/23/2010 8:35 AM, Benjamin Pritchard wrote: unsubscribe You have to do that yourself. The instructions are always included in posts sent from the list: ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Suggestions for output on multiple platforms
On 6/29/2010 5:26 AM, Thomas C. Hicks wrote: I am a beginner at all this and never expected to reach a point where people other than myself may have to have access to the output of one of my programs. My problem is this - I have written a program that uses xlrd to read a series of xls files and collate and summarize the data. My original plan was to then write out that data into another xlwt spreadsheet that could be updated on a regular basis. I was thinking of adding a page per month as the data is updated regularly. The problem is that xlwt doesn't allow for very convenient addition of data to a spreadsheet - basically it has to re-create the whole spreadsheet each time. So now I am looking for suggestions of how I can output my data analysis. I am running Linux but the data needs to be able to be seen by users of OSX and Windows. I have been reading about GTK and figure I could output the analysis using that but am not sure it will be readable under Mac and Windows. Any ideas are welcome! Write the data to an html file and view it in a browser. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with choices for new database program
On 7/2/2010 5:56 PM, Jeff Johnson wrote: [snip] Visual FoxPro ... is very similar to Access I differ. Access and FoxPro are very different. Yes they both use tables, relationships, indexes and SQL. Yes they both have visual designers for forms and reports. Yes they both are programmable. But the differences are much more dramatic than the commonalities. I have developed in both. I find it painful to work in one while desiring a feature that exists only in the other. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with choices for new database program
On 7/2/2010 9:44 PM, Jeff Johnson wrote: On 07/02/2010 08:19 PM, bob gailer wrote: On 7/2/2010 5:56 PM, Jeff Johnson wrote: [snip] Visual FoxPro ... is very similar to Access I differ. Access and FoxPro are very different. Yes they both use tables, relationships, indexes and SQL. Yes they both have visual designers for forms and reports. Yes they both are programmable. But the differences are much more dramatic than the commonalities. I have developed in both. I find it painful to work in one while desiring a feature that exists only in the other. Dare you say which? ;^) FoxPro - more complete and easy-to-use object orientation - classes don't need to be in separate modules - classes and controls can be subclassed - controls can be encapsulated in container classes - classes have constructor methods - so possible to pass parameters - forms do not contain any "magic" events - method editor is a simple text editor - no "magic" events - no separate application window for programming - each table, database container, program, index is a separate file - there is a command window and lots of interactively useful commands - I like being able to run SQL and data manipulation statements directly. - error handling is much better - there are no misleading or confusing error messages that result from compilation problems - SQL is integrated into the language - nice set of workarea commands (scan, replace, ) - writing programs in FoxPro much easier than in VBA - no need to separate application from data (that is automatic). - no confusion about when to use . vs ! Access: - query and report designers are much much better - the VFP report designer is incredibly limited and hard to work with by comparison. - debugger does not require separate window - subforms - recordset controls on forms - table designer has more features - there is no database container or need for one. - relationships are integrated - visually created and available in query designer. That is not an exhaustive list - and it is my opinion. I'd rather not get into any religious arguments - but I'd be glad to clarify. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutor Digest, Vol 77, Issue 25
We received 2 copies of the tutor digest from you. If you intentionally sent it - why? Please do not do that again. If you have a specific question or comment - change the subject to something more meaningful - delete everything from the digest that is not related to your question. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help
You have gotten good advice from others. My request is that you provide a meaningful subject when you post a question. We track by subject. "Help" is not the best subject. Better would be "How to find prime numbers" -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help
On 7/13/2010 5:50 AM, Dipo Elegbede wrote: I was trying to write a code that prints prime numbers between 1 and 20. Other suggestions - you need only test divisors up to the square root of the candidate. - you can easily eliminate all even numbers and numbers divisible by 3. for i in range(0,7,3): isPrime(i-1) isPrime(i+1) -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Searching a text file's contents and comparing them toalist
[snip] Since you look up the items in the grocery list it seems to me a dictionary relating each item to its aisle would be best. inventory = {"chips" : 1, "bread" : 1, "pretzels" : 1, "magazines" : 1, "juice" : 2, "ice cream" : 2, "asparagus" : 3} MAX_AISLE = 3 aisles = [[] for i in range(MAX_AISLE)] for item in grocery_list: aisle = inventory.get(item.strip(), MAX_AISLE) aisles[aisle-1].append(item) To address the formatting question: for aisleNo, items in enumerate(aisles): if aisleNo < MAX_AISLE - 1: print "Located on aisle %s" % aisleNo + 1 else: print "Not in store" print "\n".join(items) -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A file containing a string of 1 billion random digits.
On 7/17/2010 8:01 AM, Richard D. Moores wrote: That's the goal of the latest version of my script at <http://tutoree7.pastebin.com/5XYaaNfp>. The best I've been able to do so far is a file with 800 million digits. But it seems the writing of 800 million digits is the limit for the amount of memory my laptop has (4 GB). So my question is, how can I do this differently? I'm pretty brand new to opening and writing files. Here, I can't write many shorter lines, because the end result I seek is one long string. But am I correct? Not correct. Check this out: f = open("c:\test.txt", "w") f.write("1234") f.write("5678") print open("c:\test.txt").read() When you say "line" I assume you mean text followed by whatever the OS defines as end-of-line or end-of-record. To write such a line in Python you must include "\n" at the end. [snip] -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A file containing a string of 1 billion random digits.
On 7/17/2010 9:01 AM, Mark Lawrence wrote: [snip] As an alternative to the suggestions given so far, why not open the file for write in binary mode, i.e. use 'wb' instead of 'w', and don't bother converting to strings? Then when reading the file use 'rb' instead of 'r'. You can only write strings to files. See 6.9 in the documentation: file.write(/str/) Write a string to the file b mode only affects how line ends are handled. See 2. Built-in Functions: The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append 'b' to the /mode/ value to open the file in binary mode, which will improve portability. (Appending 'b' is useful even on systems that don't treat binary and text files differently, where it serves as documentation.) -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Return error message for my script in Blender
On 7/17/2010 5:11 PM, Andrew Martin wrote: I am new to Blender and Python (2.6 on vista) and was trying to follow a tutorial in the book Blender 2.49 Scripting by Michel Anders. I was trying to write a script that would create a user interface where the user could select various aspect of an insect and the code would create a polygonal bug. However, when I copied code exactly from the book, I got an error saying "'return' outside function". Here is the code I had in the text editor: #!BPY import Blender import mymesh2 Draw = Blender.Draw THORAXSEGMENTS = Draw.Create(3) TAILSEGMENTS = Draw.Create(5) LEGSEGMENTS = Draw.Create(2) WINGSEGMENTS = Draw.Create(2) EYESIZE = Draw.Create(1.0) TAILTAPER = Draw.Create(0.9) if not Draw.PupBlock('Add CreepyCrawly', [\ ('Thorax segments:' , THORAXSEGMENTS, 2, 50, 'Number of thorax segments'), ('Tail segments:' , TAILSEGMENTS, 0, 50, 'Number of tail segments'), ('Leg segments:' , LEGSEGMENTS, 2, 10, 'Number of thorax segments with legs'), ('Wing segments:' , WINGSEGMENTS, 0, 10, 'Number of thorax segments with wings'), ('Eye size:' , EYESIZE, 0.1,10, 'Size of the eyes'), ('Tail taper:' , TAILTAPER, 0.1,10, 'Taper fraction of each tail segment'),]): return Anybody know why I keep getting this error? The return statement is not in a function. What else can we say. Either you copied incorrectly or there is a problem with the book. Do you understand? -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A file containing a string of 1 billion random digits.
Check this out: import random, time s = time.time() cycles = 1000 d = "0123456789"*100 f = open("numbers.txt", "w") for i in xrange(n): l = [] l.extend(random.sample(d, 1000)) f.write(''.join(l)) f.close() print time.time() - s 1 million in ~1.25 seconds Therefore 1 billion in ~21 minutes. 3 ghz processor 2 g ram. Changing length up or down seems to increase time. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Contents of Tutor digest, help with Hangman program
On 7/19/2010 7:37 AM, John Palmer wrote: Hi Alan thanks for the help. I did try the getpass module, I think I used: getpass.getpass() This actually prompted the user to enter a password, which isn't really what I want. Unless there's something i'm missing with this module? I'll take another look anyway. Reading the documentation (15.7 in Python 3): The getpass module provides two functions: getpass.getpass(/prompt='Password: '/, /stream=None/)¶ <http://docs.python.org/py3k/library/getpass.html?highlight=getpass#getpass.getpass> Prompt the user for a password without echoing. The user is prompted using the string /prompt/, which defaults to 'Password: '. HTH -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A file containing a string of 1 billion random digits.
On 7/19/2010 10:48 AM, Richard D. Moores wrote: I've been unable to find any mention of that use of the asterisk in the 3.1 docs http://docs.python.org/py3k/library/stdtypes.html#old-string-formatting -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A file containing a string of 1 billion random digits.
[snip] I did not read the documentation with enough understanding. I withdraw the use of sample. Sigh! -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how i can change two lists into one directory
On 7/22/2010 7:51 PM, ANKUR AGGARWAL wrote: hey i have just started making a app using python and just gt a problem.. i have two list a=["x","z"] b=[1,2] i want to make a directory like this Do you mean "dictionary"? c={"x":1,"z":2} is it possible Indeed. There are several ways to do this. Easiest: dict(zip(a,b)) i mean i tried it using loops d = {} for i in range(len(a)): d[a[i] = b[i] and all but i cant append a directory Of course you can't append, since a dictionary is not a sequence. But you can add a key-value pair as the above loop demonstrates. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FTP from mainframe
On 7/29/2010 12:34 PM, Steve Bricker wrote: This is my first attempt to FTP a file from a mainframe. The code: import ftplib session = ftplib.FTP('company.lan.com','userid','passwd') myfile = open('PC.filename','w') session.retrlines("RETR 'mainframe.filename'", myfile) myfile.close() session.quit() The resulting error is: Traceback (most recent call last): File "ftp_from_mf.py", line 5, in session.retrlines("RETR 'mainframe.filename'", myfile) File "c:\python26\lib\ftplib.py", line 428, in retrlines callback(line) TypeError: 'file' object is not callable According to the ftplib module documentation: retrlines(command[, callback]) Retrieve a file or directory listing in ASCII transfer mode. command should be an appropriate RETR command (see retrbinary()) or a command such as LIST, NLST or MLSD (usually just the string 'LIST'). The callback function is called for each line, with the trailing CRLF stripped. The default callback prints the line to sys.stdout. IOW callback must be a function. You are passing a file object. I will guess that you want: def writer(line): myfile.write(line + '\n') session.retrlines("RETR 'mainframe.filename'", writer) The documentation is in error in that it does not explicitly state that a line is passed to the callback function as an argument. I am assuming that is the case. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python and Abaqus
On 7/30/2010 7:44 AM, leo.ruggier...@libero.it wrote: Dear All, I am trying to have access to the Abaqus kernel by a Python script. My intention is to avoid to use the Abaqus GUI (or command line) to run a simulation. The idea is to lunch the Python script by DOS or Python module. "lunch" mmm spam? The problem is that my Python script runs from the Abaqus command line or from the GUI (menu-->file-->run script) but it doesn't run from outside. Python doesn't recognize the Abqaus objects (i.e. mdb). How could I solve this problem? Please learn to ask good questions. In this case specifically: Tell us what you are doing to "run from outside". Be as specific and thorough as possible. Tell us what results you are getting. Be as specific and thorough as possible. "Doesn't run" and "doesn't recognize" are too vague. Post your script if not too large else use a pastebin and provide the link. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python - RPG Combat System
On 7/30/2010 10:49 PM, Jason MacFiggen wrote: what can I do instead of writing print so many times? import random my_hp = 50 mo_hp = 50 my_dmg = random.randrange(1, 20) mo_dmg = random.randrange(1, 20) while True: if mo_hp < 0: print "The Lich King has been slain!" elif my_hp < 0: print "You have been slain by the Lich King!" if mo_hp <= 0: break elif my_hp <= 0: break else: print "Menu Selections: " print "1 - Attack" print "2 - Defend" print choice = input ("Enter your selection. ") choice = float(choice) print if choice == 1: mo_hp = mo_hp - my_dmg print "The Lich King is at ", mo_hp, "Hit Points" print "You did ", my_dmg, "damage!" print my_hp = my_hp - mo_dmg print "I was attacked by the lk for ", mo_dmg," damage!" print "My Hit Points are ", my_hp print elif choice == 2: mo_hp = mo_hp - my_dmg / 2 print "The Lich King is at", mo_hp, "Hit Points" print "you did ", my_dmg / 2, "damage!" print my_hp = my_hp - mo_dmg print "I was attacked by the lk for ", mo_dmg," damage!" print "My Hit Points are ", my_hp print Most of the statements in each choice block are identical. Factor them out, giving: if choice == 1: mo_hp = mo_hp - my_dmg print "you did ", my_dmg /, "damage!" elif choice == 2: mo_hp = mo_hp - my_dmg / 2 print "you did ", my_dmg / 2, "damage!" print "The Lich King is at", mo_hp, "Hit Points" my_hp = my_hp - mo_dmg print "You did ", my_dmg, "damage!" print print "I was attacked by the lk for ", mo_dmg," damage!" print "My Hit Points are ", my_hp print You could (better) move these statements into a function, passing 1 or 2 as the divisor for my_dmg and returning the updated values for my_ho and my_hp. def update(factor): print "The Lich King is at", mo_hp, "Hit Points" print "you did ", my_dmg / factor, "damage!" print print "I was attacked by the lk for ", mo_dmg," damage!" print "My Hit Points are ", my_hp print return mo_hp - my_dmg / factor, my_hp - mo_dmg ... if choice == 1: mo_hp, my_hp = update(1) elif choice == 2: mo_hp, my_hp = update(2) -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple Python Program
On 7/31/2010 12:00 AM, Jason MacFiggen wrote: Can anyone tell me how to fix the errors I am getting if possible? I'm quite new and so confused... I could give lots of diagnostic advice and detail. There is so much wrong with this program. I suggest you discard it, back up and start with the simplest possible statement of the problem which is: print a number randomly chosen from (0,1,2) Then write the simplest possible program to do this one time; no loops or functions. The entire program could then be written in 2 lines of code. Run it, fix it if it does not work. Once you have success - Add (one at a time) various features: - roll dice to select winner - player names - repetition Continue to avoid writing functions. They are not necessary for such a simple program. The final product will have less than 15 statements. also how do I display the winner under the displayInfo function? import random def main(): print playerOne, playerTwo = inputNames(playerOne, PlayerTwo) while endProgram == 'no': endProgram == no playerOne = 'NO NAME' playerTwo = 'NO NAME' winnerName = rollDice(p1number, p2number, playerOne, playerTwo, winnerName) winnerName = displayInfo endProgram = raw_input('Do you want to end program? (Enter yes or no): ') def inputNames(playerOne, PlayerTwo): p1name = raw_input("Enter your name.") p2name = raw_input("Enter your name.") return playerOne, playerTwo def random(winnerName): p1number = random.randint(1, 6) p2number = random.randint(1, 6) if p1number > p2number: playerOne = winnerName elif p1number < p2number: playerTwo = winnerName else p1number == p2number: playerOne, playerTwo = winnerName def displayInfo(): #how do I display winner? main() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Writing scripts and apps for Internet consumption
On 7/31/2010 2:45 PM, Eric Hamiter wrote: Get a linux hosting account, and a web address, most linux hosting comes with python, so practice in the 'cloud'. I have that-- an account with Dreamhost. This hasn't solved my problems yet though. Like I said, I can have it write a simple Hello, World! Please post that code, and the URL you use to invoke it. ...but if I make it do anything more complex, I get a 404 error. Please post that code, and the URL you use to invoke it. Do you import cgi? There is a companion module (cgitb) that captures exceptions and returns the traceback to the web browser. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Writing scripts and apps for Internet consumption
On 7/31/2010 6:40 PM, Eric Hamiter wrote: On Sat, Jul 31, 2010 at 4:48 PM, bob gailer <mailto:bgai...@gmail.com>> wrote: Please post that code, and the URL you use to invoke it. test.py: this works on my laptop but not on the server http://pastebin.com/ChjUzLRU test-working.py: this works on both laptop & server http://pastebin.com/iLNTrGdW both available for execution here: http:// <http://erichamiter.com/xkred27/>erichamiter.com/ <http://erichamiter.com/xkred27/>xkred27/ <http://erichamiter.com/xkred27/> Do you import cgi? Yes. There is a companion module (cgitb) that captures exceptions and returns the traceback to the web browser. I tried that as well. I'm sure I'm missing something fundamental here, but that's kind of obvious since I posted I don't know what I'm doing in the first place! :) Main difference I see is lack of any html tags in test.py! Try adding 1. print "" 2. print "Publix Aide" 3. print "" 4. # the store map print statements go here 5. print "" Where is erichamiter.com/ <http://erichamiter.com/xkred27/> hosted? Is there a way I could put something there? -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple Python Program
On 7/31/2010 8:24 PM, Steven D'Aprano wrote: On Sun, 1 Aug 2010 04:35:03 am bob gailer wrote: Continue to avoid writing functions. They are not necessary for such a simple program. That is *terrible* advice. Absolutely awful. Well I disagree. I was trying to steer the OP to get the simplest possible program running, then do incremental expansion. In my understanding user defined functions serve these purposes: 1 - modularizing large programs 2 - factoring out common code 3 - providing callbacks 4 - choosing callable objects from some collection. 5 - providing a main function for the if __name__ == "__main__" idiom 6 - what else can we think of? None of these are needed in this simple case. Functions should not be avoided unless necessary. Functions should be used unless there is a compelling reason to avoid them. Once the OP has succeeded in getting some program running he will experience some relief and satisfaction. Then I think it is time to add language features. But not just for the sake of using them. This is not 1972 any more, and we're not teaching kids to write spaghetti code with BASIC and GOTO. Functions have no relationship to avoiding spaghetti code. Python makes spaghetti code impossible since it lacks a goto or equivalent statement. Functions, or their object-oriented equivalent methods, are *the* single most important feature of programming. And they're simple too Well - almost simple. Until you get into issues like global vs local names, positional vs keyword arguments, required vs optional arguments, default values (especially mutable objects), * and **, generator functions, magic methods, nested defs, decorators, -- they might not be the first thing you teach an absolute newbie who has never programmed before That is what our OP appears to be. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Writing scripts and apps for Internet consumption
On 7/31/2010 11:03 PM, Eric Hamiter wrote: On Sat, Jul 31, 2010 at 9:53 PM, bob gailer <mailto:bgai...@gmail.com>> wrote: Main difference I see is lack of any html tags in test.py! Try adding 1. print "" 2. print "Publix Aide" 3. print "" 4. # the store map print statements go here 5. print "" I understand that this would work-- Did you send the altered code to the server and test it? Did it succeed or fail? What happens if you put the grocery code into test-working.py? my question was how can I get a python script to "do anything" on it? Why is it returning a 404 error? Where is erichamiter.com/ <http://erichamiter.com/xkred27/> hosted? Is there a way I could put something there? A hosted server, so it's not on my local machine. Afraid I can't hand you any access directly to it, I have too much personal stuff on there at the moment. I would be more than happy to look at any code you would want to send in an email or pastebin, and I could put it up for a test. Could I have a link to the hosting service? Perhaps I could set up my own account. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] web-based python?
On 8/1/2010 1:07 PM, Alex Hall wrote: Hi all, I have an IPowerWeb.com server, which claims to support Python. How would I use this? For example, to start, how would I print html code to the screen, or manage input from a form? Thanks. Another participant just raised a similar question! Unfortunately IPowerWeb.com does not "provide support for custom code or custom scripts. We assume that if a customer wants to use Perl, CGI, PHP, Python, ASP or any other scripting language, he/she has the necessary programming skills to manage his/her scripts." A starting place is the following script - let's call it "test.py". Upload it then invoke it. Try http://url-to-your-site/test.py #!/usr/bin/python print "Content-type: text/html" print print "" print "Hello World from Python" print "" print "Standard Hello World from a Python CGI Script" print " -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr()
On 8/4/2010 1:23 PM, Pete wrote: Hi, I'm trying to understand the syntax for reflection in python. I was wondering about this. From the example on diveintopython: http://diveintopython.org/power_of_introspection/index.html import statsout def output(data, format="text"): output_function = getattr(statsout,"output_%s" % format, statsout.output_text) return output_function(data) I was wondering about how to make this work if the function that you are trying to call is not in a module. Everything in Python is in a module. I suspect you mean not in an imported module, e.g. in the main module. Whose __name__ is '__main__'. A reference to the main module can be found: import sys main = sys.modules['__main__'] Is that possible? Something like this: def output_text(data): return_value = "This is text: " + data return return_value def output(data, format="text"): output_function = getattr(*,"output_%s" % format, statsout.output_text) return output_function(data) What I can't figure out is what to put in place of *. I've tried globals()['__name__'], in various forms, to no avail. Replace those stars with main as derived above. globals()['output_text'] will also give you a reference to the function. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr()
On 8/4/2010 3:44 PM, Huy Ton That wrote: Oh, that's right, I should have tried to example in the interpreter instead of in my head:P Say Bob, Is that the preferred method over something like: I would prefer to create a class and make these functions class methods. class A: def output_text(self, data):return data def output_hex(self, data):return '\\x' + data def __getattr__(self, name): return self.output_text a = A() data='bar' print a.output_text(data) print a.output_hex(data) print a.foo(data) -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr()
On 8/4/2010 4:04 PM, bob gailer wrote: On 8/4/2010 3:44 PM, Huy Ton That wrote: Oh, that's right, I should have tried to example in the interpreter instead of in my head:P Say Bob, Is that the preferred method over something like: I would prefer to create a class and make these functions class methods. class A: def output_text(self, data):return data def output_hex(self, data):return '\\x' + data def __getattr__(self, name): return self.output_text a = A() data='bar' print a.output_text(data) print a.output_hex(data) print a.foo(data) I just realized my answer does not accomodate your looking for the function by name. Please stand by -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr()
class A: def call_by_name(self, func, data): f = A.__dict__.get(func, self.output_text) return f(data) def output_text(self, data):return data def output_hex(self, data):return '\\x' + data a = A() data = 'bar' print a.call_by_name('output_text', data) print a.call_by_name('output_hex', data) print a.call_by_name('foo', data) -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr()
On 8/4/2010 4:32 PM, Huy Ton That wrote: I have a side question, I am using python 2.7. Why do you use class A: instead of class A(object): ? My example does not depend on old / new style classes. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] os.urandom()
On 8/7/2010 6:29 PM, Evert Rol wrote: [a for a in map(chr, os.urandom(6))] Overkill! map(chr, os.urandom(6)) is sufficient. Or [chr(x) for x in os.urandom(6))] The latter is easier to read. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] os.urandom()
On 8/8/2010 1:57 AM, Richard D. Moores wrote: On Sat, Aug 7, 2010 at 17:00, Alan Gauld wrote: "Richard D. Moores" wrote Yes, the number of bytes seems to<= 6, or is it?: os.urandom(6) b'\xf1\x1c\x15\x83\x14\x0e' ok os.urandom(6) b'l\xbb\xae\xb7\x0ft' still ok - the l and t at the ends are valid characters so Python prints the letter hex(ord('t')) '0x74' hex(ord('l')) '0x6c' So if os.urandom() had been written so that it printed only hex, b'l\xbb\xae\xb7\x0ft' would have been b'\x6c\xbb\xae\xb7\x0f\x74' , right? Thanks very much for that, Alan. How were we supposed to know that all the hexes have 2 digits? In version 2.6.5 Language Reference 2.4.1 - String literals: \xhh Character with hex value hh -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading every 5th line
On 8/8/2010 8:04 AM, nitin chandra wrote: Hello Everyone, I am to make a small programme for a friend of mine where i am to start reading from 14th (string) from a file and then read every 5th row. ie. in 1st read it reads the 14 row in a File, write to an OUTPUT-1 file Next reads 19th row, write to the OUTPUT-1 file then 24th row,... so on. and the second loop does is reads the 15th line as the first line from same input file and write to OUTPUT-2 file next reads 20th line / row, write to the OUTPUT-2 file I have tried various ways but some how i am ONLY able to do i simple read from one file and write to another. Please show us the attempts you have made. There are 3024 rows / lines PER file That is irrelevant. and there are 24 such file I need to run the programme on. Several unknowns here. Do you process one file at a time? Where does the output from the other files go? -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor