Re: Traceback error
Cai Gengyang writes: > This is a piece of code about comparators : > j# Assign True or False as appropriate on the lines below! > ... > When I tried to run it, this is the error I got : > > Traceback (most recent call last): > File "python", line 1, in > NameError: name 'j' is not defined The error information is very precise: in your line 1, you have: j# Assign True or False as appropriate on the lines below! The "j" before the comment ("#...") is what causes the problem. Likely, you did not want it there. -- https://mail.python.org/mailman/listinfo/python-list
Re: Traceback error
Right ... I removed the 'j' and the code works now. I must have accidentally put it in , forgot about it and thought that it was part of the original code when it shouldn't have been there in the first place. Thanks ! On Saturday, November 21, 2015 at 3:27:02 PM UTC+8, Frank Millman wrote: > "Cai Gengyang" wrote in message > news:e5d80196-61c5-44d9-bec8-dc563d58f...@googlegroups.com... > > > This is a piece of code about comparators : > > > > j# Assign True or False as appropriate on the lines below! > > [snip rest of code] > > > When I tried to run it, this is the error I got : > > > Traceback (most recent call last): > > File "python", line 1, in > > NameError: name 'j' is not defined > > > > Any ideas how to debug this ? > > > It looks to me as if the error is right there on the first line. What is > that 'j' doing there? It looks like a typo. > > HTH > > Frank Millman -- https://mail.python.org/mailman/listinfo/python-list
Re: Late-binding of function defaults (was Re: What is a function parameter =[] for?)
Jussi Piitulainen writes: > dieter writes: >> Chris Angelico writes: >> >>> IMO it's controversial mainly because there's an easy and obvious >>> syntax for early binding, but late binding doesn't have syntactic >>> support, and all the options are imperfect. >> >> I do not think that we should get additional syntax for lately bound >> default values. It would explicitely introduce the concepts early >> versus late binding which are likely difficult to understand by many >> users. > > I'm confused by the term. I don't like it one bit. > > "Early binding" of a default value seems to mean that the expression > that produces the default value of a function parameter is evaluated > when the function is defined. "Late binding" seems to mean that the > expression is evaluated when the function is called. > > In both cases the actual binding of the parameter to the value (either > the default or an actual argument) is established when the function is > called. Several different bindings of that same parameter to different > values can hold simultaneously, so the *binding* has to be conceptually > "late". Because recursion. Conventionally, "binding" is the association of a "value" with a "name". In this sense, you can call "early binding" the current Python behavior with respect to default parameters: the expression is evaluated into a "value" at function definition time and bound to the parameter name. A later call may rebind the parameter name (if it provides its own value). In the case of "late binding", the function definition would also bind at function definition time the "name" to something (but not a "value"): an expression, maybe together with some binding. This expression would then be evaluated at a later time (and we only then get the typical binding of a "name" to a "value"). > Why isn't the evaluation of the default expression called evaluation? I do not mind if you prefer to use the term "evaluation" instead of "binding". Nothing important in my previous message would be changed by the term exchange: you must specify how (and when) the variables referenced in the expression get their values. And this will give new difficulties - more serious than Python's current handling of default parameters. -- https://mail.python.org/mailman/listinfo/python-list
Re: Traceback error
"Cai Gengyang" wrote in message news:e5d80196-61c5-44d9-bec8-dc563d58f...@googlegroups.com... This is a piece of code about comparators : j# Assign True or False as appropriate on the lines below! [snip rest of code] When I tried to run it, this is the error I got : Traceback (most recent call last): File "python", line 1, in NameError: name 'j' is not defined Any ideas how to debug this ? It looks to me as if the error is right there on the first line. What is that 'j' doing there? It looks like a typo. HTH Frank Millman -- https://mail.python.org/mailman/listinfo/python-list
Traceback error
This is a piece of code about comparators : j# Assign True or False as appropriate on the lines below! # Set this to True if 17 < 328 or to False if it is not. bool_one = 17 < 328 # We did this one for you! # Set this to True if 100 == (2 * 50) or to False otherwise. bool_two = 100 == (2 * 50) # Set this to True if 19 <= 19 or to False if it is not. bool_three = 19 <= 19 # Set this to True if -22 >= -18 or to False if it is not. bool_four = -22 >= -18 # Set this to True if 99 != (98 + 1) or to False otherwise. bool_five = 99 != (98 + 1) When I tried to run it, this is the error I got : Traceback (most recent call last): File "python", line 1, in NameError: name 'j' is not defined Any ideas how to debug this ? Thanks a lot! Appreciate it Cai Gengyang -- https://mail.python.org/mailman/listinfo/python-list
Re: anyone tell me why my program will not run?
On Sat, Nov 21, 2015 at 2:30 PM, Dylan Riley wrote: > I have done so coming up with this piece of work but it doesnt run can anyone > help me out? > Please, please, try to help us out here! What does it mean to "not run"? Does it run and give an exception? Does it run to completion but give no output? Do you type "python somefile.py" and get back an error from the system? What? ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: anyone tell me why my program will not run?
On Fri, Nov 20, 2015 at 10:30 PM, Dylan Riley wrote: > i am learning python and was tasked with making a program that flips a > coin 100 times and then tells you > the number of heads and tails. > > I have done so coming up with this piece of work but it doesnt run can > anyone help me out? > > #This is credited to dylan > > print(" \\ \\ \\ \\ \\ \\ \\ \\ D FLIPS \\ \\ \\ \\ \\ \\ \\ \\") > print("\n\nThis is D's coin flipper program. You get 100 flips. \n\t LETS > SEE HOW LUCKY YOU ARE") > input("Press enter") > > import random > > heads = int("1") > tails = int("2") > flips = 100 > headscount = 0 > tailscount = 0 > > while flips != 0: > flips -= 1 > > shouldn't this below be in the while loop? > result = random.randint(heads, tails) > if result = heads: > headscount += 1 > else: > tailscount += 1 > > > up to here > print(headscount, tailscount) > > input("press enter to exit") > -- > https://mail.python.org/mailman/listinfo/python-list > -- Joel Goldstick http://joelgoldstick.com/stats/birthdays -- https://mail.python.org/mailman/listinfo/python-list
anyone tell me why my program will not run?
i am learning python and was tasked with making a program that flips a coin 100 times and then tells you the number of heads and tails. I have done so coming up with this piece of work but it doesnt run can anyone help me out? #This is credited to dylan print(" \\ \\ \\ \\ \\ \\ \\ \\ D FLIPS \\ \\ \\ \\ \\ \\ \\ \\") print("\n\nThis is D's coin flipper program. You get 100 flips. \n\t LETS SEE HOW LUCKY YOU ARE") input("Press enter") import random heads = int("1") tails = int("2") flips = 100 headscount = 0 tailscount = 0 while flips != 0: flips -= 1 result = random.randint(heads, tails) if result = heads: headscount += 1 else: tailscount += 1 print(headscount, tailscount) input("press enter to exit") -- https://mail.python.org/mailman/listinfo/python-list
Re: error help import random
On Friday, November 20, 2015 at 11:06:05 PM UTC, Rob Gaddi wrote: > On Fri, 20 Nov 2015 15:15:42 -0500, Terry Reedy wrote: > > > On 11/20/2015 12:22 PM, Dylan Riley wrote: > >> This is my fortune cookie program i wrote in python. > >> the problem is it will not run past the first line of input. > >> could someone please identify the error and explain to me why. > >> here is the code: > >> > >> #the program silulates a fortune cookie #the program should display one > >> of five unique fortunes, at randon, each time its run > >> > >> import random > >> > >> print(" \\ \\ \\ \\ DYLANS FORTUNE COOKIE \\ \\ \\ ") > >> print("\n\n\tGood things come to those who wait") > >> input("\nPress enter to see your fortune") > >> > >> fortune = random.randrange(6) + 1 print(fortune) > >> if fortune == 1: > >> print("happy") > >> elif fortune == 2: > >> print("horny") > >> elif fortune == 3: > >> print("messy") > >> elif fortune == 4: > >> print("sad") > >> elif fortune == 5: > >> print("lool") > > > > Use a dict instead of if-elif. > > > > i = random.randrange(6) > > fortunes = {0:'happy', 1:'horny', 2:'messy', > > 3:'sad', 4:'lool', 5:'buggy'} > > print(i, fortunes[i]) > > > > Or a list/tuple, which saves in typing, memory, and access time. > > fortunes = ('happy', 'horny', 'messy', 'sad', 'lool', 'buggy') > i = random.randrange(len(fortunes)) > print(i, fortunes[i]) > > Or to be lazier still, just use random.choice > > fortunes = ('happy', 'horny', 'messy', 'sad', 'lool', 'buggy') > print(random.choice(fortunes)) > > None of which actually addresses the OP's issue with input(), but it's > nice to get the back half clean as well. > > -- > Rob Gaddi, Highland Technology -- www.highlandtechnology.com > Email address domain is currently out of order. See above to fix. very nice i like the way you code. i managed to solve the problem it was because i wasnt using raw_input however i updated to python 3 so the original now works. many thanks anyway -- https://mail.python.org/mailman/listinfo/python-list
Re: Mapping between python packages and distro packages?
Stephane Wirtel writes: > in fact, I would like to have a database where I want the requests > library, I will get the python-requests for debian/ubuntu and the > right package for the yum installer. Okay. That's a pretty simple technical problem (a simple relation between PyPI distribution name, GNU+Linux operating system name, and package name). Of course, *populating* that database, *verifying* the ambiguous inputs, and *maintaining* that database into the future, are all social problems. You'll probably need an organised group of people to address it. I'm not aware of any sufficiently motivated group of people to put in the ongoing effort to provide what you want. (Another social problem is convincing people not to top-post, but instead to reply interleaved and trim irrelevant quoted material https://en.wikipedia.org/wiki/Posting_style#Interleaved_style>.) -- \ “Anyone who puts a small gloss on [a] fundamental technology, | `\ calls it proprietary, and then tries to keep others from | _o__) building on it, is a thief.” —Tim O'Reilly, 2000-01-25 | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Re: error help import random
On Fri, 20 Nov 2015 15:15:42 -0500, Terry Reedy wrote: > On 11/20/2015 12:22 PM, Dylan Riley wrote: >> This is my fortune cookie program i wrote in python. >> the problem is it will not run past the first line of input. >> could someone please identify the error and explain to me why. >> here is the code: >> >> #the program silulates a fortune cookie #the program should display one >> of five unique fortunes, at randon, each time its run >> >> import random >> >> print(" \\ \\ \\ \\ DYLANS FORTUNE COOKIE \\ \\ \\ ") >> print("\n\n\tGood things come to those who wait") >> input("\nPress enter to see your fortune") >> >> fortune = random.randrange(6) + 1 print(fortune) >> if fortune == 1: >> print("happy") >> elif fortune == 2: >> print("horny") >> elif fortune == 3: >> print("messy") >> elif fortune == 4: >> print("sad") >> elif fortune == 5: >> print("lool") > > Use a dict instead of if-elif. > > i = random.randrange(6) > fortunes = {0:'happy', 1:'horny', 2:'messy', > 3:'sad', 4:'lool', 5:'buggy'} > print(i, fortunes[i]) > Or a list/tuple, which saves in typing, memory, and access time. fortunes = ('happy', 'horny', 'messy', 'sad', 'lool', 'buggy') i = random.randrange(len(fortunes)) print(i, fortunes[i]) Or to be lazier still, just use random.choice fortunes = ('happy', 'horny', 'messy', 'sad', 'lool', 'buggy') print(random.choice(fortunes)) None of which actually addresses the OP's issue with input(), but it's nice to get the back half clean as well. -- Rob Gaddi, Highland Technology -- www.highlandtechnology.com Email address domain is currently out of order. See above to fix. -- https://mail.python.org/mailman/listinfo/python-list
Re: error help import random
On Fri, 20 Nov 2015 09:22:10 -0800 (PST), Dylan Riley wrote: >This is my fortune cookie program i wrote in python. >the problem is it will not run past the first line of input. >could someone please identify the error and explain to me why. >here is the code: > >#the program silulates a fortune cookie >#the program should display one of five unique fortunes, at randon, each time >its run > >import random > A problem I used to have is that if you have a file called random.py in the folder when you try to import random, it caused an error. >print(" \\ \\ \\ \\ DYLANS FORTUNE COOKIE \\ \\ \\ ") >print("\n\n\tGood things come to those who wait") >input("\nPress enter to see your fortune") > >fortune = random.randrange(6) + 1 >print(fortune) >if fortune == 1: >print("happy") >elif fortune == 2: >print("horny") >elif fortune == 3: >print("messy") >elif fortune == 4: >print("sad") >elif fortune == 5: >print("lool") > >print("hope ypu enjoyed your fortune being told") >input("\nPress enter to exit") > > >many thanks in advance -- https://mail.python.org/mailman/listinfo/python-list
Re: Mapping between python packages and distro packages?
> I don't know how the program would detect it, but I'd be thinking "the > one where 'sudo apt-get install PACKAGENAME' gets the same code that > 'pip install THING' gets". In a lot of cases, PACKAGENAME will simply > be python-THING or python3-THING, eg python3-sqlalchemy, > python3-scipy, python3-bs4; as a human, that's what I'd try first. But > having a program recognize this would be hugely beneficial. +1 -- Stéphane Wirtel - http://wirtel.be - @matrixise -- https://mail.python.org/mailman/listinfo/python-list
Re: Mapping between python packages and distro packages?
Hi Ben, sorry for my late reply, just forgotten to reply :/ really sorry in fact, I would like to have a database where I want the requests library, I will get the python-requests for debian/ubuntu and the right package for the yum installer. I have an other solution, but I don't like it because I risk to break the linux distribution (the target) and use the wheel package. On 11/18, Ben Finney wrote: > Stephane Wirtel writes: > > > Do you know if there is a library to match a python package (from PyPI) > > and find the right debian/redhat packages ? > > What would count as “the right package”? > > Do you mean “the package that has that PyPI distribution URL in its > ‘debian/watch’ configuration”? > > Do you mean “the package that names that PyPI distribution in its > ‘debian/copyright’ “Source” field”? > > Or something else? > > The answers will differ depending on exactly what question is being > asked of the data. > > If you can define exactly what query you want to perform, perhaps a > solution can be offered. > > -- > \ “The Vatican is not a state.… a state must have territory. This | > `\ is a palace with gardens, about as big as an average golf | > _o__) course.” —Geoffrey Robertson, 2010-09-18 | > Ben Finney > > -- > https://mail.python.org/mailman/listinfo/python-list -- Stéphane Wirtel - http://wirtel.be - @matrixise -- https://mail.python.org/mailman/listinfo/python-list
Re: error help import random
On 11/20/2015 12:22 PM, Dylan Riley wrote: This is my fortune cookie program i wrote in python. the problem is it will not run past the first line of input. could someone please identify the error and explain to me why. here is the code: #the program silulates a fortune cookie #the program should display one of five unique fortunes, at randon, each time its run import random print(" \\ \\ \\ \\ DYLANS FORTUNE COOKIE \\ \\ \\ ") print("\n\n\tGood things come to those who wait") input("\nPress enter to see your fortune") fortune = random.randrange(6) + 1 print(fortune) if fortune == 1: print("happy") elif fortune == 2: print("horny") elif fortune == 3: print("messy") elif fortune == 4: print("sad") elif fortune == 5: print("lool") Use a dict instead of if-elif. i = random.randrange(6) fortunes = {0:'happy', 1:'horny', 2:'messy', 3:'sad', 4:'lool', 5:'buggy'} print(i, fortunes[i]) print("hope ypu enjoyed your fortune being told") input("\nPress enter to exit") -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
Re: String format - resolve placeholders names
Hi Denis, On Fri, Nov 20, 2015 at 05:08:21PM -, Denis McMahon wrote: > On Fri, 20 Nov 2015 16:53:47 +0100, Peter Otten wrote: > > > Ervin Hegedüs wrote: > > >> Python has a good string formatter, eg. I can do this: > > Or even: > > >>> s = "{who} likes {what}" > >>> d = {'who': "Adam", 'what': "ants"} > >>> keys = [x[1] for x in string.Formatter().parse(s)] > >>> keys > ['who', 'what'] > > then ... > > for key in keys: > if key not in d: > raise KeyError("Missing key '{}' in format string '{}'".format > (key, s)) well, I think I'm very satisfied - I got better and more better solutions :). Thanks for all, folks: a. -- I � UTF-8 -- https://mail.python.org/mailman/listinfo/python-list
Re: String format - resolve placeholders names
Hi Peter, On Fri, Nov 20, 2015 at 04:53:47PM +0100, Peter Otten wrote: > Ervin Hegedüs wrote: > > > Python has a good string formatter, eg. I can do this: > > > > s = "{who} likes {what}" > > d = {'who': "Adam", 'what': "ants"} > > s.format(**d) > > > > result: > > 'Adam likes ants' > > > > Is it possible, and if yes, how to resolve the placeholders names > > in string? > > >>> import string > >>> for item in string.Formatter().parse("{who} likes {what}"): > ... print(item) > ... > ('', 'who', '', None) > (' likes ', 'what', '', None) nice solution, thanks, a. -- I � UTF-8 -- https://mail.python.org/mailman/listinfo/python-list
Re: How To Create A Endles List Of Lists In Python...???
On Friday, November 20, 2015 at 10:16:34 AM UTC-8, robert...@si.t-com.hr wrote: > Dana petak, 20. studenoga 2015. u 18:16:52 UTC+1, korisnik Denis McMahon > napisao je: > > On Fri, 20 Nov 2015 08:43:04 +0100, HKRSS wrote: > > > > > Thanks In Advance, Robert...;) > > > > Just keep appending child lists to parent list: > > > > l = [] > > > > while True: > >l.append([]) > > > > Until you run out of memory > > > > But I think that this answer although it appears accurate to the question > > is not a solution for anything useful, because it will just use all the > > memory up. So perhaps you need to express your question in a better > > manner. > > > > -- > > Denis McMahon, denismfmcma...@gmail.com > > I Think That LISP Is Only Solution, I Wil Give Up Frpm Python... > > Thanks, Robert...;) Is There A Reason You're Starting Every Word With A Capital Letter? I mean, really, you're going out of your way and expending extra effort to type incorrectly. -- https://mail.python.org/mailman/listinfo/python-list
Re: How To Create A Endles List Of Lists In Python...???
On Fri, Nov 20, 2015 at 11:58 PM, srinivas devaki wrote: > def __str__(self): > if len(self.list) == 0: > return '(' + str(self.data) + ')[...]' > return ''.join(['(', str(self.data), ')['] + map(str, self.list) + > [', ...]']) > ... > Gist: https://gist.github.com/c0c2ee1e7c6535ef8c3d uhh, there is an error in representing it, the code should be def __str__(self): if len(self.list) == 0: return '(' + str(self.data) + ')[...]' return ''.join(['(', str(self.data), ')[', ', '.join(map(str, self.list)), ', ...]']) Output: (None)[...] (None)[(None)[...], (None)[...], (None)[...], (20)[...], ...] ps: code is updated in gist. -- https://mail.python.org/mailman/listinfo/python-list
Re: How To Create A Endles List Of Lists In Python...???
On Sat, Nov 21, 2015 at 5:16 AM, wrote: > I Think That LISP Is Only Solution, I Wil Give Up Frpm Python... Capital Letters For The Win. You Should Consider Talking In German. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: How To Create A Endles List Of Lists In Python...???
On Fri, Nov 20, 2015 at 11:16 AM, wrote: > Dana petak, 20. studenoga 2015. u 18:16:52 UTC+1, korisnik Denis McMahon > napisao je: >> On Fri, 20 Nov 2015 08:43:04 +0100, HKRSS wrote: >> >> > Thanks In Advance, Robert...;) >> >> Just keep appending child lists to parent list: >> >> l = [] >> >> while True: >>l.append([]) >> >> Until you run out of memory >> >> But I think that this answer although it appears accurate to the question >> is not a solution for anything useful, because it will just use all the >> memory up. So perhaps you need to express your question in a better >> manner. >> >> -- >> Denis McMahon, denismfmcma...@gmail.com > > I Think That LISP Is Only Solution, I Wil Give Up Frpm Python... Nagy and Chris gave you two different perfectly good solutions for Python. -- https://mail.python.org/mailman/listinfo/python-list
Re: How To Create A Endles List Of Lists In Python...???
On Fri, Nov 20, 2015 at 6:39 PM, Chris Angelico wrote: > My crystal ball suggests that defaultdict(list) might be useful here. > > ChrisA I used something similar to this for some problem in hackerrank, anyway i think this is what you want. class defaultlist(object): def __init__(self, factory, data=None): self.factory = factory self.list = [] self.data = data def __getitem__(self, x): if x >= len(self.list): self.list.extend([self.factory() for _ in range(len(self.list), x + 1)]) return self.list[x] def __repr__(self): return str(self) def __str__(self): if len(self.list) == 0: return '(' + str(self.data) + ')[...]' return ''.join(['(', str(self.data), ')['] + map(str, self.list) + [', ...]']) def __setitem__(self, x, v): if x >= len(self.list): self.list.extend([self.factory() for _ in range(len(self.list), x + 1)]) self.list[x] = v def main(): factory = lambda: defaultlist(factory) list_of_lists = defaultlist(factory) print (list_of_lists[0]) list_of_lists[0][10].data = 20 print (list_of_lists[0]) main() Gist: https://gist.github.com/c0c2ee1e7c6535ef8c3d -- https://mail.python.org/mailman/listinfo/python-list
Re: How To Create A Endles List Of Lists In Python...???
Dana petak, 20. studenoga 2015. u 18:16:52 UTC+1, korisnik Denis McMahon napisao je: > On Fri, 20 Nov 2015 08:43:04 +0100, HKRSS wrote: > > > Thanks In Advance, Robert...;) > > Just keep appending child lists to parent list: > > l = [] > > while True: >l.append([]) > > Until you run out of memory > > But I think that this answer although it appears accurate to the question > is not a solution for anything useful, because it will just use all the > memory up. So perhaps you need to express your question in a better > manner. > > -- > Denis McMahon, denismfmcma...@gmail.com I Think That LISP Is Only Solution, I Wil Give Up Frpm Python... Thanks, Robert...;) -- https://mail.python.org/mailman/listinfo/python-list
Re: error help import random
On Fri, Nov 20, 2015 at 10:57 AM, Peter Otten <__pete...@web.de> wrote: > Dylan Riley wrote: > >> input("\nPress enter to see your fortune") > > Make sure that you run your code with Python 3, not Python 2. Or if you must use Python 2, use raw_input() instead of input(). >> fortune = random.randrange(6) + 1 Also, you have an off-by-one error here. randrange(6) will give you an integer between 0 and 5, inclusive (a total of 6 possible values). Adding 1 will then result in an integer between 1 and 6, inclusive, but you don't have a case for a value of 6. -- https://mail.python.org/mailman/listinfo/python-list
Re: Dabbling in web development
Thanks all! -- https://mail.python.org/mailman/listinfo/python-list
Re: error help import random
Dylan Riley wrote: > This is my fortune cookie program i wrote in python. > the problem is it will not run past the first line of input. > could someone please identify the error and explain to me why. > here is the code: > > #the program silulates a fortune cookie > #the program should display one of five unique fortunes, at randon, each > #time its run > > import random > > print(" \\ \\ \\ \\ DYLANS FORTUNE COOKIE \\ \\ \\ ") > print("\n\n\tGood things come to those who wait") > input("\nPress enter to see your fortune") > > fortune = random.randrange(6) + 1 > print(fortune) > if fortune == 1: > print("happy") > elif fortune == 2: > print("horny") > elif fortune == 3: > print("messy") > elif fortune == 4: > print("sad") > elif fortune == 5: > print("lool") > > print("hope ypu enjoyed your fortune being told") > input("\nPress enter to exit") > > > many thanks in advance Make sure that you run your code with Python 3, not Python 2. -- https://mail.python.org/mailman/listinfo/python-list
Re: How can I export data from a website and write the contents to a text file?
On 11/19/2015 12:17 PM, Patrick Hess wrote: > ryguy7272 wrote: >> text_file = open("C:/Users/rshuell001/Desktop/excel/Text1.txt", "wb") >> [...] >> It doesn't seem like the '\n' is doing anything useful. All the text is >> jumbled together. >> [...] >> I finally got it working. It's like this: >> "\r\n" > > The better solution would be to open text files in actual text mode: > > open("filename", "wb") # binary mode > open("filename", "w")# text mode > > In text mode, the correct line-ending characters, which will vary > depending on the operating system, are chosen automatically. It's not just a matter of line endings. It's a matter of text encoding also. This is critical in Python3 where everything is unicode and encoding is essential. You have to to use the text mode when writing files here, and it's also a good idea to specify what encoding you wish to write with (UTF-8 is a good default). -- https://mail.python.org/mailman/listinfo/python-list
Re: error help import random
On Sat, Nov 21, 2015 at 4:22 AM, Dylan Riley wrote: > This is my fortune cookie program i wrote in python. > the problem is it will not run past the first line of input. > could someone please identify the error and explain to me why. > here is the code: > > #the program silulates a fortune cookie > #the program should display one of five unique fortunes, at randon, each time > its run > > import random Actually, you could help us identify the error. What happens when you run it? Show us exactly how you invoke it and what the output is. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
error help import random
This is my fortune cookie program i wrote in python. the problem is it will not run past the first line of input. could someone please identify the error and explain to me why. here is the code: #the program silulates a fortune cookie #the program should display one of five unique fortunes, at randon, each time its run import random print(" \\ \\ \\ \\ DYLANS FORTUNE COOKIE \\ \\ \\ ") print("\n\n\tGood things come to those who wait") input("\nPress enter to see your fortune") fortune = random.randrange(6) + 1 print(fortune) if fortune == 1: print("happy") elif fortune == 2: print("horny") elif fortune == 3: print("messy") elif fortune == 4: print("sad") elif fortune == 5: print("lool") print("hope ypu enjoyed your fortune being told") input("\nPress enter to exit") many thanks in advance -- https://mail.python.org/mailman/listinfo/python-list
Re: How To Create A Endles List Of Lists In Python...???
On Fri, 20 Nov 2015 08:43:04 +0100, HKRSS wrote: > Thanks In Advance, Robert...;) Just keep appending child lists to parent list: l = [] while True: l.append([]) Until you run out of memory But I think that this answer although it appears accurate to the question is not a solution for anything useful, because it will just use all the memory up. So perhaps you need to express your question in a better manner. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: String format - resolve placeholders names
On Fri, 20 Nov 2015 16:53:47 +0100, Peter Otten wrote: > Ervin Hegedüs wrote: >> Python has a good string formatter, eg. I can do this: >> s = "{who} likes {what}" >> d = {'who': "Adam", 'what': "ants"} >> s.format(**d) >> result: >> 'Adam likes ants' >> Is it possible, and if yes, how to resolve the placeholders names in >> string? import string for item in string.Formatter().parse("{who} likes {what}"): > ... print(item) > ... > ('', 'who', '', None) > (' likes ', 'what', '', None) Or even: >>> s = "{who} likes {what}" >>> d = {'who': "Adam", 'what': "ants"} >>> keys = [x[1] for x in string.Formatter().parse(s)] >>> keys ['who', 'what'] then ... for key in keys: if key not in d: raise KeyError("Missing key '{}' in format string '{}'".format (key, s)) -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: What is a function parameter =[] for?
Ian Kelly : > On Fri, Nov 20, 2015 at 9:24 AM, Chris Angelico wrote: >> The cases where that's not true are usually ones that are more like >> C++ overloaded functions: >> >> def next(iter): >> return iter.__next__() >> def next(iter, default): >> try: return iter.__next__() >> except StopIteration: return default > > IMO the version with the default argument should have a different > name, as it is conceptually a different function. I don't necessarily disagree, but consider this function: socket.create_connection(address[, timeout[, source_address]]) https://docs.python.org/3/library/socket.html?highlight=conne ct#socket.create_connection> It has been implemented: _GLOBAL_DEFAULT_TIMEOUT = object() def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None): which is somewhat inconsistent. Why not: def create_connection(address, timeout=None, source_address=None): or: omitted = object() def create_connection(address, timeout=omitted, source_address=omitted): The argument for the former is that neither timeout nor source_address can meaningfully be None. The argument for the latter is that it follows a generic pattern that places no assumptions on the legality or illegality of None as a value. The chosen implementation allows: s.create_connection(address, source_address=None) but not: s.create_connection(address, timeout=None) Marko -- https://mail.python.org/mailman/listinfo/python-list
Re: What is a function parameter =[] for?
On Fri, Nov 20, 2015 at 9:31 AM, Marko Rauhamaa wrote: > Ian Kelly : > >> On Fri, Nov 20, 2015 at 5:28 AM, Marko Rauhamaa wrote: >>> One could argue that you should always use a sentinel object for >>> default values. That also allows you to distinguish between omitted >>> values and default values: >>> >>>def asklist(caption, data, n=omitted, rows=omitted, width=omitted, >>>flags=omitted, buttons=omitted, tablist=omitted, >>>heading=omitted): >>> >>> but that would be rather pedantic in most circumstances. >> >> I think that would be bad design; in general, you shouldn't *need* to >> distinguish whether the value was omitted, because it should always be >> possible to explicitly pass the default value. > > Consider the mutator pattern: > > def name(self, value=omitted): > if value is omitted: > return self._name > self._name = value > > https://en.wikipedia.org/wiki/Mutator_method#C.2B.2B_example> Why would you ever want to do this in a language with properties? -- https://mail.python.org/mailman/listinfo/python-list
Re: What is a function parameter =[] for?
On Sat, Nov 21, 2015 at 3:31 AM, Marko Rauhamaa wrote: > Consider the mutator pattern: > > def name(self, value=omitted): > if value is omitted: > return self._name > self._name = value > > https://en.wikipedia.org/wiki/Mutator_method#C.2B.2B_example> That should DEFINITELY be two functions. Or just an attribute. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: What is a function parameter =[] for?
On Sat, Nov 21, 2015 at 3:29 AM, Ian Kelly wrote: > On Fri, Nov 20, 2015 at 9:24 AM, Chris Angelico wrote: >> The cases where that's not true are usually ones that are more like >> C++ overloaded functions: >> >> def next(iter): >> return iter.__next__() >> def next(iter, default): >> try: return iter.__next__() >> except StopIteration: return default > > IMO the version with the default argument should have a different > name, as it is conceptually a different function. Which would make it like dict.__getitem__ and dict.get, which leads to a lot of people using dict.get() because they don't know about subscripting. And then they mask potential errors because they're using the version that suppresses them, since they didn't even know about the other. Not sure that's an improvement. But I do see the logic in the separation. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: What is a function parameter =[] for?
Ian Kelly : > On Fri, Nov 20, 2015 at 5:28 AM, Marko Rauhamaa wrote: >> One could argue that you should always use a sentinel object for >> default values. That also allows you to distinguish between omitted >> values and default values: >> >>def asklist(caption, data, n=omitted, rows=omitted, width=omitted, >>flags=omitted, buttons=omitted, tablist=omitted, >>heading=omitted): >> >> but that would be rather pedantic in most circumstances. > > I think that would be bad design; in general, you shouldn't *need* to > distinguish whether the value was omitted, because it should always be > possible to explicitly pass the default value. Consider the mutator pattern: def name(self, value=omitted): if value is omitted: return self._name self._name = value https://en.wikipedia.org/wiki/Mutator_method#C.2B.2B_example> Marko -- https://mail.python.org/mailman/listinfo/python-list
Re: What is a function parameter =[] for?
On Fri, Nov 20, 2015 at 9:24 AM, Chris Angelico wrote: > The cases where that's not true are usually ones that are more like > C++ overloaded functions: > > def next(iter): > return iter.__next__() > def next(iter, default): > try: return iter.__next__() > except StopIteration: return default IMO the version with the default argument should have a different name, as it is conceptually a different function. -- https://mail.python.org/mailman/listinfo/python-list
Re: What is a function parameter =[] for?
On Sat, Nov 21, 2015 at 3:16 AM, Ian Kelly wrote: >> One could argue that you should always use a sentinel object for default >> values. That also allows you to distinguish between omitted values and >> default values: >> >>def asklist(caption, data, n=omitted, rows=omitted, width=omitted, >>flags=omitted, buttons=omitted, tablist=omitted, >>heading=omitted): >> >> but that would be rather pedantic in most circumstances. > > I think that would be bad design; in general, you shouldn't *need* to > distinguish whether the value was omitted, because it should always be > possible to explicitly pass the default value. The cases where that's not true are usually ones that are more like C++ overloaded functions: def next(iter): return iter.__next__() def next(iter, default): try: return iter.__next__() except StopIteration: return default You cannot have any actual object to represent the default state, for the same reasons that you can't have __next__ return a magic value to represent "no more values". That's why, in the proposed semantics for an explicit late-binding syntax, I compare with *args notation, which _can_ let you distinguish perfectly. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: What is a function parameter =[] for?
On Fri, Nov 20, 2015 at 5:39 AM, BartC wrote: > * The persistent nonsense that somehow [] is mutable (what happens is that > [] is assigned to a variable, and /that/ is mutable) (And I will probably > get some flak now because 'assign' and 'variable' are meaningless in > Python!) I think the problem here is that you're talking as if [] is a unique value, which it isn't. [] is a list display that *constructs* a list, not a list itself. -- https://mail.python.org/mailman/listinfo/python-list
Re: What is a function parameter =[] for?
On Fri, Nov 20, 2015 at 5:28 AM, Marko Rauhamaa wrote: > The Ackermann function really is an esoteric example, but the other > example that has been discussed here can make practical use of the > default-value semantics: > >[ lambda x: i * x for i in range(4) ] > > which is salvaged with a default value: > >[ lambda x, i=i: i * x for i in range(4) ] > > or, more hygienically: > >[ (lambda i=i: lambda x: i * x)() for i in range(4) ] Note that this last version could be rewritten as: [ (lambda i: lambda x: i * x)(i) for i in range(4) ] At which point the default value semantics are no longer needed. > One could argue that you should always use a sentinel object for default > values. That also allows you to distinguish between omitted values and > default values: > >def asklist(caption, data, n=omitted, rows=omitted, width=omitted, >flags=omitted, buttons=omitted, tablist=omitted, >heading=omitted): > > but that would be rather pedantic in most circumstances. I think that would be bad design; in general, you shouldn't *need* to distinguish whether the value was omitted, because it should always be possible to explicitly pass the default value. -- https://mail.python.org/mailman/listinfo/python-list
Re: shorten "compress" long integer to short ascii.
On 2015-11-20, Vincent Davis wrote: > On Thu, Nov 19, 2015 at 9:27 PM, Paul Rubin wrote: > >> You can't improve much. A decimal digit carries log(10,2)=3.32 bits >> of information. A reasonable character set for Twitter-style links >> might have 80 or so characters (upper/lower alphabetic, digits, and >> a dozen or so punctuation characters), or log(80,2)= >> > > Where do I find out more about the how to calculate information per > digit? There are 10 possible states for a decimal digit. The number of digits required to represent N states in base M is log(N,M). -- Grant Edwards grant.b.edwardsYow! Are we on STRIKE yet? at gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: How To Create A Endles List Of Lists In Python...???
On 2015-11-20, HKRSS wrote: > > Sorry For Bad Question, But I need List Of Lists That I Can > Acces Horyzontaly, Not In The Deep(But This IS Not All, > I End That Evey List In List Of Lists Can Be A List... > > Thanks In Advance... > Robert..;) Not only was that genuine frontier gibberish, it expressed... something? -- Grant Edwards grant.b.edwardsYow! I feel partially at hydrogenated! gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: String format - resolve placeholders names
Ervin Hegedüs wrote: > Python has a good string formatter, eg. I can do this: > > s = "{who} likes {what}" > d = {'who': "Adam", 'what': "ants"} > s.format(**d) > > result: > 'Adam likes ants' > > Is it possible, and if yes, how to resolve the placeholders names > in string? >>> import string >>> for item in string.Formatter().parse("{who} likes {what}"): ... print(item) ... ('', 'who', '', None) (' likes ', 'what', '', None) -- https://mail.python.org/mailman/listinfo/python-list
Re: String format - resolve placeholders names
Hello Chris, On Sat, Nov 21, 2015 at 02:06:11AM +1100, Chris Angelico wrote: > On Sat, Nov 21, 2015 at 1:52 AM, Ervin Hegedüs wrote: > > Python has a good string formatter, eg. I can do this: > > > > s = "{who} likes {what}" > > d = {'who': "Adam", 'what': "ants"} > > s.format(**d) ... > > But is there any other (direct) way, which keywords exists in > > string? > > I think what you're asking for can be done using format_map with a > custom mapping object: > > >>> class IdentiMap: > ... def __init__(self): > ... self.keys = [] > ... def __getitem__(self, key): > ... self.keys.append(key) > ... > >>> m = IdentiMap() > >>> "{who} likes {what}".format_map(m) > 'None likes None' > >>> m.keys > ['who', 'what'] > > Does that help? absolutely, many thanks again! a. -- https://mail.python.org/mailman/listinfo/python-list
Re: String format - resolve placeholders names
On Sat, Nov 21, 2015 at 1:52 AM, Ervin Hegedüs wrote: > Python has a good string formatter, eg. I can do this: > > s = "{who} likes {what}" > d = {'who': "Adam", 'what': "ants"} > s.format(**d) > > result: > 'Adam likes ants' > > Is it possible, and if yes, how to resolve the placeholders names > in string? > > There is a know method: > > d1 = {'who1': "Adam", 'what1': "ants"} > try: > s.format(**d1) > except KeyError: > print("keyword missing") > > (gives 'keyword missing' as result). > > > But is there any other (direct) way, which keywords exists in > string? I think what you're asking for can be done using format_map with a custom mapping object: >>> class IdentiMap: ... def __init__(self): ... self.keys = [] ... def __getitem__(self, key): ... self.keys.append(key) ... >>> m = IdentiMap() >>> "{who} likes {what}".format_map(m) 'None likes None' >>> m.keys ['who', 'what'] Does that help? ChrisA -- https://mail.python.org/mailman/listinfo/python-list
String format - resolve placeholders names
Hi, Python has a good string formatter, eg. I can do this: s = "{who} likes {what}" d = {'who': "Adam", 'what': "ants"} s.format(**d) result: 'Adam likes ants' Is it possible, and if yes, how to resolve the placeholders names in string? There is a know method: d1 = {'who1': "Adam", 'what1': "ants"} try: s.format(**d1) except KeyError: print("keyword missing") (gives 'keyword missing' as result). But is there any other (direct) way, which keywords exists in string? Thanks, a. -- https://mail.python.org/mailman/listinfo/python-list
Re: What is a function parameter =[] for?
On 2015-11-20, BartC wrote: > Finally, a down-to-earth example. Here it probably doesn't matter at > what point 'global_database' gets bound. You know it will always refer > to the current state of global_database, and you know that it is a data > structure external to the function even if it is updated from inside. > > That is a bit different from an empty list that later is not empty. Why is it different? The only difference is that you're thinking of it as "this particular database" rather than "a database containing this particular data", but I'd argue you can say the same for the list. -- https://mail.python.org/mailman/listinfo/python-list
Re: download
On 20/11/2015 13:48, Dennis Lee Bieber wrote: On Fri, 20 Nov 2015 10:52:53 +0100, marozzyye declaimed the following: i am about to download python 3.5.0 but there are three options 1.windows x86 web-based installer 2.windows x86 executable installer 3.windows x86 embeddable zip file i have tried no.1 but while installing there was an error. so which do i pick? A) If you are running Windows XP, NONE OF THE ABOVE. 3.5 does not run on WinXP B) What site is offering those? I just went to python.org, and the 3.5 download button (just the one -- no options for type of file) only provides a downloadable EXE installer (note: I normally use the ActiveState installers rather than python.org) Compare https://www.python.org/downloads/ which I believe is being referred to above, to https://www.python.org/ and hover your mouse over "downloads" and then "Python 3.5.0", this offers a web install exe, to https://www.python.org/downloads/windows/ which offers everything including the kitchen sink. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: What is a function parameter =[] for?
On 2015-11-20, Dennis Lee Bieber wrote: > You can substitute list() where ever you use [] with > no > effective change in the semantics. (I wouldn't be surprised if the parser > was doing that behind the scenes anyway). No, because list() does a name lookup on "list" (which is the primary issue behind every request for frozendict/frozenset literals) -- https://mail.python.org/mailman/listinfo/python-list
Re: shorten "compress" long integer to short ascii.
On Thu, Nov 19, 2015 at 9:27 PM, Paul Rubin wrote: > You can't improve much. A decimal digit carries log(10,2)=3.32 bits > of information. A reasonable character set for Twitter-style links > might have 80 or so characters (upper/lower alphabetic, digits, and > a dozen or so punctuation characters), or log(80,2)= > Where do I find out more about the how to calculate information per digit? Lots of nice little tricks you used below. Thanks for sharing. > Here is my shortened version: > > import string > > # alphabet here is 83 chars > alphabet = string.ascii_lowercase + \ >string.ascii_uppercase +'!"#$%&\'()*+,-./:;<=>?@[]^_`{|}~' > alphabet_size = len(alphabet) > > decoderdict = dict((b,a) for a,b in enumerate(alphabet)) > > def encoder(integer): > a,b = divmod(integer, alphabet_size) > if a == 0: return alphabet[b] > return encoder(a) + alphabet[b] > > def decoder(code): > return reduce(lambda n,d: n*alphabet_size + decoderdict[d], code, 0) > > def test(): > n = 92928729379271 > short = encoder(n) > backagain = decoder(short) > nlen = len(str(n)) > print (nlen, len(short), float(len(short))/nlen) > assert n==backagain, (n,short,b) > > test() > Vincent Davis 720-301-3003 -- https://mail.python.org/mailman/listinfo/python-list
Re: Late-binding of function defaults (was Re: What is a function parameter =[] for?)
On 19/11/2015 22:41, Laura Creighton wrote: In a message of Thu, 19 Nov 2015 22:57:10 +0200, Marko Rauhamaa writes: Note: Ned Bachelder (who is probably reading this on python-list anyway added cc on this mail, as if I am to discuss somebody, however briefly, they deserve to hear about it. Which may irritate him to get 2 copies instead of one, but so it goes. I am talking about BartC as well, but since this is his thread, I assume he is here.) Actually that thread was started by 'fl'. Sometimes you want to understand what you are doing. Sometimes you just want to do it. And sometimes, well, the only real way to get an understanding of what you are doing is to do it more. This is, in my opinion, Bartc's problem. He doesn't program in python enough to understand it more. That's true. I'll have to do a substantial project soon. But a lot of my interest is about comparisons between Python and the languages I work on. (Especially of speed. Up to now my interpreters have been comfortably faster. But with PyPy I might now have do do a bit more work on mine next year. This is where a proper application is needed for comparison and not small benchmarks.) I'm also interested in what handy features I can 'borrow' from Python. Enough that I was planning a big upgrade earlier this year to bring it more into line with how Python works. (/That/ is a good way of learning about a language! To try and implement a lookalike.) But that was changing my language too much (I was losing too many features of my own) so it was abandoned. (Perhaps it can be a separate, higher level language at some point as I quite like the Python style even if I have misgivings about some features.) They have the opposite problem of BartC -- they want to be excellent programmers without understanding anything, while he wants to understand everything before he knows how to write decent python code. I can already tell you that I will never be able to write 'Pythonic' code if that is what you mean by 'decent'. But at least everyone will be able to understand it! -- Bartc -- https://mail.python.org/mailman/listinfo/python-list
Re: What is a function parameter =[] for?
On Friday, November 20, 2015 at 7:40:37 AM UTC-5, BartC wrote: > On 20/11/2015 12:12, Ned Batchelder wrote: > > On Friday, November 20, 2015 at 6:59:54 AM UTC-5, BartC wrote: > >> On 20/11/2015 01:05, Steven D'Aprano wrote: > >>> On Fri, 20 Nov 2015 04:30 am, BartC wrote: > >>> > On 19/11/2015 16:01, Steven D'Aprano wrote: > >>> [...] > >>> > The whole concept of 'mutable' default is alien to me. A default is just > a convenient device to avoid having to write: > > fn(0) or fn("") or fn([]) > >>> > >>> Says who? > >> > >> People who want to avoid having to write: > >> > >>fn(0) or fn("") or fn([]) > > > > I think we all understand by now that you are unhappy with what happens > > in Python with mutable defaults. We get it. You are not alone. Lots of > > people are surprised by this. But it is how Python works. > > > > I'm not sure what your goal is at this point. Are you: > > > >1) still unsure what the behavior is, or > >2) trying to understand why it behaves that way, or > >3) hoping to change Python, or > >4) trying to convince us that your language is better, or > >5) something else? > > Mostly 5. (With a bit of 4. However that language is not something I'm > selling or pushing. It's just something different used as a contrast.). > > What's bothering me is: Let me try to answer some of these. > > * The large amount of mumbo-jumbo used to describe what's going on We try not to use mumbo-jumbo, we use terms that can be confusing sometimes. This page was recommended early on in this thread: http://nedbatchelder.com/text/names1.html It is my best attempt to lay out many of the issues here. I hope you have had a chance to read/watch it. > * The insistence (I think largely from Steven) that the way this feature > works is good rather than bad I think the fairest summary is that the way this works is better than the alternatives, when you take into account the desire to keep the semantics of the language simple. > * The refusal to acknowledge that the def fn(a=[]) syntax is misleading. > (What value will a have when you call fn()? The true answer is that you > can't tell.) I completely agree with you that the syntax surprises people. Anyone who claims that it isn't surprising is ignoring the abundant empirical evidence that people new to Python (and even some who have been using it for a long time) are surprised by this. But it is not true that "you can't tell" what value a will have. You have been surprised by it, but I am confident that if we could sit together, I could explain to you what value you would get, and it would be clear to you. You might not like the answer, and it might not be what you first imagined, but it is not unpredictable. > * The persistent nonsense that somehow [] is mutable (what happens is > that [] is assigned to a variable, and /that/ is mutable) (And I will > probably get some flak now because 'assign' and 'variable' are > meaningless in Python!) As others have explained, [] is a value, a list. Lists are mutable. a = [] # Create an empty list a.append(1) # and mutate that list. If we don't agree on this, then please please please go and look at the page I linked above. This is a central concept in Python, and we aren't going to be able to get anywhere if we can't agree on this. > * And above, where I lay out /why/ people want to use the feature, so > that the function can take care of some details, even that is refuted. I understand why you want to use the feature. It would be nice if it came out the way you (and many others) want. But it doesn't. --Ned. -- https://mail.python.org/mailman/listinfo/python-list
Re: How To Create A Endles List Of Lists In Python...???
Dana petak, 20. studenoga 2015. u 14:06:31 UTC+1, korisnik Nagy László Zsolt napisao je: > > Sorry For Bad Question, But I need List Of Lists That I Can > > Acces Horyzontaly, Not In The Deep(But This IS Not All, > > I End That Evey List In List Of Lists Can Be A List... > It is not possible to do it with a native list. But you can write your > own iterable that can be iterated forever, and indexed with an integer. > > But before you do that: what is this needed for? To Make A Turing Machine That Accepts A Classes (This Is My Idea, And Must Be Published By Me, And I Don't Respond How I Think Make This Machine)... Thanks, Robert...;) -- https://mail.python.org/mailman/listinfo/python-list
Re: How To Create A Endles List Of Lists In Python...???
On Sat, Nov 21, 2015 at 12:06 AM, Nagy László Zsolt wrote: >> Sorry For Bad Question, But I need List Of Lists That I Can >> Acces Horyzontaly, Not In The Deep(But This IS Not All, >> I End That Evey List In List Of Lists Can Be A List... > It is not possible to do it with a native list. But you can write your > own iterable that can be iterated forever, and indexed with an integer. > > But before you do that: what is this needed for? My crystal ball suggests that defaultdict(list) might be useful here. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: How To Create A Endles List Of Lists In Python...???
> Sorry For Bad Question, But I need List Of Lists That I Can > Acces Horyzontaly, Not In The Deep(But This IS Not All, > I End That Evey List In List Of Lists Can Be A List... It is not possible to do it with a native list. But you can write your own iterable that can be iterated forever, and indexed with an integer. But before you do that: what is this needed for? -- https://mail.python.org/mailman/listinfo/python-list
Re: What is a function parameter =[] for?
On Fri, Nov 20, 2015 at 11:39 PM, BartC wrote: > * The refusal to acknowledge that the def fn(a=[]) syntax is misleading. > (What value will a have when you call fn()? The true answer is that you > can't tell.) It isn't misleading. The default value for the argument is set when the function is defined, and it is set to the *object* that results from evaluating the *expression* given. After that, the *object* is the one you will always get (barring shenanigans) if the argument is omitted. If the value of that object changes, it changes! You keep expecting the *value* to be consistent. But what you actually get is that the *object* is consistent. It's virtually impossible to guarantee the former, in the face of mutable objects. > * The persistent nonsense that somehow [] is mutable (what happens is that > [] is assigned to a variable, and /that/ is mutable) (And I will probably > get some flak now because 'assign' and 'variable' are meaningless in > Python!) What happens is that [] evaluates to an object, and *that object* is mutable. Python does not store the syntactic element "[]" (empty list-display), but instead stores (a reference to) the object. It's exactly the same as: def fn(a=list()): ... def generate_list(): return [] def fn(a=generate_list()): ... initial_list = [] def fn(a=initial_list): ... import sys def fn(a=[x*3+424 for x in range(not sys)]): """how ridiculous would you like to go?""" Every one of these constructs exactly one new list, *when it is evaluated*, which is at function definition time. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: What is a function parameter =[] for?
On 20/11/2015 12:28, Marko Rauhamaa wrote: BartC : We're arguing at cross-purposes then since you are obviously interested in these esoteric aspects, The Ackermann function really is an esoteric example, but the other example that has been discussed here can make practical use of the default-value semantics: And you go on to give a couple of slightly less esoteric examples! (I don't think I've ever written a lambda function in my life.) Even more appropriately, you may expressly want a mutable, singleton object to be the default: def initiate_query(query, database=global_database): Finally, a down-to-earth example. Here it probably doesn't matter at what point 'global_database' gets bound. You know it will always refer to the current state of global_database, and you know that it is a data structure external to the function even if it is updated from inside. That is a bit different from an empty list that later is not empty. def asklist(caption, data, n=omitted, rows=omitted, width=omitted, flags=omitted, buttons=omitted, tablist=omitted, heading=omitted): but that would be rather pedantic in most circumstances. Yes, that's along the lines of what I used do before I had proper default values! Then I had code inside the function to test a parameter and set it as needed. I still do this when the default isn't straightforward (where it depends on other parameters for example). -- Bartc -- https://mail.python.org/mailman/listinfo/python-list
Re: What is a function parameter =[] for?
On 20/11/2015 12:12, Ned Batchelder wrote: On Friday, November 20, 2015 at 6:59:54 AM UTC-5, BartC wrote: On 20/11/2015 01:05, Steven D'Aprano wrote: On Fri, 20 Nov 2015 04:30 am, BartC wrote: On 19/11/2015 16:01, Steven D'Aprano wrote: [...] The whole concept of 'mutable' default is alien to me. A default is just a convenient device to avoid having to write: fn(0) or fn("") or fn([]) Says who? People who want to avoid having to write: fn(0) or fn("") or fn([]) I think we all understand by now that you are unhappy with what happens in Python with mutable defaults. We get it. You are not alone. Lots of people are surprised by this. But it is how Python works. I'm not sure what your goal is at this point. Are you: 1) still unsure what the behavior is, or 2) trying to understand why it behaves that way, or 3) hoping to change Python, or 4) trying to convince us that your language is better, or 5) something else? Mostly 5. (With a bit of 4. However that language is not something I'm selling or pushing. It's just something different used as a contrast.). What's bothering me is: * The large amount of mumbo-jumbo used to describe what's going on * The insistence (I think largely from Steven) that the way this feature works is good rather than bad * The refusal to acknowledge that the def fn(a=[]) syntax is misleading. (What value will a have when you call fn()? The true answer is that you can't tell.) * The persistent nonsense that somehow [] is mutable (what happens is that [] is assigned to a variable, and /that/ is mutable) (And I will probably get some flak now because 'assign' and 'variable' are meaningless in Python!) * And above, where I lay out /why/ people want to use the feature, so that the function can take care of some details, even that is refuted. -- Bartc -- https://mail.python.org/mailman/listinfo/python-list
Re: What is a function parameter =[] for?
BartC : > On 20/11/2015 01:05, Steven D'Aprano wrote: >> On Fri, 20 Nov 2015 04:30 am, BartC wrote: >>> The whole concept of 'mutable' default is alien to me. A default is just >>> a convenient device to avoid having to write: >>> >>> fn(0) or fn("") or fn([]) >> >> Says who? > > People who want to avoid having to write: > > fn(0) or fn("") or fn([]) Undoubtedly a mutable default value can lead to accidents. However, I already showed C++ default values can also be mutable and lead to analogous problems, so the question is not related to Python alone. If there is a risk of a default [] or {} ending up in the wrong hands, you can always write your function with a sentinel: omitted = object() def f(collection=omitted): if collection is omitted: collection = [] ... > We're arguing at cross-purposes then since you are obviously > interested in these esoteric aspects, The Ackermann function really is an esoteric example, but the other example that has been discussed here can make practical use of the default-value semantics: [ lambda x: i * x for i in range(4) ] which is salvaged with a default value: [ lambda x, i=i: i * x for i in range(4) ] or, more hygienically: [ (lambda i=i: lambda x: i * x)() for i in range(4) ] Even more appropriately, you may expressly want a mutable, singleton object to be the default: def initiate_query(query, database=global_database): > but all I want to do is avoid remembering a long list of defaults. > Here's an example from another language, a function I'm working on at > the minute: > > function asklist(caption,&data,n=1, rows=10, width=50, flags="", > buttons=(), tablist=(), heading="")= One could argue that you should always use a sentinel object for default values. That also allows you to distinguish between omitted values and default values: def asklist(caption, data, n=omitted, rows=omitted, width=omitted, flags=omitted, buttons=omitted, tablist=omitted, heading=omitted): but that would be rather pedantic in most circumstances. Marko -- https://mail.python.org/mailman/listinfo/python-list
Re: What is a function parameter =[] for?
On Friday, November 20, 2015 at 6:59:54 AM UTC-5, BartC wrote: > On 20/11/2015 01:05, Steven D'Aprano wrote: > > On Fri, 20 Nov 2015 04:30 am, BartC wrote: > > > >> On 19/11/2015 16:01, Steven D'Aprano wrote: > > [...] > > > >> The whole concept of 'mutable' default is alien to me. A default is just > >> a convenient device to avoid having to write: > >> > >> fn(0) or fn("") or fn([]) > > > > Says who? > > People who want to avoid having to write: > > fn(0) or fn("") or fn([]) I think we all understand by now that you are unhappy with what happens in Python with mutable defaults. We get it. You are not alone. Lots of people are surprised by this. But it is how Python works. I'm not sure what your goal is at this point. Are you: 1) still unsure what the behavior is, or 2) trying to understand why it behaves that way, or 3) hoping to change Python, or 4) trying to convince us that your language is better, or 5) something else? --Ned. -- https://mail.python.org/mailman/listinfo/python-list
Re: What is a function parameter =[] for?
On 20/11/2015 01:05, Steven D'Aprano wrote: On Fri, 20 Nov 2015 04:30 am, BartC wrote: On 19/11/2015 16:01, Steven D'Aprano wrote: [...] The whole concept of 'mutable' default is alien to me. A default is just a convenient device to avoid having to write: fn(0) or fn("") or fn([]) Says who? People who want to avoid having to write: fn(0) or fn("") or fn([]) Here's another use for function defaults, as static storage: # Ackermann's function def ack(m, n, _memo={}): key = m, n if key not in _memo: if m==0: v = n + 1 elif n==0: v = ack(m-1, 1) else: v = ack(m-1, ack(m, n-1)) _memo[key] = v return _memo[key] This is a quick and easy way to memoise a function which would otherwise be horribly slow. And it only works because _memo is bound to a mutable object once, and once only. We're arguing at cross-purposes then since you are obviously interested in these esoteric aspects, but all I want to do is avoid remembering a long list of defaults. Here's an example from another language, a function I'm working on at the minute: function asklist(caption,&data,n=1, rows=10, width=50, flags="", buttons=(), tablist=(), heading="")= 9 parameters, 7 of them optional. This is designed to be used with keyword arguments which is where the default values come into their own, as you don't need to remember positional order either. Very basic stuff and very obvious what it's for. Notice some defaults are () (empty lists here), which are the ones that cause bother in Python. (Here, however, the language doesn't like you doing in-place modification of a parameter unless the '&' is used, in which case you wouldn't be able to assign a default value such as () as you can only pass l-values.) def test(arg=[]): arg.append(1) return len(arg) The binding arg=[] is NOT inside the body of the function. Therefore, it is NOT executed repeatedly, but only once. OK, so the "=" is misleading if not a lie. So you didn't bother reading the LRM either! LRM? Left Right Manual? Language Reference Manual. That [] doesn't look like an object that could change. Of course it does. You've lost me know. a = [] a.append(1) Are you shocked to learn that a is no longer an empty list? No. But I would be surprised if, after this point, [] is no longer an empty list either! No, forget that; by now, I wouldn't be surprised at all! (That [] isn't changed is probably thanks to [] being implemented with the BUILD_LIST byte-code, which constructs a brand-new empty list each time. So the next time [] is used, it will be a different one from the one that has just been appended to. In my language, a construct such as [10,20,30] is evaluated just once at start-up. If Python did the same, then I suspect such a literal could conceivably be changed if just "=" was used to __[1] it to 'a'.) ([1] To avoid further argument, insert your own choice of jargon here.) -- Bartc -- https://mail.python.org/mailman/listinfo/python-list
Re: How To Create A Endles List Of Lists In Python...???
"Peter Otten" <__pete...@web.de> wrote in message news:mailman.510.1448009596.16136.python-l...@python.org... > HKRSS wrote: > >> Thanks In Advance, Robert...;) > list_of_lists = [] list_of_lists.append(list_of_lists) list_of_lists[0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0] > [[...]] > Sorry For Bad Question, But I need List Of Lists That I Can Acces Horyzontaly, Not In The Deep(But This IS Not All, I End That Evey List In List Of Lists Can Be A List... Thanks In Advance... Robert..;) -- https://mail.python.org/mailman/listinfo/python-list
download
i am about to download python 3.5.0 but there are three options 1.windows x86 web-based installer 2.windows x86 executable installer 3.windows x86 embeddable zip file i have tried no.1 but while installing there was an error. so which do i pick? -- https://mail.python.org/mailman/listinfo/python-list
Re: How To Create A Endles List Of Lists In Python...???
HKRSS wrote: > Thanks In Advance, Robert...;) >>> list_of_lists = [] >>> list_of_lists.append(list_of_lists) >>> list_of_lists[0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0] [[...]] -- https://mail.python.org/mailman/listinfo/python-list
Re: Late-binding of function defaults (was Re: What is a function parameter =[] for?)
dieter writes: > Chris Angelico writes: > >> IMO it's controversial mainly because there's an easy and obvious >> syntax for early binding, but late binding doesn't have syntactic >> support, and all the options are imperfect. > > I do not think that we should get additional syntax for lately bound > default values. It would explicitely introduce the concepts early > versus late binding which are likely difficult to understand by many > users. I'm confused by the term. I don't like it one bit. "Early binding" of a default value seems to mean that the expression that produces the default value of a function parameter is evaluated when the function is defined. "Late binding" seems to mean that the expression is evaluated when the function is called. In both cases the actual binding of the parameter to the value (either the default or an actual argument) is established when the function is called. Several different bindings of that same parameter to different values can hold simultaneously, so the *binding* has to be conceptually "late". Because recursion. Why isn't the evaluation of the default expression called evaluation? Or at least something that doesn't already mean something else that is as crucially important as, well, I've already given up on talking about REDACTED and REDACTED in connection with Python, and here I see related established terminology used for something else *for no reason that I can see*. I see no *need* to call this other thing "binding". -- https://mail.python.org/mailman/listinfo/python-list
Re: non-blocking getkey?
On Thu, Nov 19, 2015 at 10:31 AM, Michael Torrie wrote: > One windows it might be possible to use the win32 api to enumerate the > windows, find your console window and switch to it. You can call GetConsoleWindow [1] and then SetForegroundWindow [2]. import os import sys try: import tkinter from tkinter import filedialog except ImportError: import Tkinter as tkinter import tkFileDialog as filedialog input = raw_input if sys.platform == 'win32': import ctypes kernel32 = ctypes.WinDLL('kernel32') user32 = ctypes.WinDLL('user32') def setfgwin(): hcon = kernel32.GetConsoleWindow() if hcon and user32.SetForegroundWindow(hcon): return True return False def get_filename(): filename = filedialog.askopenfilename() setfgwin() return os.path.normpath(filename) if __name__ == '__main__': root = tkinter.Tk() root.withdraw() filename = get_filename() print('filename: %s' % filename) input('press enter...') [1]: https://msdn.microsoft.com/en-us/library/ms683175 [2]: https://msdn.microsoft.com/en-us/library/ms633539 -- https://mail.python.org/mailman/listinfo/python-list
Re: How To Create A Endles List Of Lists In Python...???
I Think That There Are Two Ways: 1)Harder Way Use Procedural C... 2)Easier Way Use LISP... "HKRSS" wrote in message news:n2miu8$fl4$1...@ls237.t-com.hr... > Thanks In Advance, Robert...;) > > -- https://mail.python.org/mailman/listinfo/python-list
How To Create A Endles List Of Lists In Python...???
Thanks In Advance, Robert...;) -- https://mail.python.org/mailman/listinfo/python-list