[Tutor] An unknown error in my program
The following program has an error : new += lists[int(j)]+"-"; UnboundLocalError: local variable 'new' referenced before assignment But when I put the sentence " new = '' " in the main() function, the program run normally. Please tell me why? Isn't variable new in the following program is a global variable? the program is: lists = ['zero','one','two','three','four','five','six','seven','eight','nine']; new = ""; def main(): while True: try: iput = int(raw_input('Please input a int(0~1000): ')) if not 0<=iput<=1000: continue except: continue break iput = str(iput) for j in iput: new += lists[int(j)]+"-"; print new[0:-1]; if __name__ == "__main__": main(); daedae11___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] An unknown error in my program
On Sun, Dec 25, 2011 at 5:18 AM, daedae11 wrote: > The following program has an error : > new += lists[int(j)]+"-"; > UnboundLocalError: local variable 'new' referenced before assignment > > But when I put the sentence " new = '' " in the main() function, the > program run normally. > > Please tell me why? Isn't variable new in the following program is a global > variable? > > the program is: > lists = ['zero','one','two','three','four','five','six','seven','eight','nine']; > new = ""; This new is global to your file. Within your main() function you can read the value of new. But inside main() you are creating another variable also called new when you do this: new += . Your code is trying to add something to a variable that doesn't yet have a value. 'new' is a name that is not bound to any value. You can either move the stuff at the top of your program into main, or you could pass the outer new into main as a parameter:main(new): > > > def main(): > > while True: > try: > iput = int(raw_input('Please input a int(0~1000): ')) > if not 0<=iput<=1000: > continue > except: > continue > break > > iput = str(iput) > for j in iput: > new += lists[int(j)]+"-"; > print new[0:-1]; > > if __name__ == "__main__": > main(); > > > daedae11 > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] An unknown error in my program
On 12/25/2011 09:46 PM, Joel Goldstick wrote: You can either move the stuff at the top of your program into main, or you could pass the outer new into main as a parameter:main(new): the third alternative is to use the global keyword, e.g. # declare a global named 'new' new = 0 def increment_new(): # tell python to use the global 'new' instead of # creating a local 'new' global new new += 1 print new increment_new() print new ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] An unknown error in my program
On Sun, Dec 25, 2011 at 6:00 AM, Lie Ryan wrote: > On 12/25/2011 09:46 PM, Joel Goldstick wrote: >> >> >> You can either move the stuff at the top of your program into main, or >> you could pass the outer new >> into main as a parameter: main(new): > > > the third alternative is to use the global keyword, e.g. > > # declare a global named 'new' > new = 0 > > def increment_new(): > # tell python to use the global 'new' instead of > # creating a local 'new' > global new > > new += 1 > > print new > increment_new() > print new > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Since this is a tutor mailing list, many questions come from people learning not only python, but programming in general. Lie is right in showing that you can let your function know that you want it to know about the global called new. But I think this is generally not a good approach. To get good at python you need to understand scope and namespaces. The value of using functions is that they let you write small self contained code that accomplishes some purpose. The purpose should be clear from the name of the function. Once your function works as you like it, you don't need to worry about how it works. You can just call it from somewhere else in your program, knowing that it will do what it does. Using a global messes this up. Now, when you call your function it will fail unless there is some variable named 'new' in some outer namespace. Your function is no longer self contained. Since the OPs code is so small, there may not be a need to use a function at all, but since he chose to go that route, the data that the function needs should be declared within the function. If that data is created elsewhere it should be passed to the function via parameters. If the function creates a result that will be needed later, it should be returned by the function. So, my point is that learning about the value of and aspects of writing good functions is more instructive than going with the global declaration. -- Joel Goldstick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about the build-in function reversed in Python2.5
daedae11 wrote: The build-in function reversed() in Python2.5 returns a iterator. But I don't know how to use the iterator. Please give me a simple example about how to use bulid-in function reversed() to reverse a list. You use the iterator the same way you would any other iterator: * in for loops: for obj in reversed(my_list): print(obj) * pass it to functions which expect an iterator: a = reduce(function, reversed(my_list)) b = map(func, reversed(my_string)) * create a new sequence: my_list = list(reversed(my_list)) Note that the advantage of reversed is that it is lazy (it returns an iterator). If you just want a copy of a list in reverse order, you can use slicing: my_list[::-1] (also works on strings and tuples). If you want to reverse the list in place, instead of making a copy: my_list.reverse() # must be a list, not strings or tuples reversed() is more general: it can work on any finite iterable object, not just lists. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] An unknown error in my program
On 25/12/11 10:18, daedae11 wrote: The following program has an error : new += lists[int(j)]+"-"; UnboundLocalError: local variable 'new' referenced before assignment Others have answered the question for you however there are two additional points to make: 1) Always send the complete erroir message not just the last line. 2) You do not need semi-colons at the end of lines in Python. lists = ['zero','one','two','three','four','five','six','seven','eight','nine']; new = ""; No need for them here for j in iput: new += lists[int(j)]+"-"; print new[0:-1]; if __name__ == "__main__": main(); Nor here. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] insert queries into related tables referencing foreign keys using python
On 12/24/2011 11:13 PM, Lie Ryan wrote: Querying .lastrowid is pretty much safe as long as you don't use a single cursor from multiple threads. The .lastrowid attribute belongs to a cursor, so write operations from one cursor would not affect the .lastrowid of other cursors. However, note that multiple cursors created from a single connection will be able to see each other's changes immediately (as opposed to when commited). This might or might not always be desirable. In sqlite, it is more common to create one **connection** for each thread. Creating one connection for each thread prevents concurrency problems since each thread will not see uncommitted data from another thread. However, the recommended scenario is to avoid multithreading at all. sqlite developers have a strong opinion against multithreading (http://www.sqlite.org/faq.html#q6), even though they claimed that sqlite is the *embedded* SQL engine with the most concurrency (and it does very well in multithreaded scenarios). It is common pattern in sqlite-backed applications to have a single thread doing all the writes. Okay... sounds like I should be safe for the most part. Down the road (way down the road) I had some thoughts of working on an application that would in certain situations have multiple users (1-10) and had hoped that as long as I kept the sqlite insert/update activity wrapped in transactions there wouldn't be much problem with table locks, etc. and in this case, confusing lastrowid from one transaction with that from another. By the time I get to where I'm ready/willing/able to write that particular app, I might have moved on to an ORM, though. Thanks, Monte ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] PYTHONPATH (Mac OS X)
Hey there! I'm reading Lutz's Learning Python. Here is some code from the book. There is a module called lcclient_lutz.py: from lengthcounter_lutz import countLines, countChars print countLines('lengthcounter_lutz.py'), countChars('lengthcounter_lutz.py') And there is another one called lengthcounter_lutz.py: def countLines(name): file = open(name) return len(file.readlines()) def countChars(name): return len(open(name).read()) def test(name): return "Lines:", countLines(name), "Chars:", countChars(name) if __name__ == '__main__': print test('lengthcounter_lutz.py') I've got an error while trying to load lcclient_lutz module: python /Users/Username/Python_modules/lcclient_lutz.py Traceback (most recent call last): File "/Users/Username/Python_modules/lcclient_lutz.py", line 2, in print countLines('lengthcounter_lutz.py'), countChars('lengthcounter_lutz.py') File "/Users/Username/Python_modules/lengthcounter_lutz.py", line 2, in countLines file = open(name) IOError: [Errno 2] No such file or directory: 'lengthcounter_lutz.py' How to fix it? Is it connected with the PYTHONPATH variable? P.S. There might be an error in the lengthcounter_lutz module, because it makes mistakes while counting. Kind regards. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] PYTHONPATH (Mac OS X)
On 25/12/11 22:55, Stayvoid wrote: There is a module called lcclient_lutz.py: from lengthcounter_lutz import countLines, countChars print countLines('lengthcounter_lutz.py'), countChars('lengthcounter_lutz.py') countChars('lengthcounter_lutz.py') File "/Users/Username/Python_modules/lengthcounter_lutz.py", line 2, in countLines file = open(name) IOError: [Errno 2] No such file or directory: 'lengthcounter_lutz.py' How to fix it? Is it connected with the PYTHONPATH variable? PYTHONPATH only helps Python find the files to import. Since the error message is pointing at code insiude the imported functions then clearly PYTHONPATH is working just fine. So what is the error? Simply that python is saying it cannot find the file. So it is probably in a different folder to the one in which the program is running. You need to provide a valid path to the file, P.S. There might be an error in the lengthcounter_lutz module, because it makes mistakes while counting. Thats possible. Or it may e worlking to a different definition of success to the one you expect! Counting words and letters is quite a subjective past-time. So what is it doing exactly that seems wrong? What input? What output? What did you expect? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor