From alan.gauld at btinternet.com Fri Apr 1 04:17:25 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 1 Apr 2016 09:17:25 +0100 Subject: [Tutor] Week 10 warmup assignment In-Reply-To: References: Message-ID: On 01/04/16 04:26, Daniella Sapozhnikova wrote: > Umm I'm new to this whole tutoring list and I'm having a little bit of > trouble in school with my programming classes (hopefully it's not too late > to pass my class) but anyway, here's the code I've written: > > > #!/usr/bin/env python > # -*- coding: utf-8 -*- > """Task 07: declaring a dictionary, creating a function, > return a funky total """ > > > DATA = {2: 7493945, > 76: 4654320, > 3: 4091979, > 90: 1824881, > 82: 714422, > 45: 1137701, > 10: 374362, > 0: 326226, > -15: 417203, > -56: 333525, > 67: 323451, > 99: 321696, > 21: 336753, > -100: 361237, > 55: 1209714, > 5150: 1771800, > 42: 4714011, > 888: 14817667, > 3500: 13760234, > 712: 10903322, > 7: 10443792, > 842: 11716264, > 18584: 10559923, > 666: 9275602, > 70: 11901200, > 153: 12074784, > 8: 4337229} > > > def iter_dict_funky_sum(**DATA): > """function that takes one dictionary argument declaring > a running total variable, extracting key/value pairs from > DATA simultaneously in a for loop, assigning and appending > the product of the value minus the key to the running total > variable and returning the total.""" > funky = 0 > for key, value in DATA.iteritems(): > funky += value - key > return funky > > > Now, everything it's returning is correct, the only problems I'm having is > the 2 errors pylint is throwing me, which are: > task_07.py:36: [W0621(redefined-outer-name), iter_dict_funky_sum] > Redefining name 'DATA' from outer scope (line 7) > task_07.py:36: [C0103(invalid-name), iter_dict_funky_sum] Invalid argument > name "DATA" > > What does it mean and how can I fix it? It means you have the same name for your parameter as for your global variable which is potentially confusing, so change the name of your parameter. Also you don't need the ** in front of DATA in the function definition. Finally, you say it's working but you don't actually call your function in your code. How are you exercising it? Did you just miss that bit out or are you importing at the >>> prompt? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From dyoo at hashcollision.org Fri Apr 1 14:45:50 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 1 Apr 2016 11:45:50 -0700 Subject: [Tutor] Week 10 warmup assignment In-Reply-To: References: Message-ID: Hi Daniella, Your class is using an additional tool called 'pylint' which enforces certain style conventions. One of those conventions that Pylint is checking is that variables as arguments aren't supposed to be all in upper case. Upper case is a convention for constants, and a variable is not a constant, unchanging thing. (For those who are interested, Pylint's enforcement of this rule can be found here: http://pylint-messages.wikidot.com/messages:c0103) That's what the tool is trying to tell you when it gives you this error message: > task_07.py:36: [C0103(invalid-name), iter_dict_funky_sum] Invalid argument > name "DATA" About how this list works: please feel free to ask questions if there's something you don't understand, and we'll try to point you in the right direction. :P We won't do homework assignments, just to be clear, but we will be very happy to help answer your questions and clear misunderstandings. From N.Bouali at aui.ma Fri Apr 1 15:46:28 2016 From: N.Bouali at aui.ma (Nacir Bouali) Date: Fri, 1 Apr 2016 19:46:28 +0000 Subject: [Tutor] Fw: About the Round Function Message-ID: -----Forwarded by Nacir Bouali/sse/stud/aui/ma on 04/01/2016 08:46PM ----- To: tutor at python.org From: Nacir Bouali/sse/stud/aui/ma Date: 11/14/2015 08:21PM Subject: About the Round Function Dear Python Tutor(s), My students and I are interested in knowing the rationale behind Python's choice of the Banker's rounding algorithm to be the default rounding algorithm in the third release of Python. We'd also like to know how the function is actually implemented. Regards, Nacir From breamoreboy at yahoo.co.uk Fri Apr 1 19:05:33 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 2 Apr 2016 00:05:33 +0100 Subject: [Tutor] Fw: About the Round Function In-Reply-To: References: Message-ID: On 01/04/2016 20:46, Nacir Bouali wrote: > -----Forwarded by Nacir Bouali/sse/stud/aui/ma on 04/01/2016 08:46PM ----- > To: tutor at python.org > From: Nacir Bouali/sse/stud/aui/ma > Date: 11/14/2015 08:21PM > Subject: About the Round Function > > Dear Python Tutor(s), > My students and I are interested in knowing the rationale behind Python's > choice of the Banker's rounding algorithm to be the default rounding > algorithm in the third release of Python. I'm sorry but I do not understand the above at all, what third release of Python, for what type of Python object, please explain? > We'd also like to know how the function is actually implemented. I'm sorry but I cannot say until you give us precise details as I've asked above. > Regards, > Nacir -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From dyoo at hashcollision.org Fri Apr 1 21:01:39 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 1 Apr 2016 18:01:39 -0700 Subject: [Tutor] Fw: About the Round Function In-Reply-To: References: Message-ID: > My students and I are interested in knowing the rationale behind Python's > choice of the Banker's rounding algorithm to be the default rounding > algorithm in the third release of Python. To be specific: your question is on the toplevel round() function. https://docs.python.org/3/library/functions.html#round The assumption implicit in the question is that Python is the only system that does this. However, it's not just Python: the general "IEEE 754" standard says to do this. https://en.wikipedia.org/wiki/Rounding#Round_half_to_even There's more background information here: http://www.lahey.com/float.htm --- The rest of this is very-deep diving: if you are a beginner to Python, I strongly recommend skipping the rest of this. Let me double check where the rounding is happening, just for my own peace of mind. According the source code, in Python 2: https://github.com/python-git/python/blob/master/Python/bltinmodule.c#L2064 it does its own thing, and we can see in in terms of floor() and ceiling(). What about in Python 3? If we look at the latest code, http://svn.python.org/projects/python/trunk/Python/bltinmodule.c, and look for "builtin_round", it tells us to look at the '_Py_double_round' function defined in floatobject.c, http://svn.python.org/projects/python/trunk/Objects/floatobject.c which in fact does appear to have its own implementation of rounding, with the internal comment C: /* The basic idea is very simple: convert and round the double to a decimal string using _Py_dg_dtoa, then convert that decimal string back to a double with _Py_dg_strtod. There's one minor difficulty: Python 2.x expects round to do round-half-away-from-zero, while _Py_dg_dtoa does round-half-to-even. So we need some way to detect and correct the halfway cases. Detection: a halfway value has the form k * 0.5 * 10**-ndigits for some odd integer k. Or in other words, a rational number x is exactly halfway between two multiples of 10**-ndigits if its 2-valuation is exactly -ndigits-1 and its 5-valuation is at least -ndigits. For ndigits >= 0 the latter condition is automatically satisfied for a binary float x, since any such float has nonnegative 5-valuation. For 0 > ndigits >= -22, x needs to be an integral multiple of 5**-ndigits; we can check this using fmod. For -22 > ndigits, there are no halfway cases: 5**23 takes 54 bits to represent exactly, so any odd multiple of 0.5 * 10**n for n >= 23 takes at least 54 bits of precision to represent exactly. Correction: a simple strategy for dealing with halfway cases is to (for the halfway cases only) call _Py_dg_dtoa with an argument of ndigits+1 instead of ndigits (thus doing an exact conversion to decimal), round the resulting string manually, and then convert back using _Py_dg_strtod. */ Suffice it to say, this is probably too much detail already. From ben+python at benfinney.id.au Fri Apr 1 21:13:46 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 02 Apr 2016 12:13:46 +1100 Subject: [Tutor] Fw: About the Round Function References: Message-ID: <85twjk95it.fsf@benfinney.id.au> Nacir Bouali writes: > My students and I are interested in knowing the rationale behind > Python's choice of the Banker's rounding algorithm to be the default > rounding algorithm in the third release of Python. Can you provide a link to the Python documentation for this? The term ?Banker's rounding algorithm? is not familiar to me. What does the Python documentation say about it, and where? > We'd also like to know how the function is actually implemented. What kind of answer to ?how it is implemented? do you want? At one level, it can be answered with the source code of CPython . Perhaps you want a different answer, but what? -- \ ?We spend the first twelve months of our children's lives | `\ teaching them to walk and talk and the next twelve years | _o__) telling them to sit down and shut up.? ?Phyllis Diller | Ben Finney From daniellasapo at gmail.com Fri Apr 1 21:21:02 2016 From: daniellasapo at gmail.com (Daniella Sapozhnikova) Date: Fri, 1 Apr 2016 21:21:02 -0400 Subject: [Tutor] Alan G Week 10 warmup assignment help Message-ID: I changed the file to this: #!/usr/bin/env python # -*- coding: utf-8 -*- """Task 07: declaring a dictionary, creating a function, return a funky total """ DATA = {2: 7493945, 76: 4654320, 3: 4091979, 90: 1824881, 82: 714422, 45: 1137701, 10: 374362, 0: 326226, -15: 417203, -56: 333525, 67: 323451, 99: 321696, 21: 336753, -100: 361237, 55: 1209714, 5150: 1771800, 42: 4714011, 888: 14817667, 3500: 13760234, 712: 10903322, 7: 10443792, 842: 11716264, 18584: 10559923, 666: 9275602, 70: 11901200, 153: 12074784, 8: 4337229} def iter_dict_funky_sum(data=DATA): """function that takes one dictionary argument declaring a running total variable, extracting key/value pairs from DATA simultaneously in a for loop, assigning and appending the product of the value minus the key to the running total variable and returning the total.""" funky = 0 for key, value in data.iteritems(): funky += value - key return funky however now pylint is returning: task_07.py:36: [W0102(dangerous-default-value), iter_dict_funky_sum] Dangerous default value DATA (__builtin__.dict) as argument how can I pass the dictionary into the function, since pylint considers the wway I'm doing it to be wrong? the assignment specifications are: #. Create a file named ``task_07.py`` #. Declare a variable named ``DATA`` as a dictionary object. Assign it a set of key/value pairs. This is example data for you to work with but you may create any dictionary of data provided it is at least 10 items long and both keys and values are integers. #. Create a function named ``iter_dict_funky_sum()`` that takes one dictionary argument. #. Declare a running total integer variable. #. Extract the key/value pairs from ``DATA`` simultaneously in a loop. Do this with just one ``for`` loop and no additional forms of looping. #. Assign and append the product of the value minus the key to the running total variable. #. Return the funky total. I'm sure I'm doing everything else right, I guess pylint just doesn't like how I'm declaring the variable? Everything is returning perfectly regarding the example data and it's returning amount. On Fri, Apr 1, 2016 at 12:00 PM, wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > https://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Week 10 warmup assignment (Daniella Sapozhnikova) > 2. Re: Week 10 warmup assignment (Alan Gauld) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Thu, 31 Mar 2016 23:26:38 -0400 > From: Daniella Sapozhnikova > To: tutor at python.org > Subject: [Tutor] Week 10 warmup assignment > Message-ID: > jAC0b_d9ejPA at mail.gmail.com> > Content-Type: text/plain; charset=UTF-8 > > Umm I'm new to this whole tutoring list and I'm having a little bit of > trouble in school with my programming classes (hopefully it's not too late > to pass my class) but anyway, here's the code I've written: > > > #!/usr/bin/env python > # -*- coding: utf-8 -*- > """Task 07: declaring a dictionary, creating a function, > return a funky total """ > > > DATA = {2: 7493945, > 76: 4654320, > 3: 4091979, > 90: 1824881, > 82: 714422, > 45: 1137701, > 10: 374362, > 0: 326226, > -15: 417203, > -56: 333525, > 67: 323451, > 99: 321696, > 21: 336753, > -100: 361237, > 55: 1209714, > 5150: 1771800, > 42: 4714011, > 888: 14817667, > 3500: 13760234, > 712: 10903322, > 7: 10443792, > 842: 11716264, > 18584: 10559923, > 666: 9275602, > 70: 11901200, > 153: 12074784, > 8: 4337229} > > > def iter_dict_funky_sum(**DATA): > """function that takes one dictionary argument declaring > a running total variable, extracting key/value pairs from > DATA simultaneously in a for loop, assigning and appending > the product of the value minus the key to the running total > variable and returning the total.""" > funky = 0 > for key, value in DATA.iteritems(): > funky += value - key > return funky > > > Now, everything it's returning is correct, the only problems I'm having is > the 2 errors pylint is throwing me, which are: > task_07.py:36: [W0621(redefined-outer-name), iter_dict_funky_sum] > Redefining name 'DATA' from outer scope (line 7) > task_07.py:36: [C0103(invalid-name), iter_dict_funky_sum] Invalid argument > name "DATA" > > What does it mean and how can I fix it? > > > ------------------------------ > > Message: 2 > Date: Fri, 1 Apr 2016 09:17:25 +0100 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] Week 10 warmup assignment > Message-ID: > Content-Type: text/plain; charset=utf-8 > > On 01/04/16 04:26, Daniella Sapozhnikova wrote: > > Umm I'm new to this whole tutoring list and I'm having a little bit of > > trouble in school with my programming classes (hopefully it's not too > late > > to pass my class) but anyway, here's the code I've written: > > > > > > #!/usr/bin/env python > > # -*- coding: utf-8 -*- > > """Task 07: declaring a dictionary, creating a function, > > return a funky total """ > > > > > > DATA = {2: 7493945, > > 76: 4654320, > > 3: 4091979, > > 90: 1824881, > > 82: 714422, > > 45: 1137701, > > 10: 374362, > > 0: 326226, > > -15: 417203, > > -56: 333525, > > 67: 323451, > > 99: 321696, > > 21: 336753, > > -100: 361237, > > 55: 1209714, > > 5150: 1771800, > > 42: 4714011, > > 888: 14817667, > > 3500: 13760234, > > 712: 10903322, > > 7: 10443792, > > 842: 11716264, > > 18584: 10559923, > > 666: 9275602, > > 70: 11901200, > > 153: 12074784, > > 8: 4337229} > > > > > > def iter_dict_funky_sum(**DATA): > > """function that takes one dictionary argument declaring > > a running total variable, extracting key/value pairs from > > DATA simultaneously in a for loop, assigning and appending > > the product of the value minus the key to the running total > > variable and returning the total.""" > > funky = 0 > > for key, value in DATA.iteritems(): > > funky += value - key > > return funky > > > > > > Now, everything it's returning is correct, the only problems I'm having > is > > the 2 errors pylint is throwing me, which are: > > task_07.py:36: [W0621(redefined-outer-name), iter_dict_funky_sum] > > Redefining name 'DATA' from outer scope (line 7) > > task_07.py:36: [C0103(invalid-name), iter_dict_funky_sum] Invalid > argument > > name "DATA" > > > > What does it mean and how can I fix it? > > > It means you have the same name for your parameter as for your global > variable which is potentially confusing, so change the name of your > parameter. > > Also you don't need the ** in front of DATA in the function definition. > > Finally, you say it's working but you don't actually call your > function in your code. How are you exercising it? Did you just miss that > bit out or are you importing at the >>> prompt? > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > https://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 146, Issue 1 > ************************************* > From daniellasapo at gmail.com Fri Apr 1 22:19:49 2016 From: daniellasapo at gmail.com (Daniella Sapozhnikova) Date: Fri, 1 Apr 2016 22:19:49 -0400 Subject: [Tutor] week 10 warm up assignment Message-ID: I tried changing the file earlier, however it wasn't returning the apropriate value, so the file looks the same as earlier: #!/usr/bin/env python # -*- coding: utf-8 -*- """Task 07: declaring a dictionary, creating a function, return a funky total """ DATA = {2: 7493945, 76: 4654320, 3: 4091979, 90: 1824881, 82: 714422, 45: 1137701, 10: 374362, 0: 326226, -15: 417203, -56: 333525, 67: 323451, 99: 321696, 21: 336753, -100: 361237, 55: 1209714, 5150: 1771800, 42: 4714011, 888: 14817667, 3500: 13760234, 712: 10903322, 7: 10443792, 842: 11716264, 18584: 10559923, 666: 9275602, 70: 11901200, 153: 12074784, 8: 4337229} def iter_dict_funky_sum(DATA): """function that takes one dictionary argument declaring a running total variable, extracting key/value pairs from DATA simultaneously in a for loop, assigning and appending the product of the value minus the key to the running total variable and returning the total.""" funky = 0 for key, value in DATA.iteritems(): funky += value - key return funky the assignment specifications include: #. Create a file named ``task_07.py`` #. Declare a variable named ``DATA`` as a dictionary object. Assign it a set of key/value pairs. This is example data for you to work with but you may create any dictionary of data provided it is at least 10 items long and both keys and values are integers. #. Create a function named ``iter_dict_funky_sum()`` that takes one dictionary argument. #. Declare a running total integer variable. #. Extract the key/value pairs from ``DATA`` simultaneously in a loop. Do this with just one ``for`` loop and no additional forms of looping. #. Assign and append the product of the value minus the key to the running total variable. #. Return the funky total. and pylint is throwing these errors: task_07.py:36: [W0621(redefined-outer-name), iter_dict_funky_sum] Redefining name 'DATA' from outer scope (line 7) task_07.py:36: [C0103(invalid-name), iter_dict_funky_sum] Invalid argument name "DATA" my question is: how would i go about passing the dictionary into the function without pylint throwing errors? Basically how would I pass a dictionary to a function (am I doing it right???) Thank you, Daniella Sapozhnikova From daniellasapo at gmail.com Sat Apr 2 03:22:37 2016 From: daniellasapo at gmail.com (Daniella Sapozhnikova) Date: Sat, 2 Apr 2016 03:22:37 -0400 Subject: [Tutor] week 10 synthesizing assignment Message-ID: I have a couple of questions. 1) If I wanted to combine two dictionaries into one, how would I go about doing so? (the .update method?) 2) How can I make that combined dictionary have inner dictionaries with the inner values from the previous separate dictionaries? Please point me in the right direction. Thank you From ben+python at benfinney.id.au Sat Apr 2 04:06:45 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 02 Apr 2016 19:06:45 +1100 Subject: [Tutor] week 10 synthesizing assignment References: Message-ID: <85pou88mei.fsf@benfinney.id.au> Daniella Sapozhnikova writes: > 1) If I wanted to combine two dictionaries into one, how would I go > about doing so? How to do it depends on what policy you want to adopt for duplicate keys: * Existing item stays? * New item overrides existing item? * Something else happens? > (the .update method?) The ?dict.update? method is good, yes. It requires that you be explicit about which items you are updating in the existing dictionary. > 2) How can I make that combined dictionary have inner dictionaries > with the inner values from the previous separate dictionaries? That will be easier to talk about if you give some sample inputs and the expected output from the operation. -- \ ?I find the whole business of religion profoundly interesting. | `\ But it does mystify me that otherwise intelligent people take | _o__) it seriously.? ?Douglas Adams | Ben Finney From alan.gauld at btinternet.com Sat Apr 2 04:08:04 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 2 Apr 2016 09:08:04 +0100 Subject: [Tutor] Alan G Week 10 warmup assignment help In-Reply-To: References: Message-ID: On 02/04/16 02:21, Daniella Sapozhnikova wrote: > I changed the file to this: > DATA = {2: 7493945, > 76: 4654320, ... > 153: 12074784, > 8: 4337229} > > def iter_dict_funky_sum(data=DATA): > funky = 0 > for key, value in data.iteritems(): > funky += value - key > return funky > > > however now pylint is returning: > task_07.py:36: [W0102(dangerous-default-value), iter_dict_funky_sum] > Dangerous default value DATA (__builtin__.dict) as argument > > how can I pass the dictionary into the function, since pylint considers the > wway I'm doing it to be wrong? > I would drop the default value for the parameter. ( I suspect that Python doesn't like DATA as a default value because it means you cant use the function anywhere DATA is not defined. But I'm not sure about that) Just use: def iter_dict_funky_sum(data): ... Then when you call the function pass in DATA as its argument: iter_dict_funky_sum(DATA): -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Sat Apr 2 04:15:42 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 2 Apr 2016 09:15:42 +0100 Subject: [Tutor] week 10 synthesizing assignment In-Reply-To: References: Message-ID: On 02/04/16 08:22, Daniella Sapozhnikova wrote: > I have a couple of questions. > 1) If I wanted to combine two dictionaries into one, how would I go about > doing so? (the .update method?) I'm not sure what you mean by that. There are at kleat 2 ways to interpret it. Do you want to merge the data from both into a single dictionary? Or do you want a dictionary with two elements, each of which is itself a dictionary? Both are possible but its not clear which you mean. > 2) How can I make that combined dictionary have inner dictionaries with the > inner values from the previous separate dictionaries? This sounds like the second of the two options I asked about above but again I'm not sure. What do you mean by the "inner values of the previous separate dictionaries"? The simple explanation is: >>> dict1 = {1:'a', 2:'e'} >>> dict2 = {1:'a', 2:'b'} >>> firstTwo = { vowels:dict1, alphabet:dict2} Now I can do print firstTwo['vowels'] print firstTwo['alphabet'] or if firstTwo['vowels'][0] == firstTwo['alphabet'][0]: print 'the first vowel is also the first letter' HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From sjeik_appie at hotmail.com Sat Apr 2 05:59:33 2016 From: sjeik_appie at hotmail.com (Albert-Jan Roskam) Date: Sat, 2 Apr 2016 09:59:33 +0000 Subject: [Tutor] Alan G Week 10 warmup assignment help In-Reply-To: References: , Message-ID: > To: tutor at python.org > From: alan.gauld at btinternet.com > Date: Sat, 2 Apr 2016 09:08:04 +0100 > Subject: Re: [Tutor] Alan G Week 10 warmup assignment help > > On 02/04/16 02:21, Daniella Sapozhnikova wrote: > > I changed the file to this: > > > DATA = {2: 7493945, > > 76: 4654320, > ... > > 153: 12074784, > > 8: 4337229} > > > > def iter_dict_funky_sum(data=DATA): > > funky = 0 > > for key, value in data.iteritems(): > > funky += value - key > > return funky > > > > > > however now pylint is returning: > > task_07.py:36: [W0102(dangerous-default-value), iter_dict_funky_sum] > > Dangerous default value DATA (__builtin__.dict) as argument > > > > how can I pass the dictionary into the function, since pylint considers the > > wway I'm doing it to be wrong? > > > > I would drop the default value for the parameter. > ( I suspect that Python doesn't like DATA as a default value > because it means you cant use the function anywhere DATA is > not defined. But I'm not sure about that) I thought this warning was about the use of mutable default arguments and its counterintuitive behavior: https://pythonconquerstheuniverse.wordpress.com/2012/02/15/mutable-default-arguments/ From dyoo at hashcollision.org Sat Apr 2 07:38:44 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Sat, 2 Apr 2016 04:38:44 -0700 Subject: [Tutor] Fw: About the Round Function In-Reply-To: <85twjk95it.fsf@benfinney.id.au> References: <85twjk95it.fsf@benfinney.id.au> Message-ID: On Fri, Apr 1, 2016 at 6:13 PM, Ben Finney wrote: > Nacir Bouali writes: > >> My students and I are interested in knowing the rationale behind >> Python's choice of the Banker's rounding algorithm to be the default >> rounding algorithm in the third release of Python. > > Can you provide a link to the Python documentation for this? Hi Ben, Rounding behavior is one of the things that changed in Python 3.0. See the "Builtins" section in: https://docs.python.org/3/whatsnew/3.0.html#builtins As far as I can tell, discussion of the possibility of changing this started around Python 2.6 time: https://mail.python.org/pipermail/python-dev/2008-January/075798.html with the reasoning behind the switch because it has nicer statistical properties. The following messages on that thread are especially interesting: https://mail.python.org/pipermail/python-dev/2008-January/075863.html https://mail.python.org/pipermail/python-dev/2008-January/075866.html https://mail.python.org/pipermail/python-dev/2008-January/075873.html From alan.gauld at btinternet.com Sat Apr 2 19:10:54 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 3 Apr 2016 00:10:54 +0100 Subject: [Tutor] Alan G Week 10 warmup assignment help In-Reply-To: References: Message-ID: On 02/04/16 10:59, Albert-Jan Roskam wrote: >>> however now pylint is returning: >>> task_07.py:36: [W0102(dangerous-default-value), iter_dict_funky_sum] >>> Dangerous default value DATA (__builtin__.dict) as argument >> I would drop the default value for the parameter. >> ( I suspect that Python doesn't like DATA as a default value >> because it means you cant use the function anywhere DATA is >> not defined. But I'm not sure about that) > > I thought this warning was about the use of mutable default arguments Possibly so, I don't really know why the warning is there. The "fix" is the same, remove the default value it's not really helping here. (if you really wanted it you could use None: def foo(data = None): if not data: data = DATA # use global ... ) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From eenoch at ncsu.edu Sat Apr 2 17:46:22 2016 From: eenoch at ncsu.edu (Eric Enoch) Date: Sat, 2 Apr 2016 14:46:22 -0700 Subject: [Tutor] Python OOP question Message-ID: This is my first non-MATLAB programming language so I am having some trouble with object-oriented programming. Specifically, I am working on a program that simulates a blackjack game. It was functioning but I have tried adding some new functionality in allowing players to make bets To surmise, BJ Player is an object that was a collection of card objects. Def_init used to just have self and names as parameters, but I added startingmonies (starting money that the player is wagering.) The superclass of BJ player is ultimately BJ hand. I am now getting an error when calling a method to add a card to that hand. Below is where the error o class BJ_Game(object): """ A Blackjack Game. """ def *init*(self, names, startingmonies): self.players = [] for name in names: player = BJ_Player(name) spot = names.index(name) startingscratch = startingmonies[spot] player_with_money = (name, startingscratch,0) self.players.append(player_with_money) This is where the error originates (cards module that is imported into the BJ module used above): class Hand(object): """ A hand of playing cards. """ def *init*(self): self.cards = [] def __str__(self): if self.cards: rep = "" for card in self.cards: rep += str(card) + "\t" else: rep = "" return rep def clear(self): self.cards = [] def add(self, card): self.cards.append(card) def give(self, card, other_hand): self.cards.remove(card) other_hand.add(card) This is the error that I get.: line 47, in give other_hand.add(card) AttributeError: 'tuple' object has no attribute 'add' I get this error when trying to deal cards. Everything else worked before so the only real change that I made is adding the bet parameter. I researched this issue and was not able to gain a strong understanding. Any assistance would be greatly appreciated. Thank you! From ben+python at benfinney.id.au Sat Apr 2 20:37:34 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 03 Apr 2016 10:37:34 +1000 Subject: [Tutor] Python OOP question References: Message-ID: <85fuv38r3l.fsf@benfinney.id.au> Eric Enoch writes: > This is my first non-MATLAB programming language so I am having some > trouble with object-oriented programming. Welcome! Thanks for learning Python. > Specifically, I am working on a program that simulates a blackjack > game. It was functioning but I have tried adding some new > functionality in allowing players to make bets Please set your mail client to send ?plain text? messages only. Special formatting, so-called ?rich? text, or anything beyond plain text means you risk losing the literal layout of your program code in the message. -- \ Moriarty: ?Forty thousand million billion dollars? That money | `\ must be worth a fortune!? ?The Goon Show, _The Sale of | _o__) Manhattan_ | Ben Finney From alan.gauld at btinternet.com Sat Apr 2 20:45:48 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 3 Apr 2016 01:45:48 +0100 Subject: [Tutor] Python OOP question In-Reply-To: References: Message-ID: On 02/04/16 22:46, Eric Enoch wrote: > of BJ player is ultimately BJ hand. I am now getting an error when calling > a method to add a card to that hand. Below is where the error o Unfortunately you don't show us the actual code where you call that method, nor do you show us the actual error (in full). As a result its hard to guess what's going on. Please post the actual code where you call the method and the full error traceback. > class BJ_Game(object): """ A Blackjack Game. """ def *init*(self, names, > startingmonies): > self.players = [] for name in names: player = BJ_Player(name) spot = > names.index(name) startingscratch = startingmonies[spot] player_with_money > = (name, startingscratch,0) self.players.append(player_with_money) We also seem to have lost the formatting, probably due to not posting in plain text. HTML/RTF mail tends to get spacing messed up, please always use plain text when posting code. > def give(self, card, other_hand): > self.cards.remove(card) > other_hand.add(card) > > This is the error that I get.: line 47, in give other_hand.add(card) > AttributeError: 'tuple' object has no attribute 'add' This suggests you are passing a tuple into the method when you call it. But without either the full traceback or the calling code we can only guess. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From abhijeet560 at yahoo.in Sun Apr 3 13:31:32 2016 From: abhijeet560 at yahoo.in (abhijeet560 at yahoo.in) Date: Sun, 3 Apr 2016 17:31:32 +0000 (UTC) Subject: [Tutor] regarding some basic element References: <1370265761.1478265.1459704692378.JavaMail.yahoo.ref@mail.yahoo.com> Message-ID: <1370265761.1478265.1459704692378.JavaMail.yahoo@mail.yahoo.com> want the zero trailed form this :check the code please: num=int(raw_input()) fact=0for x in xrange(1, num+1): fact= fact*x str(fact)l= len(fact)for x in reversed(xrange(l)): if x==0: c+=1print c having issue in this code ..? From zemmoura.khalil at gmail.com Sun Apr 3 17:10:20 2016 From: zemmoura.khalil at gmail.com (khalil zakaria Zemmoura) Date: Sun, 3 Apr 2016 22:10:20 +0100 Subject: [Tutor] Python OOP question In-Reply-To: References: Message-ID: Hi, Other_hand seems to be a tuple object which is immutable (unchangeable) so you can't alter it. By the way, what other_hand is supposed to be? A variable that you declared as tuple? An instance of a class? As other people said to you, we can only guess because we don't see where "other_hand" is declared. Regards From alan.gauld at btinternet.com Sun Apr 3 18:32:50 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 3 Apr 2016 23:32:50 +0100 Subject: [Tutor] regarding some basic element In-Reply-To: <1370265761.1478265.1459704692378.JavaMail.yahoo@mail.yahoo.com> References: <1370265761.1478265.1459704692378.JavaMail.yahoo.ref@mail.yahoo.com> <1370265761.1478265.1459704692378.JavaMail.yahoo@mail.yahoo.com> Message-ID: On 03/04/16 18:31, Abhijeet via Tutor wrote: > want the zero trailed form this :check the code please: > num=int(raw_input()) > fact=0for x in xrange(1, num+1): fact= fact*x str(fact)l= len(fact)for x in reversed(xrange(l)): if x==0: c+=1print c > having issue in this code ..? Unfortunately you haven't posted in plain text so the formatting is all messed up. Can you repost in plain text please? Also can you explain what you mean by "the zero trailed form"? Can you show us what kind of output you expect? Its probably just a string formatting issue but until we see what you mean we can't be specific. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From ashleyyjacobsss at gmail.com Sun Apr 3 23:17:55 2016 From: ashleyyjacobsss at gmail.com (Ashley Jacobs) Date: Sun, 3 Apr 2016 23:17:55 -0400 Subject: [Tutor] Drawing simple graphics objects Message-ID: Hi, could you help me with python 3.5 coding for graphics? From breamoreboy at yahoo.co.uk Mon Apr 4 09:54:10 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 4 Apr 2016 14:54:10 +0100 Subject: [Tutor] Drawing simple graphics objects In-Reply-To: References: Message-ID: On 04/04/2016 04:17, Ashley Jacobs wrote: > Hi, > could you help me with python 3.5 coding for graphics? > Yes, if you provide some code that we can comment on. We do not write code for you. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From alan.gauld at btinternet.com Mon Apr 4 10:09:39 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 4 Apr 2016 15:09:39 +0100 Subject: [Tutor] Drawing simple graphics objects In-Reply-To: References: Message-ID: On 04/04/16 04:17, Ashley Jacobs wrote: > Hi, > could you help me with python 3.5 coding for graphics? Probably, but you'll need to give us a clearer idea of what you want to do. For example you could use the turtle module to draw basic turtle graphics. Or you could use a plotting library to draw graphs etc Or you could use a GUI to do basic geometric figures (line, square, circle etc) Or to display graphic images, like photos or icons. Or you could use PyGame to draw game style sprites (and much more) And beyond that there are a bunch of more advanced 3D graphics toolkits and scientific plotting tools that you could use. It just depends on what you want to do. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Mon Apr 4 11:51:03 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 5 Apr 2016 01:51:03 +1000 Subject: [Tutor] Drawing simple graphics objects In-Reply-To: References: Message-ID: <20160404155100.GF12526@ando.pearwood.info> On Sun, Apr 03, 2016 at 11:17:55PM -0400, Ashley Jacobs wrote: > Hi, > could you help me with python 3.5 coding for graphics? You can start with the turtle graphics: https://docs.python.org/3/library/turtle.html Here is a simple example. Copy and paste this code into Python and run it, and you will see the turtle draw some lines and circles: import turtle turtle.color("blue") turtle.forward(20) turtle.left(30) turtle.forward(20) turtle.penup() turtle.forward(20) turtle.pendown() turtle.forward(80) turtle.color("red") turtle.circle(35) turtle.color("black") turtle.circle(-20) -- Steve From diliupg at gmail.com Wed Apr 6 11:14:45 2016 From: diliupg at gmail.com (DiliupG) Date: Wed, 6 Apr 2016 20:44:45 +0530 Subject: [Tutor] Drawing simple graphics objects In-Reply-To: References: Message-ID: If you really want learn graphics programming with Python then learning Pygame is the best way to go.All these other things are pretty much simple stuff. The easiest way is to start learning by setting yourself objectives and trying to fulfill them. Given below is one of the BEST sources to learn Pygame. http://thepythongamebook.com/en:pygame:start This is another excellent course http://programarcadegames.com/index.php?chapter=example_code&lang=en here are video tutorial. Professor Craven is fantastic. https://www.youtube.com/user/professorcraven Last but not the least have a look at Peter Collinridges site. He will teach you great stuff. http://www.petercollingridge.co.uk/ On Mon, Apr 4, 2016 at 8:47 AM, Ashley Jacobs wrote: > Hi, > could you help me with python 3.5 coding for graphics? > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ********************************************************************************************** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ********************************************************************************************** From dimitarxivanov at gmail.com Thu Apr 7 13:49:03 2016 From: dimitarxivanov at gmail.com (Dimitar Ivanov) Date: Thu, 7 Apr 2016 20:49:03 +0300 Subject: [Tutor] Declaring variables Message-ID: Hello everyone, I have a (hopefully) quick and easy to explain question. I'm currently using MySQLdb module to retrieve some information from a database. In my case, the result that's being yield back is a single line. As far as my understanding goes, MySQLdb function called 'fetchone()' returns the result as a tuple. Problem is, the tuple has some unnecessary characters, such as an additional comma being returned. In my case: >>> idquery = 'select id from table;' >>> cur = mysql.cursor() >>> cur.execute(idquery) >>> id = cur.fetchone() >>> print id ('idinhere',) I stumbled across an example given like this: >>> (id,) = cur.fetchone() So I decided to give it a try and the result is exactly what I need: >>> (id,) = cur.fetchone() >>> print id idinhere My question is - can I reliably use this method? Is it always going to return the string between the brackets as long as I define the variable with '(,)'? I'm planning to use another query that will be using the result from this one and then update another database with this result but I must be sure that the variable will always be the string in and between the brackets otherwise I'm risking to mess up a lot of things big time. A backup plan I had was to use the following: >>> id = cur.fetchone() >>> for x in id: >>> id = x But if the method above is certain to always return only the value I need, I find it to be a far more elegant solution. Also, just to clarify things for myself - what does this method of declaring variables do exactly? I'm sorry if this isn't the right place the ask and if this has been documented clearly already, I'm not sure what to use as a search term in order to find an answer. Thanks a lot in advance! I hope I posted all the details needed and my question is easy to comprehend. Regards, Dimitar From ben+python at benfinney.id.au Thu Apr 7 18:33:38 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 08 Apr 2016 08:33:38 +1000 Subject: [Tutor] Declaring variables References: Message-ID: <85shyx59rx.fsf@benfinney.id.au> Dimitar Ivanov writes: > I have a (hopefully) quick and easy to explain question. I'm currently > using MySQLdb module to retrieve some information from a database. In > my case, the result that's being yield back is a single line. Just a note: The term is a ?record? or ?tuple?. It may be presented by some tools as a line of text, but that's not what it represents. > As far as my understanding goes, MySQLdb function called 'fetchone()' > returns the result as a tuple. That depends on how you asked for it. The MySQLdb API provides a ?DictCursor? class that will return each record as a Python ?dict?, with field names as the keys. > Problem is, the tuple has some unnecessary characters, such as an > additional comma being returned. In my case: > > >>> idquery = 'select id from table;' > >>> cur = mysql.cursor() > >>> cur.execute(idquery) > >>> id = cur.fetchone() > >>> print id > ('idinhere',) Again, you are confused between the value and its textual representation. A tuple is a collection of values, not a string of text. But when representing that to you, Python needs to show it as text. In this case, it represents the value as you might type it in Python syntax. The text, though, is not the value. You are also confused about what is returned. The row is always returned as a collection of fields. In that case, it is a Python ?tuple? (but you can also arrange for it to be a Python ?dict?, as mentioned above). This is true whether the record contains one field, no fields, or seventeen fields. It is always returned as a collection of fields. So to get an individual field from that record, you need to extract the desired item from the collection. record = cur.fetchone() id = record[0] > Thanks a lot in advance! I hope I posted all the details needed and my > question is easy to comprehend. Your question was well written and you provided good information. I hope this helps. -- \ ?Apologize, v. To lay the foundation for a future offense.? | `\ ?Ambrose Bierce, _The Devil's Dictionary_, 1906 | _o__) | Ben Finney From alan.gauld at btinternet.com Thu Apr 7 19:17:23 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 8 Apr 2016 00:17:23 +0100 Subject: [Tutor] Declaring variables In-Reply-To: References: Message-ID: On 07/04/16 18:49, Dimitar Ivanov wrote: > As far as my understanding goes, MySQLdb function called 'fetchone()' > returns the result as a tuple. Problem is, the tuple has some unnecessary > characters, such as an additional comma being returned. In my case: The comma is what makes it a tuple, its not an extra character. It's like the quotes around a string, they are what defines it to be a string. The tuple is defined by having its members separated by commas (not as some think by having parens around them!). So how do you represent a tuple of one element? By adding a trailing comma, which is what you are seeing. x,y = (1,2) the two expressions, on each side of the equals are both tuples. One with parens, one without. But they are both tuples. The parens are really only needed to avoid ambiguity. >>>> idquery = 'select id from table;' >>>> cur = mysql.cursor() >>>> cur.execute(idquery) >>>> id = cur.fetchone() >>>> print id > ('idinhere',) > > So I decided to give it a try and the result is exactly what I need: > >>>> (id,) = cur.fetchone() >>>> print id > idinhere Yes, or you could just have printed id[0] - the first(only) element of the tuple. >>> t = (3,) >>> type(t) >>> print (t) (3,) >>> print(t[0]) 3 >>> > My question is - can I reliably use this method? Is it always going to > return the string between the brackets It will always return a tuple containing as many element as you request. In this case one. > with '(,)'? I'm planning to use another query that will be using the result > from this one and then update another database with this result but I must > be sure that the variable will always be the string in and between the > brackets otherwise I'm risking to mess up a lot of things big time. Provided you extract the values from the tuple they will be of whatever type the database returns. In this case its a string but it could be an integer or float too. Just extract them from the tuple using indexing as you would do for any other tuple. > A backup plan I had was to use the following: > >>>> id = cur.fetchone() >>>> for x in id: >>>> id = x Again that will work, but the simplest option is just to use indexing id = id[0] in your case. Or just use id[0] directly wherever you need the value. > Also, just to clarify things for myself - what does this method of > declaring variables do exactly? x,y = 3,4 Is known as tuple unpacking and is equivalent to x = 3 y = 4 or expressing it slightly differently tup = (3,4) x,y = tup is equivalent to x = tup[0] y = tup[1] it assigns the elements of the tuple on the right to the elements of the tuple on the left. So in your case you are just doing the same thing but with single valued tuples x, = t # where t = (3,) in this case equivalent to saying x = t[0] > I'm sorry if this isn't the right place the > ask and if this has been documented clearly already, I'm not sure what to > use as a search term in order to find an answer. It's exactly the right place to ask and it has been documented, the trick is to know to search for tuple unpacking! :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From chaoticslacker at gmail.com Thu Apr 7 20:51:29 2016 From: chaoticslacker at gmail.com (Jason Willis) Date: Thu, 7 Apr 2016 20:51:29 -0400 Subject: [Tutor] customizing dark_harvest problems Message-ID: Hi , I am a complete noob when it comes to python and programming in general. Though, I do know some things and can figure a little bit out when looking at source code I'm usually at a loss when understanding the entire workings of a program. Any and all help provided here would be greatly appreciated and will further my journey into learning how to code in python. Which will be the first language I learn. Recently I found a program that does a marvelous job at what I'm trying to do. That program is called grey_harvest. It harvests proxies from one website and spits them out by country and other arguments. What i understand from the code so far is that the website being queried is http://freeproxylists.com . This information is put into a variable. Also, the proxies are being read from the "elite.html" web page that is on this website. This information is also put into a variable. What i would like to do is change the second variable , "elite.html" , to "standard.html" and have the program work exactly the same way. Even though, from my understanding, the both web pages are structured identically the program does not work when I change the variable. What am I missing here? I haven't the slightest idea. Hopefully someone here is willing to help me along. Thanks! The code is , I think, short and sweet. It is as follows: """ ''' File: grey_harvest.py ''' Author: s0lst1c3 ''' Created: Tue May 26 2015 ''' Source: https://github.com/s0lst1c3/grey_harvest ''' License: MIT (see attached) ''' Description: Scrapes the web for reliable http or https proxies and prints ''' them to stdout. Can also be used as a python library to ''' easily generate reliable proxies for use within Python ''' application (see README.md). """ __version__ = '0.1.1' __author__ = 'John "s0lst1c3" Ryan' __license__ = 'MIT' __copyright__ = 'Copyright (c) 2015 John Ryan' import requests import socket import sys import argparse from time import sleep from bs4 import BeautifulSoup from lxml import etree ''' configs ''' DOC_ROOT = 'http://freeproxylists.com' ELITE_PAGE = 'elite.html' HTTPS_ONLY = True ALLOWED_COUNTRIES = None DENIED_COUNTRIES = ['China'] MAX_TIMEOUT = 1 TEST_SLEEPTIME = 1 TEST_DOMAIN = 'example.com' class Proxy(dict): def __init__(self, ip, port, country=None, latency=None, https=False, last_checked=None): dict.__init__(self) self.ip = ip self.port = int(port) self.country = country self.latency = int(latency) self.https = https self['ip'] = ip self['port'] = port self['country'] = country self['latency'] = latency self['https'] = https def test(self, test_domain=TEST_DOMAIN, test_sleeptime=TEST_SLEEPTIME, max_timeout=MAX_TIMEOUT): ''' get ready for test ''' protocol = 'https' if self['https'] else 'http' test_url = '%s://%s' % (protocol, test_domain) proxies = { 'https://%s' : str(self), 'http://%s' : str(self), } ''' make a brief HEAD request to test_domain and see if it times out ''' requests.head(test_url, timeout=max_timeout, proxies=proxies) try: response = requests.head(test_url, timeout=max_timeout, proxies=proxies) if test_sleeptime > 0: sleep(test_sleeptime) return True except requests.exceptions.ConnectionError: if test_sleeptime > 0: sleep(test_sleeptime) return False def __str__(self): return '%s:%s' % (self.ip, self.port) class GreyHarvester(object): def __init__(self, test_domain=TEST_DOMAIN, test_sleeptime=TEST_SLEEPTIME, https_only=HTTPS_ONLY, allowed_countries=ALLOWED_COUNTRIES, denied_countries=DENIED_COUNTRIES, max_timeout=MAX_TIMEOUT): self.allowed_countries = allowed_countries self.denied_countries = denied_countries self.max_timeout = max_timeout self.test_sleeptime = test_sleeptime self.test_domain = test_domain self.https_only = https_only def run(self): for endpoint in self._extract_ajax_endpoints(): for proxy in self._extract_proxies(endpoint): if self._passes_filter(proxy) and proxy.test( test_domain=self.test_domain, test_sleeptime=self.test_sleeptime, max_timeout = self.max_timeout, ) == True: yield proxy def _extract_proxies(self, ajax_endpoint): ''' request the xml object ''' proxy_xml = requests.get(ajax_endpoint) root = etree.XML(str(proxy_xml.text)) quote = root.xpath('quote')[0] ''' extract the raw text from the body of the quote tag ''' raw_text = quote.text ''' eliminate the stuff we don't need ''' proxy_data = raw_text.split('You will definitely love it! Give it a try!')[1] ''' get rid of the at the end of proxy_data ''' proxy_data = proxy_data[:-len('')] ''' split proxy_data into rows ''' table_rows = proxy_data.split('') ''' convert each row into a Proxy object ''' for row in table_rows: ''' get rid of the at the end of each row ''' row = row[:-len('')] ''' split each row into a list of items ''' items = row.split('') ''' sometimes we get weird lists containing only an empty string ''' if len(items) != 7: continue ''' we'll use this to remove the from the end of each item ''' tdlen = len('') ''' create proxy dict ''' proxy = Proxy( ip=items[1][:-tdlen], port=int(items[2][:-tdlen]), https=bool(items[3][:-tdlen]), latency=int(items[4][:-tdlen]), last_checked=items[5][:-tdlen], country=items[6][:-tdlen], ) yield proxy def _passes_filter(self, proxy): ''' avoid redudant and space consuming calls to 'self' ''' ''' validate proxy based on provided filters ''' if self.allowed_countries is not None and proxy['country'] not in self.allowed_countries: return False if self.denied_countries is not None and proxy['country'] in self.denied_countries: return False if self.https_only and proxy['https'] == False: return False return True def _extract_ajax_endpoints(self): ''' make a GET request to freeproxylists.com/elite.html ''' url = '/'.join([DOC_ROOT, ELITE_PAGE]) response = requests.get(url) ''' extract the raw HTML doc from the response ''' raw_html = response.text ''' convert raw html into BeautifulSoup object ''' soup = BeautifulSoup(raw_html) for url in soup.select('table tr td table tr td a'): if 'elite #' in url.text: yield '%s/load_elite_d%s' % (DOC_ROOT, url['href'].lstrip('elite/')) def setup(parser): parser.add_argument('-a', '--allowed-countries', dest='allowed_countries', nargs='*', metavar='', required=False, default=ALLOWED_COUNTRIES, help='''Only use proxies physically located in the specified countries.''' ) parser.add_argument('-d', '--denied-countries', dest='denied_countries', nargs='*', metavar='', default=DENIED_COUNTRIES, required=False, help='Do not use proxies physically located these countries. This flag takes precedence over --allowed-countries.''' ) parser.add_argument('-t', '--max-timeout', dest='max_timeout', nargs=1, type=int, metavar='', default=MAX_TIMEOUT, required=False, help='Discard proxies that do not respond within seconds of HEAD request.' ) parser.add_argument('-H', '--https-only', action='store_true', dest='https_only', default=HTTPS_ONLY, help='Only keep proxies with https support.', ) parser.add_argument('-D', '--test-domain', dest='test_domain', nargs=1, metavar='', default=TEST_DOMAIN, required=False, help='Test proxies by making HEAD request to ', ) parser.add_argument('-n', '--num-proxies', dest='num_proxies', nargs=1, type=int, metavar='', required=True, help='Harvest working and free proxies from teh interwebz', ) args = parser.parse_args() return { 'num_proxies' : args.num_proxies[0], 'test_domain' : args.test_domain, 'https_only' : args.https_only, 'max_timeout' : args.max_timeout, 'allowed_countries' : args.allowed_countries, 'denied_countries' : args.denied_countries, } def main(): ''' set things up ''' configs = setup(argparse.ArgumentParser()) harvester = GreyHarvester( test_domain=configs['test_domain'], test_sleeptime=TEST_SLEEPTIME, https_only=configs['https_only'], allowed_countries=configs['allowed_countries'], denied_countries=configs['denied_countries'], max_timeout=configs['max_timeout'] ) ''' harvest free and working proxies from teh interwebz ''' count = 0 for proxy in harvester.run(): if count >= configs['num_proxies']: break print proxy count += 1 if __name__ == '__main__': main() What i understand from the code so far is that the website being queried is http://freeproxylists.com . This information is put into a variable. Also, the proxies are being read from the "elite.html" web page that is on this website. This information is also put into a variable. What i would like to do is change the second variable , "elite.html" , to "standard.html" and have the program work exactly the same way. Even though, from my understanding, the both web pages are structured identically the program does not work when I change the variable. What am I missing here? I haven't the slightest idea. Hopefully someone here is willing to help me along. Thanks! From breamoreboy at yahoo.co.uk Thu Apr 7 17:51:05 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 7 Apr 2016 22:51:05 +0100 Subject: [Tutor] Declaring variables In-Reply-To: References: Message-ID: On 07/04/2016 18:49, Dimitar Ivanov wrote: > Hello everyone, > > I have a (hopefully) quick and easy to explain question. I'm currently > using MySQLdb module to retrieve some information from a database. In my > case, the result that's being yield back is a single line. > > As far as my understanding goes, MySQLdb function called 'fetchone()' > returns the result as a tuple. Problem is, the tuple has some unnecessary > characters, such as an additional comma being returned. In my case: > >>>> idquery = 'select id from table;' >>>> cur = mysql.cursor() >>>> cur.execute(idquery) >>>> id = cur.fetchone() Note that using 'id' is frowned upon as you're overriding the builtin of the same name. I'll use id_ below. >>>> print id > ('idinhere',) No, it isn't an additional comma, it's a tuple that only has one field. > > I stumbled across an example given like this: > >>>> (id,) = cur.fetchone() > > So I decided to give it a try and the result is exactly what I need: > >>>> (id,) = cur.fetchone() >>>> print id > idinhere > > My question is - can I reliably use this method? Is it always going to > return the string between the brackets as long as I define the variable > with '(,)'? I'm planning to use another query that will be using the result > from this one and then update another database with this result but I must > be sure that the variable will always be the string in and between the > brackets otherwise I'm risking to mess up a lot of things big time. I'd write it as:- id_ = cur.fetchone()[0] > > A backup plan I had was to use the following: > >>>> id = cur.fetchone() >>>> for x in id: >>>> id = x Yuck :) > > But if the method above is certain to always return only the value I need, > I find it to be a far more elegant solution. > > Also, just to clarify things for myself - what does this method of > declaring variables do exactly? I'm sorry if this isn't the right place the > ask and if this has been documented clearly already, I'm not sure what to > use as a search term in order to find an answer. In Python nothing is declared as in C or Java. A name is bound to an object. So from the above the name 'id_' is bound to the string object that happens to be 'idinhere'. Once this has been done there is nothing to stop you from writing:- id_ = 1 id_ = 1.0 id_ = Point(1, 2) id_ = Complicated(lots, of, parameters, here) > > Thanks a lot in advance! I hope I posted all the details needed and my > question is easy to comprehend. The only things that are sometimes needed are your OS and Python version. The latter can be deduced from your 'print id' rather than 'print(id)', indicating that it is 2.x, not 3.y. > > Regards, > Dimitar > -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From alan.gauld at btinternet.com Thu Apr 7 21:10:55 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 8 Apr 2016 02:10:55 +0100 Subject: [Tutor] customizing dark_harvest problems In-Reply-To: References: Message-ID: On 08/04/16 01:51, Jason Willis wrote: > Though, I do know some things and can figure a little bit out when looking > at source code I'm usually at a loss when understanding the entire workings > of a program. And thats the problem here. The code is very specific to the page it is parsing. Simply substituting a different file will never work. For example... > DOC_ROOT = 'http://freeproxylists.com' > ELITE_PAGE = 'elite.html' > def _extract_ajax_endpoints(self): > > ''' make a GET request to freeproxylists.com/elite.html ''' > url = '/'.join([DOC_ROOT, ELITE_PAGE]) > response = requests.get(url) > > ''' extract the raw HTML doc from the response ''' > raw_html = response.text > > ''' convert raw html into BeautifulSoup object ''' > soup = BeautifulSoup(raw_html) > > for url in soup.select('table tr td table tr td a'): > if 'elite #' in url.text: > yield '%s/load_elite_d%s' % (DOC_ROOT, > url['href'].lstrip('elite/')) Notice that last 'if' section has 'elite #' hard coded in. But the standard page doesn't use 'elite #'... There are probably a lot more similar content-dependant things in the code, I just happened to spot that one. It would be better if you took the time(only a few hours really) to learn how to program in Python so that you can actually understand the code rather than making "poke 'n hope" changes. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From ben+python at benfinney.id.au Thu Apr 7 21:15:07 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 08 Apr 2016 11:15:07 +1000 Subject: [Tutor] customizing dark_harvest problems References: Message-ID: <85oa9k6gv8.fsf@benfinney.id.au> Jason Willis writes: > I am a complete noob when it comes to python and programming in > general. Welcome! Congratulations on choosing to learn Python. > What i understand from the code so far Please set your mail client to send plain text messages, and to not automatically wrap lines of text when you paste in examples of program code. Only then can we see the exact same program code you see. > Even though, from my understanding, the both web pages are structured > identically the program does not work when I change the variable. What > am I missing here? I haven't the slightest idea. Nor do we. When reporting confusing behaviour, you need to say not only that ?the program does not work?; you need to say in quite close detail what it *does*. -- \ ?It is forbidden to steal hotel towels. Please if you are not | `\ person to do such is please not to read notice.? ?hotel, | _o__) Kowloon, Hong Kong | Ben Finney From chaoticslacker at gmail.com Fri Apr 8 12:44:06 2016 From: chaoticslacker at gmail.com (Jason Willis) Date: Fri, 8 Apr 2016 12:44:06 -0400 Subject: [Tutor] Tutor Digest, Vol 146, Issue 9 In-Reply-To: References: Message-ID: My apologies for the word wrap. It seemed to look ok in my web client (gmail). Thank you for the pointer to other instances in the program where there are hard-coded content dependant entries. I solved this by changing all instances of the word "elite" and changing them to "standard" and the program works! I agree with you that taking a few hours to learn python would go a long way. I believe by doing things like this that this is exactly what I am doing. I don't know if it's the materials I'm using or what but learning from a book is not helping me much. Maybe you all have better ideas about sources that would be helpful in moving me along into learning python. Thanks again! On Fri, Apr 8, 2016 at 12:00 PM, wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > https://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: Declaring variables (Mark Lawrence) > 2. Re: customizing dark_harvest problems (Alan Gauld) > 3. Re: customizing dark_harvest problems (Ben Finney) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Thu, 7 Apr 2016 22:51:05 +0100 > From: Mark Lawrence > To: tutor at python.org > Subject: Re: [Tutor] Declaring variables > Message-ID: > Content-Type: text/plain; charset=windows-1252; format=flowed > > On 07/04/2016 18:49, Dimitar Ivanov wrote: > > Hello everyone, > > > > I have a (hopefully) quick and easy to explain question. I'm currently > > using MySQLdb module to retrieve some information from a database. In my > > case, the result that's being yield back is a single line. > > > > As far as my understanding goes, MySQLdb function called 'fetchone()' > > returns the result as a tuple. Problem is, the tuple has some unnecessary > > characters, such as an additional comma being returned. In my case: > > > >>>> idquery = 'select id from table;' > >>>> cur = mysql.cursor() > >>>> cur.execute(idquery) > >>>> id = cur.fetchone() > > Note that using 'id' is frowned upon as you're overriding the builtin of > the same name. I'll use id_ below. > > >>>> print id > > ('idinhere',) > > No, it isn't an additional comma, it's a tuple that only has one field. > > > > > I stumbled across an example given like this: > > > >>>> (id,) = cur.fetchone() > > > > So I decided to give it a try and the result is exactly what I need: > > > >>>> (id,) = cur.fetchone() > >>>> print id > > idinhere > > > > My question is - can I reliably use this method? Is it always going to > > return the string between the brackets as long as I define the variable > > with '(,)'? I'm planning to use another query that will be using the > result > > from this one and then update another database with this result but I > must > > be sure that the variable will always be the string in and between the > > brackets otherwise I'm risking to mess up a lot of things big time. > > I'd write it as:- > > id_ = cur.fetchone()[0] > > > > > A backup plan I had was to use the following: > > > >>>> id = cur.fetchone() > >>>> for x in id: > >>>> id = x > > Yuck :) > > > > > But if the method above is certain to always return only the value I > need, > > I find it to be a far more elegant solution. > > > > Also, just to clarify things for myself - what does this method of > > declaring variables do exactly? I'm sorry if this isn't the right place > the > > ask and if this has been documented clearly already, I'm not sure what to > > use as a search term in order to find an answer. > > In Python nothing is declared as in C or Java. A name is bound to an > object. So from the above the name 'id_' is bound to the string object > that happens to be 'idinhere'. Once this has been done there is nothing > to stop you from writing:- > > id_ = 1 > id_ = 1.0 > id_ = Point(1, 2) > id_ = Complicated(lots, of, parameters, here) > > > > > Thanks a lot in advance! I hope I posted all the details needed and my > > question is easy to comprehend. > > The only things that are sometimes needed are your OS and Python > version. The latter can be deduced from your 'print id' rather than > 'print(id)', indicating that it is 2.x, not 3.y. > > > > > Regards, > > Dimitar > > > > > -- > My fellow Pythonistas, ask not what our language can do for you, ask > what you can do for our language. > > Mark Lawrence > > > > ------------------------------ > > Message: 2 > Date: Fri, 8 Apr 2016 02:10:55 +0100 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] customizing dark_harvest problems > Message-ID: > Content-Type: text/plain; charset=utf-8 > > On 08/04/16 01:51, Jason Willis wrote: > > > Though, I do know some things and can figure a little bit out when > looking > > at source code I'm usually at a loss when understanding the entire > workings > > of a program. > > And thats the problem here. The code is very specific to the page it is > parsing. Simply substituting a different file will never work. > > For example... > > > DOC_ROOT = 'http://freeproxylists.com' > > ELITE_PAGE = 'elite.html' > > > > def _extract_ajax_endpoints(self): > > > > ''' make a GET request to freeproxylists.com/elite.html ''' > > url = '/'.join([DOC_ROOT, ELITE_PAGE]) > > response = requests.get(url) > > > > ''' extract the raw HTML doc from the response ''' > > raw_html = response.text > > > > ''' convert raw html into BeautifulSoup object ''' > > soup = BeautifulSoup(raw_html) > > > > for url in soup.select('table tr td table tr td a'): > > if 'elite #' in url.text: > > yield '%s/load_elite_d%s' % (DOC_ROOT, > > url['href'].lstrip('elite/')) > > > Notice that last 'if' section has 'elite #' hard coded in. > But the standard page doesn't use 'elite #'... > > There are probably a lot more similar content-dependant things > in the code, I just happened to spot that one. > > It would be better if you took the time(only a few hours really) to > learn how to program in Python so that you can actually understand > the code rather than making "poke 'n hope" changes. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > > > ------------------------------ > > Message: 3 > Date: Fri, 08 Apr 2016 11:15:07 +1000 > From: Ben Finney > To: tutor at python.org > Subject: Re: [Tutor] customizing dark_harvest problems > Message-ID: <85oa9k6gv8.fsf at benfinney.id.au> > Content-Type: text/plain; charset=utf-8 > > Jason Willis writes: > > > I am a complete noob when it comes to python and programming in > > general. > > Welcome! Congratulations on choosing to learn Python. > > > What i understand from the code so far > > Please set your mail client to send plain text messages, and to not > automatically wrap lines of text when you paste in examples of program > code. > > Only then can we see the exact same program code you see. > > > Even though, from my understanding, the both web pages are structured > > identically the program does not work when I change the variable. What > > am I missing here? I haven't the slightest idea. > > Nor do we. When reporting confusing behaviour, you need to say not only > that ?the program does not work?; you need to say in quite close detail > what it *does*. > > -- > \ ?It is forbidden to steal hotel towels. Please if you are not | > `\ person to do such is please not to read notice.? ?hotel, | > _o__) Kowloon, Hong Kong | > Ben Finney > > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > https://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 146, Issue 9 > ************************************* > From alan.gauld at btinternet.com Fri Apr 8 14:39:22 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 8 Apr 2016 19:39:22 +0100 Subject: [Tutor] Tutor Digest, Vol 146, Issue 9 In-Reply-To: References: Message-ID: On 08/04/16 17:44, Jason Willis wrote: > there are hard-coded content dependant entries. I solved this by changing > all instances of the word "elite" and changing them to "standard" and the > program works! Glad you got it working. > I agree with you that taking a few hours to learn python > would go a long way. I believe by doing things like this that this is > exactly what I am doing. I don't know that you are. You are reading and playing with other people's code. But you don't know if what you are reading is good or bad code. For example the code you just posted is not that great it (unnecessarily) mixes two different techniques for processing the text and has several awkward stylistic things going on. Also do you know what classes are for and when/how they should be used? In the code example you sent there are two classes and two functions, but why? And is that a good idea? Just because something gives you the answer you expect today does not mean it will tomorrow if it is not properly designed. How do you know when the code you modify is well designed unless you know what it all does? How will you fix it if/when it breaks? > I don't know if it's the materials I'm using or > what but learning from a book is not helping me much. There are many online tutorials (see below for mine) but there are also videos galore on Youtube/Vimeo etc. I personally like the ShowMeDo series: http://showmedo.com/videos/python And there are interactive code schools online too that many find more inspiring than reading books. Here's one you might try: http://www.learnpython.org/ But there are several others. Don't get me wrong, reading and playing code is an important part of learning to code. But even more important is creating your own code from scratch. Only then are you forced to confront what each and every line does and thus be sure you understand it. And the great thing about Python is you can get up to a useful standard with literally a few (<10?) hours of reading/practising. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From tomjmaher4 at gmail.com Fri Apr 8 16:48:21 2016 From: tomjmaher4 at gmail.com (Tom Maher) Date: Fri, 8 Apr 2016 15:48:21 -0500 Subject: [Tutor] Understanding error in recursive function Message-ID: Hi, As a test I am trying to write a function that returns the sum of values attached to one key in a dictionary. I am wondering why the code that I wrote is returning: "maximum recursion depth exceeded " Here is the code: animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']} x = animals['a'] def howMany(aDict): count = 0 for value in howMany(aDict): count += 1 return count howMany(x) Just wondering why I would be getting that error. Thanks From dyoo at hashcollision.org Fri Apr 8 19:28:24 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 8 Apr 2016 16:28:24 -0700 Subject: [Tutor] Understanding error in recursive function In-Reply-To: References: Message-ID: On Fri, Apr 8, 2016 at 1:48 PM, Tom Maher wrote: > Hi, > > As a test I am trying to write a function that returns the sum of values > attached to one key in a dictionary. Why does the program try to use recursion for this problem? From martin at linux-ip.net Fri Apr 8 19:34:03 2016 From: martin at linux-ip.net (Martin A. Brown) Date: Fri, 8 Apr 2016 16:34:03 -0700 Subject: [Tutor] Understanding error in recursive function In-Reply-To: References: Message-ID: Greetings Tom, >As a test I am trying to write a function that returns the sum of >values Given the code you pasted, I think you mean 'count' of values, right? I'll assume that below, because it is a tricky thing to sum some strings. >attached to one key in a dictionary. I am wondering why the >code that I wrote is returning: >"maximum recursion depth exceeded " >Here is the code: Recursion is a great tool, and quite powerful. (Though you may not need it for this problem.) >animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']} > >x = animals['a'] > >def howMany(aDict): > count = 0 > for value in howMany(aDict): > count += 1 > return count > >howMany(x) >Just wondering why I would be getting that error. I will show you how I would change the howMany function so that it prints (to STDERR) its argument(s). This is always a useful diagnostic or debugging feature. Even after many years, I still grab frequently for printing variable contents or logging them. N.B. I'm going to assume you are using Python3. import sys def howMany(aDict): print('%r' % (aDict,), file=sys.stderr) count = 0 for value in howMany(aDict): count += 1 return count This will print out a whole bunch of ['aardvark'], once each time the howMany function is called. Now, Im going to separate my reply into one part about recursion and another part about what I think you are trying to do. First, it looks like you want to see how many animals have names which start with a specific letter. You start by creating a dictionary that uses an initial letter as the key and a list to hold the names of the animals. Your function could probably be as simple as: def howMany(aList): return len(aList) Note that the object passed into the howMany function is not a dict, so I changed the variable name to aList. Since I know that you are trying to learn recursion, then, we could try to use a recursion solution to your question, rather than use len(aList). It is important to recognize that the next step is not efficient use of CPU nor memory, but it should help you play with recursion. So, now, I'll mention a thing or two about recursion and then I'll return to your problem about counting the number of animals in each list, where there's a dictionary key for the initial letter of the name we give to each type of animal. One of the most important parts of recursion is defining the termination condition for the recursion. When does the recursion stop? When did we reach the end of the list? One other important piece of successful recursion is to make sure when you are about to call the function again, that you have changed something about the variable you are giving to the function. Your problem, in essence is that you were calling the function like this: def func(x): func(x) There is no difference between what the function accepts and what the function calls. This, essentially is an infinite loop. And, Python dutifully runs this until it runs out of stack space. In Python this sort of error is called an Exception, and it looks like this: RuntimeError: maximum recursion depth exceeded If you look back at your code, you'll also see that Python never gets to the line where you set count += 1. So, to review, here's what a recursive function would need to do in order to count the items of the list: * have a beginning count of 0 * return the count as soon as it receives an empty list * strip off one item of the list AND * add one to the count, for each time it calls itself Here is an inefficient function that demonstrates these principles of recursion: def howMany(l, count=0): if not l: # -- termination condition, empty list! return count return howMany(l[1:], count+1) The problems with this list include that it will fail if the lists are long. For example, I was able to determine that on my box, I can only handle 988 calls to the same function before triggering the maxmimum recursion depth exceeded error. Given that your question was recursion, I chose to focus on that, but I would recommend using the simplest tool for the job, and in this case that would be the builtin function called 'len'. But, this is a great place to ask the question you asked. Best of luck and I hope you are enjoying Python, -Martin -- Martin A. Brown http://linux-ip.net/ From alan.gauld at btinternet.com Fri Apr 8 19:38:20 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 9 Apr 2016 00:38:20 +0100 Subject: [Tutor] Understanding error in recursive function In-Reply-To: References: Message-ID: On 08/04/16 21:48, Tom Maher wrote: > As a test I am trying to write a function that returns the sum of values > attached to one key in a dictionary. I am wondering why the code that I > wrote is returning: > "maximum recursion depth exceeded " Python has a limit to how many times you can recursively call a function. (Last time I looked it was about 1000) You have hit it. The problem is you have broken one of the primary rules of recursion, you are not checking for the terminating condition before recursively calling the function. As soon as you enter the function you call it again - forever... or until Python hits its limits. > def howMany(aDict): > count = 0 > for value in howMany(aDict): Effectively your code never gets further than this. You need to think about what will stop the recursion and how to test for that before calling the next level. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Fri Apr 8 20:55:26 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 9 Apr 2016 01:55:26 +0100 Subject: [Tutor] Understanding error in recursive function In-Reply-To: References: Message-ID: On 09/04/16 00:34, Martin A. Brown wrote: > You start by creating a dictionary that uses an initial letter as > the key and a list to hold the names of the animals. Your function > could probably be as simple as: > > def howMany(aList): > return len(aList) > > Here is an inefficient function that demonstrates these principles > of recursion: > > def howMany(l, count=0): > if not l: # -- termination condition, empty list! > return count > return howMany(l[1:], count+1) > > Given that your question was recursion, I chose to focus on that, > but I would recommend using the simplest tool for the job, and in > this case that would be the builtin function called 'len'. Just to round off Martin's discussion we should probably consider the non recursive option without using len(). It's still pretty simple: def howMany(aList): count = 0 for item in aList: count += 1 return count or a slightly sneaky but faster version: def howMany(aList): return aList.index(aList[-1]) + 1 But the len() function does what you want so in practice just use that. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From breamoreboy at yahoo.co.uk Fri Apr 8 19:12:30 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 9 Apr 2016 00:12:30 +0100 Subject: [Tutor] Understanding error in recursive function In-Reply-To: References: Message-ID: On 08/04/2016 21:48, Tom Maher wrote: > Hi, > > As a test I am trying to write a function that returns the sum of values > attached to one key in a dictionary. I am wondering why the code that I > wrote is returning: > "maximum recursion depth exceeded" > Here is the code: > > animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']} > x = animals['a'] > def howMany(aDict): > count = 0 > for value in howMany(aDict): > count += 1 > return count > > howMany(x) > > Just wondering why I would be getting that error. > > Thanks howMany calls howMany which calls howMany... -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From oliver at bestwalter.de Fri Apr 8 19:08:23 2016 From: oliver at bestwalter.de (Oliver Bestwalter) Date: Fri, 08 Apr 2016 23:08:23 +0000 Subject: [Tutor] Understanding error in recursive function In-Reply-To: References: Message-ID: Hi Tom, You can see what happens for yourself in the Pythontutor: http://goo.gl/YVkh03 - step through the code by clicking on "Forward" and see what happens. You are calling the howMany function from inside the function itself, which is called recursion. This can be practical, but in your case it isn't. In other langauges, the function would call itself until you run out of memory, but in Python there is an (adjustable) limit to the number of recursion that can be executed, before the error occurs that you describe. One simple rewrite of your function that counts alle elements of all lists in the dictionary (I am not sur if that's what you want, but I guess you can figure out what you need from the example) is this: http://goo.gl/frZfkc animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']} x = animals['a'] def how_many(aDict): count = 0 for value in animals.values(): count += len(value) return count print(how_many(x)) (hope the pasted code is not mangled ...) cheers Oliver On Sat, 9 Apr 2016 at 00:52 Tom Maher wrote: > Hi, > > As a test I am trying to write a function that returns the sum of values > attached to one key in a dictionary. I am wondering why the code that I > wrote is returning: > "maximum recursion depth exceeded " > Here is the code: > > animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']} > > x = animals['a'] > > def howMany(aDict): > > count = 0 > > for value in howMany(aDict): > > count += 1 > > return count > > howMany(x) > > > Just wondering why I would be getting that error. > > > Thanks > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From zemmoura.khalil at gmail.com Fri Apr 8 19:23:28 2016 From: zemmoura.khalil at gmail.com (khalil zakaria Zemmoura) Date: Sat, 9 Apr 2016 00:23:28 +0100 Subject: [Tutor] Tutor Digest, Vol 146, Issue 9 Message-ID: Hi, there is one place i think you have to have a look at it and it's the python official site. One thing i love about python is the so well written documentation, i remember when i was learning ruby and had to go to the official doc! it was hard to understand for the beginner how i was. so, here is the link https://docs.python.org/3/tutorial/index.html Good luck Regards From zemmoura.khalil at gmail.com Fri Apr 8 19:54:39 2016 From: zemmoura.khalil at gmail.com (khalil zakaria Zemmoura) Date: Sat, 9 Apr 2016 00:54:39 +0100 Subject: [Tutor] Understanding error in recursive function Message-ID: Hi, I think your function runs forever because the only thing it done is calling it self when entering the for loop when you call your function in the for loop it jump to the definition (def howMany(aDict)) then initialise count and bond the value 0 to it then enter a for loop then call the function 'howMany' again and so on! before the for loop there is nothing happening to the function you defined or the argument is not modified in the recursive call, so i don't understand why you used a recursion there! i think you have to replace the howMany(aDict) in the for loop by aDict it self and it will be ok. for value in aDict: ... Regards From __peter__ at web.de Sun Apr 10 14:36:43 2016 From: __peter__ at web.de (Peter Otten) Date: Sun, 10 Apr 2016 20:36:43 +0200 Subject: [Tutor] Understanding error in recursive function References: Message-ID: Alan Gauld wrote: > or a slightly sneaky but faster version: > > def howMany(aList): > return aList.index(aList[-1]) + 1 Sorry, but this isn't "slightly sneaky", this is outright wrong. I fails for both empty lists and lists with duplicate entries. From sjeik_appie at hotmail.com Thu Apr 14 15:38:31 2016 From: sjeik_appie at hotmail.com (Albert-Jan Roskam) Date: Thu, 14 Apr 2016 19:38:31 +0000 Subject: [Tutor] question about __copy__ and __deepcopy__ Message-ID: Hi, Lately I have been using the "mutable namedtuple"? shown below a lot. I found it somewhere on StackOverflow or ActiveState or something. In its original form, it only had an __init__ method. I noticed that copying Record objects sometimes failed. So I implemented __copy__ and __deepcopy__, Is this the correct way to do this? In my original use case, even shallow copies failed, but I can't reproduce that anymore (or maybe I am imagining things!). Is __copy__ really needed here? Does __deepcopy__ make any sense at all? My tests pass, but still I am not sure! Thanks! Albert-Jan from copy import copy, deepcopy class Record(dict): ??? def __init__(self, *args, **kwargs): ??????? super(Record, self).__init__(*args, **kwargs) ??????? self.__dict__ = self ??? def __str__(self): ??????? items = ["%r: %r" % (k, v) for k, v in sorted(self.__dict__.items())] ??????? return "{" + ", ".join(items) + "}" ??? def __copy__(self): ??????? return Record(**self.__dict__.copy()) ??? def __deepcopy__(self, memo): ??????? address = id(self) ??????? try: ??????????? return memo[address] ??????? except KeyError: ??????????? memo[address] = {k: copy(v) for k, v in self.items()} ??????????? return deepcopy(self, memo) if __name__ == "__main__": ??? ??? # only shallow needed??????? ??? record = Record(x=1, y=2, z=3) ??? cp = copy(record) ??? assert record == cp and not record is cp ??? record = Record(x=1, y=2, z=3) ??? dc = deepcopy(record) ??? assert record == dc and not record is dc ??? ??? # mutable value: deepcopy needed ??? L = range(10) ??? record = Record(x=1, y=2, z=L) ??? cp = copy(record) ??? print record, cp ??? assert record == cp and not record is cp ??? dc = deepcopy(record) ??? assert record == dc and not record is dc ??? L.insert(0, 42) ??? expect = {'y': 2, 'x': 1, 'z': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]} ??? assert dc == expect and not record is dc ??? print record, dc ??????? From oscar.j.benjamin at gmail.com Thu Apr 14 16:34:39 2016 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 14 Apr 2016 21:34:39 +0100 Subject: [Tutor] question about __copy__ and __deepcopy__ In-Reply-To: References: Message-ID: On 14 April 2016 at 20:38, Albert-Jan Roskam wrote: > Hi, > > Lately I have been using the "mutable namedtuple" shown below a lot. I found it somewhere on StackOverflow or ActiveState or something. > In its original form, it only had an __init__ method. I don't know about your copy/deepcopy stuff. It looked fine to me but I'm not very experienced in that area. I wonder what this mutable namedtuple is for though. Looking at it: > class Record(dict): > > def __init__(self, *args, **kwargs): > super(Record, self).__init__(*args, **kwargs) > self.__dict__ = self It's not so much a mutable namedtuple as an "attribute dict". It's a dict whose keys can be accessed as attributes - because it is its own instance dict. Of course it also has dict attributes like pop, items etc. (see dir(dict) for a list). The reason that dicts use d[k] rather than d.k for accessing keys is to be able to store arbitrary keys without conflicting with the dict's methods which are attributes. A namedtuple is something very different. It subclasses tuple and the whole idea is that an instance is lightweight (not having an attribute dict) and hashable and imutable etc. A mutable version of that might just look like: class Point(object): # No instance dict: __slots__ = ['x', 'y'] def __init__(self, x, y): self.x = x self.y = y It depends what you really want it for though. -- Oscar From steve at pearwood.info Fri Apr 15 02:30:16 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 15 Apr 2016 16:30:16 +1000 Subject: [Tutor] question about __copy__ and __deepcopy__ In-Reply-To: References: Message-ID: <20160415063015.GJ1819@ando.pearwood.info> On Thu, Apr 14, 2016 at 07:38:31PM +0000, Albert-Jan Roskam wrote: > Hi, > > Lately I have been using the "mutable namedtuple"? shown below a lot. > I found it somewhere on StackOverflow or ActiveState or something. In > its original form, it only had an __init__ method. I noticed that > copying Record objects sometimes failed. Failed how? Given how simple the class looks, I wonder whether that's a bug in copy. Apart from a fancy __str__ method, there's practically nothing to it! So I took your Record class, stripped out the __copy__ and __deepcopy__ methods, created a slightly complex instance, and tried copying it: d = Record(spam=23, ham=42, eggs=[], cheese={}) d.cheese[1] = None d.cheese[2] = ['a', 'b', 'c'] d.eggs.append(100) d.eggs.append(200) d.eggs.append(d) d.eggs.append(d.cheese) from copy import copy, deepcopy copy(d) deepcopy(d) and both appeat to work correctly. So perhaps you ought to look more carefully at the copying failure? -- Steve From sjeik_appie at hotmail.com Fri Apr 15 04:55:20 2016 From: sjeik_appie at hotmail.com (Albert-Jan Roskam) Date: Fri, 15 Apr 2016 08:55:20 +0000 Subject: [Tutor] question about __copy__ and __deepcopy__ In-Reply-To: <20160415063015.GJ1819@ando.pearwood.info> References: , <20160415063015.GJ1819@ando.pearwood.info> Message-ID: > Date: Fri, 15 Apr 2016 16:30:16 +1000 > From: steve at pearwood.info > To: tutor at python.org > Subject: Re: [Tutor] question about __copy__ and __deepcopy__ > > On Thu, Apr 14, 2016 at 07:38:31PM +0000, Albert-Jan Roskam wrote: > > Hi, > > > > Lately I have been using the "mutable namedtuple" shown below a lot. > > I found it somewhere on StackOverflow or ActiveState or something. In > > its original form, it only had an __init__ method. I noticed that > > copying Record objects sometimes failed. > > Failed how? > > Given how simple the class looks, I wonder whether that's a bug in copy. > Apart from a fancy __str__ method, there's practically nothing to it! > > So I took your Record class, stripped out the __copy__ and __deepcopy__ > methods, created a slightly complex instance, and tried copying it: > > d = Record(spam=23, ham=42, eggs=[], cheese={}) > d.cheese[1] = None > d.cheese[2] = ['a', 'b', 'c'] > d.eggs.append(100) > d.eggs.append(200) > d.eggs.append(d) > d.eggs.append(d.cheese) > > from copy import copy, deepcopy > > copy(d) > deepcopy(d) > > > and both appeat to work correctly. So perhaps you ought to look more > carefully at the copying failure? Hi Steven, Heh, it's my fancy __str__ method that confused me. This is what I get when I run my code without __copy__ and __deepcopy__ runfile('/home/albertjan/Downloads/attrdict_tutor.py', wdir='/home/albertjan/Downloads') {'x': 1, 'y': 2, 'z': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]} {'x': 1, 'y': 2, 'z': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]} {'x': 1, 'y': 2, 'z': [42, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]} {} # print statements --> call __str__ dc.__str__() Out[19]: '{}' dc.__repr__() Out[20]: "{'y': 2, 'x': 1, 'z': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]}" Wicked. I do not understand the output of dc.__str__(). Somehow self.__dict__ is empty. If I store a deepcopy of the instance __dict__ in a class attribute "Record.dict_copy", __str__ does not return just the two curly braces. It's wasteful to create a copy, though. from copy import copy, deepcopy class Record(dict): def __init__(self, *args, **kwargs): super(Record, self).__init__(*args, **kwargs) self.__dict__ = self def __str__(self): #items = ["%r: %r" % (k, v) for k, v in sorted(self.__dict__.items())] Record.dict_copy = deepcopy(self) # store it as a class attribute. items = ["%r: %r" % (k, v) for k, v in sorted(Record.dict_copy.items())] return "{" + ", ".join(items) + "}" runfile('/home/albertjan/Downloads/attrdict_tutor.py', wdir='/home/albertjan/Downloads') {'x': 1, 'y': 2, 'z': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]} {'x': 1, 'y': 2, 'z': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]} {'x': 1, 'y': 2, 'z': [42, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]} {'x': 1, 'y': 2, 'z': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]} dc.__str__() Out[28]: "{'x': 1, 'y': 2, 'z': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]}" dc.__repr__() Out[29]: "{'y': 2, 'x': 1, 'z': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]}" From oscar.j.benjamin at gmail.com Fri Apr 15 05:31:53 2016 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Fri, 15 Apr 2016 10:31:53 +0100 Subject: [Tutor] question about __copy__ and __deepcopy__ In-Reply-To: References: <20160415063015.GJ1819@ando.pearwood.info> Message-ID: On 15 April 2016 at 09:55, Albert-Jan Roskam wrote: > > Heh, it's my fancy __str__ method that confused me. This is what I get when I run my code without __copy__ and __deepcopy__ > runfile('/home/albertjan/Downloads/attrdict_tutor.py', wdir='/home/albertjan/Downloads') > {'x': 1, 'y': 2, 'z': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]} {'x': 1, 'y': 2, 'z': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]} > {'x': 1, 'y': 2, 'z': [42, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]} {} # print statements --> call __str__ > > dc.__str__() > Out[19]: '{}' > > dc.__repr__() > Out[20]: "{'y': 2, 'x': 1, 'z': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]}" > > Wicked. I do not understand the output of dc.__str__(). Somehow self.__dict__ is empty. If I store a deepcopy of the instance __dict__ in a class attribute "Record.dict_copy", __str__ does not return just the two curly braces. It's wasteful to create a copy, though. This kind of confusion comes from setting self.__dict__ = self. That's not really a normal thing to do so I wouldn't expect it to necessarily be supported by other things like copy.copy: In [1]: class Record(dict): ...: def __init__(self, *args, **kwargs): ...: super(Record, self).__init__(*args, **kwargs) ...: self.__dict__ = self ...: In [2]: r = Record(x=1, y=2) In [3]: r Out[3]: {'x': 1, 'y': 2} In [4]: r.__dict__ is r # <--- Compare with r2 below Out[4]: True In [5]: import copy In [6]: r2 = copy.copy(r) In [7]: r2 Out[7]: {'x': 1, 'y': 2} In [8]: r2.__dict__ Out[8]: {'x': 1, 'y': 2} In [9]: r2 is r2.__dict__ # <-- self.__dict__ is not self Out[9]: False In [13]: type(r2.__dict__) Out[13]: dict In [14]: type(r.__dict__) Out[14]: __main__.Record In [15]: r2.__dict__ == r.__dict__ # <-- Equal but distinct Out[15]: True -- Oscar From sjeik_appie at hotmail.com Fri Apr 15 05:48:24 2016 From: sjeik_appie at hotmail.com (Albert-Jan Roskam) Date: Fri, 15 Apr 2016 09:48:24 +0000 Subject: [Tutor] question about __copy__ and __deepcopy__ In-Reply-To: References: , Message-ID: > From: oscar.j.benjamin at gmail.com > Date: Thu, 14 Apr 2016 21:34:39 +0100 > Subject: Re: [Tutor] question about __copy__ and __deepcopy__ > To: sjeik_appie at hotmail.com > CC: tutor at python.org > > On 14 April 2016 at 20:38, Albert-Jan Roskam wrote: > > Hi, > > > > Lately I have been using the "mutable namedtuple" shown below a lot. I found it somewhere on StackOverflow or ActiveState or something. > > In its original form, it only had an __init__ method. > > I don't know about your copy/deepcopy stuff. It looked fine to me but > I'm not very experienced in that area. I wonder what this mutable > namedtuple is for though. > > Looking at it: > > > class Record(dict): > > > > def __init__(self, *args, **kwargs): > > super(Record, self).__init__(*args, **kwargs) > > self.__dict__ = self > > It's not so much a mutable namedtuple as an "attribute dict". It's a > dict whose keys can be accessed as attributes - because it is its own > instance dict. Of course it also has dict attributes like pop, items > etc. (see dir(dict) for a list). The reason that dicts use d[k] rather > than d.k for accessing keys is to be able to store arbitrary keys > without conflicting with the dict's methods which are attributes. > > A namedtuple is something very different. It subclasses tuple and the > whole idea is that an instance is lightweight (not having an attribute > dict) and hashable and imutable etc. A mutable version of that might > just look like: > > class Point(object): > # No instance dict: > __slots__ = ['x', 'y'] > > def __init__(self, x, y): > self.x = x > self.y = y > > It depends what you really want it for though. HI Oscar, Ok, I agree that "mutable namedtuple" is a misnomer. I started using a regular namedtuple, and then I wanted something with similar functionality, but with the possibility to update/mutate the fields. The AttrDict was the option I liked. The order of the fields is rarely important in my case. I can easily use the AttrDict with SqlAlchemy, too. What I like about both namedtuple and AttrDict is attribute lookup: that makes code so, so, soooo much easier to read. This seems to be a nice generalization of your code: class Point(object): def __init__(self, **kwargs): Point.__slots__ = kwargs.keys() for k, v in kwargs.items(): setattr(self, k, v) point = Point(x=1, y=2, z=3) print point.x point.x = 42 print point.x I have no experience with __slots__ (but I think I roughly know what it's for). I expected this to fail: point.remark = "booh" point Out[36]: <__main__.Point at 0x7f282de9ccd0> point.remark Out[37]: 'booh' How can it be that __slots__ may be extended once the Point class has been instantiated? (sorry if this post is a bit long --this is just so much fun!) If I add a convenience getter/setter, the setter does indeed only seem to work for attributes that were in __slots__ already (here "z") class Point(object): def __init__(self, **kwargs): Point.__slots__ = kwargs.keys() for k, v in kwargs.items(): setattr(self, k, v) @property def values(self): return {attr: getattr(self, attr) for attr in Point.__slots__} @values.setter def values(self, d): for attr, value in d.items(): print "setting", attr, value setattr(self, attr, value) point = Point(x=1, y=2, z=3) print point.x point.x = 42 print point.x print point.values point.values = dict(a=1, b=2, c=3) print point.values ## no a, b, c here! point.values = dict(a=1, b=2, z=444) print point.values # z is updated, though! Thank you! Albert-Jan From oscar.j.benjamin at gmail.com Fri Apr 15 10:04:37 2016 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Fri, 15 Apr 2016 15:04:37 +0100 Subject: [Tutor] question about __copy__ and __deepcopy__ In-Reply-To: References: Message-ID: On 15 April 2016 at 10:48, Albert-Jan Roskam wrote: > What I like about both namedtuple and AttrDict is attribute lookup: that > makes code so, so, soooo much easier to read. This seems to be a nice > generalization of your code: > > class Point(object): > > def __init__(self, **kwargs): > Point.__slots__ = kwargs.keys() > for k, v in kwargs.items(): > setattr(self, k, v) This is not how __slots__ is supposed to work. __slots__ should be defined in the class statement (outside of any method). The way that __slots__ works is kind of magical so you can't just set the attribute on the class any time you like. I was just imagining that you would define a class with __slots__ listing the attributes instances should have when you want one. That's how namedtuple works: you make a class with particular attributes. You seem to want to generalise that so that each instance has different attributes which is not really the idea. If you just want an object to which you can attach some attributes then I think you want types.SimpleNamespace: https://docs.python.org/3/library/types.html#additional-utility-classes-and-functions That's new in 3.4 but the docs show how to make something similar: class SimpleNamespace: def __init__(self, **kwargs): self.__dict__.update(kwargs) def __repr__(self): keys = sorted(self.__dict__) items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys) return "{}({})".format(type(self).__name__, ", ".join(items)) def __eq__(self, other): return self.__dict__ == other.__dict__ Notice that it just passes the kwargs through to __dict__ rather than subclassing __dict__ and using a self-reference. -- Oscar From diasnevina at yahoo.co.uk Sat Apr 9 05:32:13 2016 From: diasnevina at yahoo.co.uk (Nevina Dias) Date: Sat, 9 Apr 2016 09:32:13 +0000 (UTC) Subject: [Tutor] Code wont run References: <265238644.3244975.1460194333393.JavaMail.yahoo.ref@mail.yahoo.com> Message-ID: <265238644.3244975.1460194333393.JavaMail.yahoo@mail.yahoo.com> import random?import time? print ("Welcome to Pizza Shed!") total_cost = 0 tablenum = input ("Enter table number from 1-25 \n ")tablenum = int(tablenum)while tablenum>25 or tablenum <=0:?? ? tablenum = input ("Enter the correct table number, there are only 25 tables ")?? ??#Pizza menu with prices? print ("---------------------")? print ("Let me help you with your order!")? print ("---------------------")? print ("Menu")? print (?? ? "1 = cheese and tomato: 3.50, "?? ? "2 = ham and pineapple: 4.20, "?? ? "3 = vegetarian: 5.20, "?? ? "4 = meat feast: 5.80, "?? ? "5 = seafood: 5.60 " ) pizza_costs = [3.5,4.2,5.2,5.8,5.6] pizza_choice = input("Enter the type of pizza that you want to order from 1-5 \n")?pizza_choice = int(pizza_choice)while pizza_choice>5 or pizza_choice <=1:?? ? pizza_choice = input ("Enter the right number ")? if pizza_choice == 1:?? ? print "You have chosen cheese and tomato. The cost for this is 3.50"?elif pizza_choice == 2:?? ? print ("You have chosen ham and pineapple. The cost for this is 4.20")?elif pizza_choice == 3:?? ? print ("You have chosen vegetarian. The cost for this is 5.20")?elif pizza_choice == 4:?? ? print ("You have chosen meat feast. The cost for this is 5.80")?elif pizza_choice == 5:?? ? print ("You have chosen sea food. The cost for this is 5.60") #find the cost and then add it to the #totalcost = pizza_costs[pizza_choice - 1]total_cost += cost? ??print ("------------------")? pizza_amount = input ("Enter the amount of Pizzas that you want to order ")?while pizza_amount > 10 or pizza_amount <=0:?? ? pizza_amount = input ("Maximum amount is 10, Please enter again ")? print ("--------------------")? #base? print ("Base")? print (?? ? "1 = thin and crispy,"?? ? "2 = traditional" )? base = input ("Select a base from 1-2 \n")?while base>2 or base<=1:?? ? base = input ("There are only 2 types, Please enter again ")? if base == 1:?? ? print "You have chosen thin and crispy"?elif base == 2:?? ? print ("You have chosen traditional")?? ??print ("-------------------")? #extra toppings? print ("Extra Toppings")? toppings = input ("Enter a number for your choice of extra topping \n Enter 1 for extra cheese \n Enter 2 for extra pepperoni \n Enter 3 for extra pineapple \n Enter 4 for extra peppers \n" )?while toppings >4 or toppings < 0:?? ? toppings = input ("There are only 4 types of extra toppings, Please try again " )? if toppings == 1:?? ? print ("You have chosen extra cheese. The cost for this is 0.50")?elif toppings == 2:?? ? print ("You have chosen pepperoni. The cost for this is 0.50")?elif toppings == 3:?? ? print ("You have chosen pineapple. The cost for this is 0.50")?elif toppings == 4:?? ? print ("You have chosen peppers. The cost for this is 0.50")? print ("-------------------------")? #drink #Here you will need to multiply the #drink cost by you drink amount #before adding it to total_cost print ("Drink")? print (?? ? "1 = Cola: 0.90, "?? ? "2 = Lemonande: 0.80, "?? ? "3 = Fizzy Orange: 0.90 " )? drink_costs = [0.9,0.8,0.9] drink = input ("Enter a number for your choice of drinks " )?while drink>3 or drink<0:?? ? drink = input ("Choices start from 0 to 3 " )drink = int(drink) if drink == 1:?? ? print "You have chosen Cola. The cost for this is 0.90"?elif drink == 2:?? ? print ("You have chosen Lemonande. The cost for this is 0.80")?elif drink == 3:?? ? print ("You have chosen Fizzy Orange. The cost for this is 0.90")? drink_cost = drink_costs[drink-1]?drink_amount = input ("Enter the amount of drinks")drink_amount =int(drink_amount)while drink_amount >10 or drink_amount<0:?? ? drink_amount = input (" You can only have upto 10 drinks, Please try again")?drink_amount = int(drink_amount) drink_cost *= drink_amounttotal_cost += drink_cost print ("--------------------------------")?print ("Calculating bill")?print ("--------------------------------")?print ("--------------------------------")?? ??print ("Thank You for ordering at Pizza Shed! ") print("?", total_cost, sep = "") Hey...I tried running this code, but it doesnt work .. ?Show original messageReply?Reply to All?Forward?MoreNevina Dias?ToAlex KleiderMar 31 at 1:09?PMimport random?import time? print ("Welcome to Pizza Shed!") total_cost = 0 tablenum = input ("Enter table number from 1-25 \n ")tablenum = int(tablenum)while tablenum>25 or tablenum <=0:?? ? tablenum = input ("Enter the correct table number, there are only 25 tables ")?? ??#Pizza menu with prices? print ("---------------------")? print ("Let me help you with your order!")? print ("---------------------")? print ("Menu")? print (?? ? "1 = cheese and tomato: 3.50, "?? ? "2 = ham and pineapple: 4.20, "?? ? "3 = vegetarian: 5.20, "?? ? "4 = meat feast: 5.80, "?? ? "5 = seafood: 5.60 " ) pizza_costs = [3.5,4.2,5.2,5.8,5.6] pizza_choice = input("Enter the type of pizza that you want to order from 1-5 \n")?pizza_choice = int(pizza_choice)while pizza_choice>5 or pizza_choice <=1:?? ? pizza_choice = input ("Enter the right number ")? if pizza_choice == 1:?? ? print "You have chosen cheese and tomato. The cost for this is 3.50"?elif pizza_choice == 2:?? ? print ("You have chosen ham and pineapple. The cost for this is 4.20")?elif pizza_choice == 3:?? ? print ("You have chosen vegetarian. The cost for this is 5.20")?elif pizza_choice == 4:?? ? print ("You have chosen meat feast. The cost for this is 5.80")?elif pizza_choice == 5:?? ? print ("You have chosen sea food. The cost for this is 5.60") #find the cost and then add it to the #totalcost = pizza_costs[pizza_choice - 1]total_cost += cost? ??print ("------------------")? pizza_amount = input ("Enter the amount of Pizzas that you want to order ")?while pizza_amount > 10 or pizza_amount <=0:?? ? pizza_amount = input ("Maximum amount is 10, Please enter again ")? print ("--------------------")? #base? print ("Base")? print (?? ? "1 = thin and crispy,"?? ? "2 = traditional" )? base = input ("Select a base from 1-2 \n")?while base>2 or base<=1:?? ? base = input ("There are only 2 types, Please enter again ")? if base == 1:?? ? print "You have chosen thin and crispy"?elif base == 2:?? ? print ("You have chosen traditional")?? ??print ("-------------------")? #extra toppings? print ("Extra Toppings")? toppings = input ("Enter a number for your choice of extra topping \n Enter 1 for extra cheese \n Enter 2 for extra pepperoni \n Enter 3 for extra pineapple \n Enter 4 for extra peppers \n" )?while toppings >4 or toppings < 0:?? ? toppings = input ("There are only 4 types of extra toppings, Please try again " )? if toppings == 1:?? ? print ("You have chosen extra cheese. The cost for this is 0.50")?elif toppings == 2:?? ? print ("You have chosen pepperoni. The cost for this is 0.50")?elif toppings == 3:?? ? print ("You have chosen pineapple. The cost for this is 0.50")?elif toppings == 4:?? ? print ("You have chosen peppers. The cost for this is 0.50")? print ("-------------------------")? #drink #Here you will need to multiply the #drink cost by you drink amount #before adding it to total_cost print ("Drink")? print (?? ? "1 = Cola: 0.90, "?? ? "2 = Lemonande: 0.80, "?? ? "3 = Fizzy Orange: 0.90 " )? drink_costs = [0.9,0.8,0.9] drink = input ("Enter a number for your choice of drinks " )?while drink>3 or drink<0:?? ? drink = input ("Choices start from 0 to 3 " )drink = int(drink) if drink == 1:?? ? print "You have chosen Cola. The cost for this is 0.90"?elif drink == 2:?? ? print ("You have chosen Lemonande. The cost for this is 0.80")?elif drink == 3:?? ? print ("You have chosen Fizzy Orange. The cost for this is 0.90")? drink_cost = drink_costs[drink-1]?drink_amount = input ("Enter the amount of drinks")drink_amount =int(drink_amount)while drink_amount >10 or drink_amount<0:?? ? drink_amount = input (" You can only have upto 10 drinks, Please try again")?drink_amount = int(drink_amount) drink_cost *= drink_amounttotal_cost += drink_cost print ("--------------------------------")?print ("Calculating bill")?print ("--------------------------------")?print ("--------------------------------")?? ??print ("Thank You for ordering at Pizza Shed! ") print("?", total_cost, sep = "") The code wont run and I was wonder whether, if the code is right in working out the total cost? From e.stockie at outlook.com Wed Apr 13 15:15:49 2016 From: e.stockie at outlook.com (Eben Stockman) Date: Wed, 13 Apr 2016 20:15:49 +0100 Subject: [Tutor] (no subject) Message-ID: Hi this is the code I have so far for the task could you please help because it is really important as it counts towards my Gcse and I need it to be working fully at the minute the files don't seem to print all the words nor the positions col you please help. I have attached my code and the task. I would be very grateful if you could hep me From marcus.luetolf at bluewin.ch Wed Apr 13 15:41:38 2016 From: marcus.luetolf at bluewin.ch (=?utf-8?Q?marcus_l=C3=BCtolf?=) Date: Wed, 13 Apr 2016 21:41:38 +0200 Subject: [Tutor] operations on lists Message-ID: <00f601d195bc\$81feba40\$85fc2ec0\$@bluewin.ch> Hello experts I'am working exercise 5. of 'Practical Programming 2nd edition, .....using Python 3' (operations on lists). The following code get's me wrong results: >>> metals = [['beryllium', 4],['magnesium', 12], ['calcium', 20], ['strontium', 38], ['barium', 56], ['radium', 88]] >>> max(metals) ['strontium', 38] >>> min(metals) ['barium', 56] It should return ['radium', 88] and ['beryllium', 4] respectively What's wrong ? Marcus. --- Diese E-Mail wurde von Avast Antivirus-Software auf Viren gepr?ft. https://www.avast.com/antivirus From oasis.boone at gmail.com Wed Apr 13 20:22:02 2016 From: oasis.boone at gmail.com (Malcolm Boone) Date: Wed, 13 Apr 2016 18:22:02 -0600 Subject: [Tutor] Slack Token Invalid Syntax Message-ID: Hello everyone! This is my first time using the Python Tutor myself, so I apologize in advance if I've done this wrong. Here is what I'm trying to do. I have a script written in Python 3 that will go through my companies Slack account and delete any files older than 30 days. I've ran this script successfully once before (about a month ago) and when I tried to run the script today to delete more files, I'm given this error: File "C:\Users\malco\Anaconda3\Lib\Slack-File-Delete.py", line 6 _token = xoxp-14301025207-14298191955-14452030292-********** SyntaxError: invalid syntax Below I will attach all of the code for this script. I have changed the end of the token to *'s to protect that information. If I've forgotten to include any information please let me know! Code: import requests import json import calendar from datetime import datetime, timedelta _token = xoxp-14301025207-14298191955-14452030292-********** _domain = oasis-vape.slack.com if __name__ == '__main__': while 1: files_list_url = 'https://slack.com/api/files.list' date = str(calendar.timegm((datetime.now() + timedelta(-30)) .utctimetuple())) data = {"token": _token, "ts_to": date} response = requests.post(files_list_url, data = data) if len(response.json()["files"]) == 0: break for f in response.json()["files"]: print "Deleting file " + f["name"] + "..." timestamp = str(calendar.timegm(datetime.now().utctimetuple())) delete_url = "https://" + _domain + ". slack.com/api/files.delete?t=" + timestamp requests.post(delete_url, data = { "token": _token, "file": f["id"], "set_active": "true", "_attempts": "1"}) print "DONE!" ----------------------------------- ----------------------------------- Malcolm Boone *Vice President* *Oasis Vape* *CONFIDENTIALITY NOTICE -- This email is intended only for the person(s) named in the message header. Unless otherwise indicated, it contains information that is confidential, privileged and/or exempt from disclosure under applicable law. If you have received this message in error, please notify the sender of the error and delete the message. Thank you. * From alan.gauld at btinternet.com Sat Apr 16 18:48:37 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 16 Apr 2016 23:48:37 +0100 Subject: [Tutor] Understanding error in recursive function In-Reply-To: References: Message-ID: On 10/04/16 19:36, Peter Otten wrote: > Alan Gauld wrote: > >> or a slightly sneaky but faster version: >> >> def howMany(aList): >> return aList.index(aList[-1]) + 1 > > Sorry, but this isn't "slightly sneaky", this is outright wrong. > I fails for both empty lists and lists with duplicate entries. Oops, quite right. Sorry. Just back from a weeks vacation hence the delayed response... Also why you'll see a bunch of delayed messages from moderation arriving... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Sat Apr 16 18:51:55 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 16 Apr 2016 23:51:55 +0100 Subject: [Tutor] Code wont run In-Reply-To: <265238644.3244975.1460194333393.JavaMail.yahoo@mail.yahoo.com> References: <265238644.3244975.1460194333393.JavaMail.yahoo.ref@mail.yahoo.com> <265238644.3244975.1460194333393.JavaMail.yahoo@mail.yahoo.com> Message-ID: On 09/04/16 10:32, Nevina Dias via Tutor wrote: Sorry for the delay the message was in the moderation queue and I was on holiday. As to your code it has not been posted in plain text so its been scrambled by the email system. We can't begin to decipher it. When you say it "won't run", do you get an error message? If so please repost both the code and the full error message and use plain text in your mail tool. > import random import time > print ("Welcome to Pizza Shed!") > total_cost = 0 > tablenum = input ("Enter table number from 1-25 \n ")tablenum = int(tablenum)while tablenum>25 or tablenum <=0: tablenum = input ("Enter the correct table number, there are only 25 tables ") #Pizza menu with prices > print ("---------------------") > print ("Let me help you with your order!") > print ("---------------------") > print ("Menu") > print ( "1 = cheese and tomato: 3.50, " "2 = ham and pineapple: 4.20, " "3 = vegetarian: 5.20, " "4 = meat feast: 5.80, " "5 = seafood: 5.60 " ) > pizza_costs = [3.5,4.2,5.2,5.8,5.6] > pizza_choice = input("Enter the type of pizza that you want to order from 1-5 \n") pizza_choice = int(pizza_choice)while pizza_choice>5 or pizza_choice <=1: pizza_choice = input ("Enter the right number ") > if pizza_choice == 1: print "You have chosen cheese and tomato. The cost for this is 3.50" elif pizza_choice == 2: print ("You have chosen ham and pineapple. The cost for this is 4.20") elif pizza_choice == 3: print ("You have chosen vegetarian. The cost for this is 5.20") elif pizza_choice == 4: print ("You have chosen meat feast. The cost for this is 5.80") elif pizza_choice == 5: print ("You have chosen sea food. The cost for this is 5.60") > #find the cost and then add it to the #totalcost = pizza_costs[pizza_choice - 1]total_cost += cost print ("------------------") > pizza_amount = input ("Enter the amount of Pizzas that you want to order ") while pizza_amount > 10 or pizza_amount <=0: pizza_amount = input ("Maximum amount is 10, Please enter again ") > print ("--------------------") > #base > print ("Base") > print ( "1 = thin and crispy," "2 = traditional" ) > base = input ("Select a base from 1-2 \n") while base>2 or base<=1: base = input ("There are only 2 types, Please enter again ") > if base == 1: print "You have chosen thin and crispy" elif base == 2: print ("You have chosen traditional") print ("-------------------") > #extra toppings > print ("Extra Toppings") > toppings = input ("Enter a number for your choice of extra topping \n Enter 1 for extra cheese \n Enter 2 for extra pepperoni \n Enter 3 for extra pineapple \n Enter 4 for extra peppers \n" ) while toppings >4 or toppings < 0: toppings = input ("There are only 4 types of extra toppings, Please try again " ) > if toppings == 1: print ("You have chosen extra cheese. The cost for this is 0.50") elif toppings == 2: print ("You have chosen pepperoni. The cost for this is 0.50") elif toppings == 3: print ("You have chosen pineapple. The cost for this is 0.50") elif toppings == 4: print ("You have chosen peppers. The cost for this is 0.50") > print ("-------------------------") > #drink > #Here you will need to multiply the #drink cost by you drink amount #before adding it to total_cost > print ("Drink") > print ( "1 = Cola: 0.90, " "2 = Lemonande: 0.80, " "3 = Fizzy Orange: 0.90 " ) > drink_costs = [0.9,0.8,0.9] > > drink = input ("Enter a number for your choice of drinks " ) while drink>3 or drink<0: drink = input ("Choices start from 0 to 3 " )drink = int(drink) > if drink == 1: print "You have chosen Cola. The cost for this is 0.90" elif drink == 2: print ("You have chosen Lemonande. The cost for this is 0.80") elif drink == 3: print ("You have chosen Fizzy Orange. The cost for this is 0.90") > drink_cost = drink_costs[drink-1] drink_amount = input ("Enter the amount of drinks")drink_amount =int(drink_amount)while drink_amount >10 or drink_amount<0: drink_amount = input (" You can only have upto 10 drinks, Please try again") drink_amount = int(drink_amount) > drink_cost *= drink_amounttotal_cost += drink_cost > print ("--------------------------------") print ("Calculating bill") print ("--------------------------------") print ("--------------------------------") print ("Thank You for ordering at Pizza Shed! ") > print("?", total_cost, sep = "") > Hey...I tried running this code, but it doesnt work .. > > Show original messageReply Reply to All Forward MoreNevina Dias ToAlex KleiderMar 31 at 1:09 PMimport random import time > print ("Welcome to Pizza Shed!") > total_cost = 0 > tablenum = input ("Enter table number from 1-25 \n ")tablenum = int(tablenum)while tablenum>25 or tablenum <=0: tablenum = input ("Enter the correct table number, there are only 25 tables ") #Pizza menu with prices > print ("---------------------") > print ("Let me help you with your order!") > print ("---------------------") > print ("Menu") > print ( "1 = cheese and tomato: 3.50, " "2 = ham and pineapple: 4.20, " "3 = vegetarian: 5.20, " "4 = meat feast: 5.80, " "5 = seafood: 5.60 " ) > pizza_costs = [3.5,4.2,5.2,5.8,5.6] > pizza_choice = input("Enter the type of pizza that you want to order from 1-5 \n") pizza_choice = int(pizza_choice)while pizza_choice>5 or pizza_choice <=1: pizza_choice = input ("Enter the right number ") > if pizza_choice == 1: print "You have chosen cheese and tomato. The cost for this is 3.50" elif pizza_choice == 2: print ("You have chosen ham and pineapple. The cost for this is 4.20") elif pizza_choice == 3: print ("You have chosen vegetarian. The cost for this is 5.20") elif pizza_choice == 4: print ("You have chosen meat feast. The cost for this is 5.80") elif pizza_choice == 5: print ("You have chosen sea food. The cost for this is 5.60") > #find the cost and then add it to the #totalcost = pizza_costs[pizza_choice - 1]total_cost += cost print ("------------------") > pizza_amount = input ("Enter the amount of Pizzas that you want to order ") while pizza_amount > 10 or pizza_amount <=0: pizza_amount = input ("Maximum amount is 10, Please enter again ") > print ("--------------------") > #base > print ("Base") > print ( "1 = thin and crispy," "2 = traditional" ) > base = input ("Select a base from 1-2 \n") while base>2 or base<=1: base = input ("There are only 2 types, Please enter again ") > if base == 1: print "You have chosen thin and crispy" elif base == 2: print ("You have chosen traditional") print ("-------------------") > #extra toppings > print ("Extra Toppings") > toppings = input ("Enter a number for your choice of extra topping \n Enter 1 for extra cheese \n Enter 2 for extra pepperoni \n Enter 3 for extra pineapple \n Enter 4 for extra peppers \n" ) while toppings >4 or toppings < 0: toppings = input ("There are only 4 types of extra toppings, Please try again " ) > if toppings == 1: print ("You have chosen extra cheese. The cost for this is 0.50") elif toppings == 2: print ("You have chosen pepperoni. The cost for this is 0.50") elif toppings == 3: print ("You have chosen pineapple. The cost for this is 0.50") elif toppings == 4: print ("You have chosen peppers. The cost for this is 0.50") > print ("-------------------------") > #drink > #Here you will need to multiply the #drink cost by you drink amount #before adding it to total_cost > print ("Drink") > print ( "1 = Cola: 0.90, " "2 = Lemonande: 0.80, " "3 = Fizzy Orange: 0.90 " ) > drink_costs = [0.9,0.8,0.9] > > drink = input ("Enter a number for your choice of drinks " ) while drink>3 or drink<0: drink = input ("Choices start from 0 to 3 " )drink = int(drink) > if drink == 1: print "You have chosen Cola. The cost for this is 0.90" elif drink == 2: print ("You have chosen Lemonande. The cost for this is 0.80") elif drink == 3: print ("You have chosen Fizzy Orange. The cost for this is 0.90") > drink_cost = drink_costs[drink-1] drink_amount = input ("Enter the amount of drinks")drink_amount =int(drink_amount)while drink_amount >10 or drink_amount<0: drink_amount = input (" You can only have upto 10 drinks, Please try again") drink_amount = int(drink_amount) > drink_cost *= drink_amounttotal_cost += drink_cost > print ("--------------------------------") print ("Calculating bill") print ("--------------------------------") print ("--------------------------------") print ("Thank You for ordering at Pizza Shed! ") > print("?", total_cost, sep = "") > The code wont run and I was wonder whether, if the code is right in working out the total cost? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Sat Apr 16 18:56:31 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 16 Apr 2016 23:56:31 +0100 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: On 13/04/16 20:15, Eben Stockman wrote: > Hi this is the code I have so far for the task Hi Eben. The code has disappeared, probably because you sent it as an attachment. This list is plain text and attachments often get stripped as potential security risks etc. Please repost with the code in the message body. Use plain text to avoid formatting errors. > could you please help because it is really important as it counts > towards my Gcse For non UK readers GCSE is a high school level educational certificate. > ... at the minute the files don't seem to print all the words > nor the positions col you please help. Without any sight of code we can't really do anything. When you repost be sure to include an example of the output you get (including any error messages)and what you expected. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Sat Apr 16 19:02:55 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 17 Apr 2016 00:02:55 +0100 Subject: [Tutor] operations on lists In-Reply-To: <00f601d195bc\$81feba40\$85fc2ec0\$@bluewin.ch> References: <00f601d195bc\$81feba40\$85fc2ec0\$@bluewin.ch> Message-ID: On 13/04/16 20:41, marcus l?tolf wrote: > Hello experts > > I'am working exercise 5. of 'Practical Programming 2nd edition, .....using Python 3' (operations on lists). > The following code get's me wrong results: > >>>> metals = [['beryllium', 4],['magnesium', 12], ['calcium', 20], ['strontium', 38], ['barium', 56], ['radium', 88]] >>>> max(metals) > ['strontium', 38] >>>> min(metals) > ['barium', 56] > > It should return > ['radium', 88] and > ['beryllium', 4] respectively Why should it return radium as the max? It may be obvious to you but looking at it as simple data (which is all Python sees) that's not obvious at all. Why would radium come before strontium? And obviously(!) the first list element takes priority over the second when looking at simple data. (And Python just sees a collection of string/integer pairs, it has no idea what those strings/integers mean) If you want to order by the second element there are several things you can do, the simplest is probably to just swap the elements around in your tuples... But that might not be possible (or easy) depending on how you get the tuples. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Sat Apr 16 19:18:24 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 17 Apr 2016 00:18:24 +0100 Subject: [Tutor] Slack Token Invalid Syntax In-Reply-To: References: Message-ID: On 14/04/16 01:22, Malcolm Boone wrote: > advance if I've done this wrong. Nope, for a first post its pretty good. :-) > this error: > > File "C:\Users\malco\Anaconda3\Lib\Slack-File-Delete.py", line 6 > _token = xoxp-14301025207-14298191955-14452030292-********** > SyntaxError: invalid syntax > Which is quite correct, that's not a valid line of Python. I suspect the right hand side should be a string? > > _token = xoxp-14301025207-14298191955-14452030292-********** > _domain = oasis-vape.slack.com And I'm pretty sure the same is true of the _domain line too? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From dyoo at hashcollision.org Sat Apr 16 19:21:12 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Sat, 16 Apr 2016 16:21:12 -0700 Subject: [Tutor] operations on lists In-Reply-To: <00f601d195bc\$81feba40\$85fc2ec0\$@bluewin.ch> References: <00f601d195bc\$81feba40\$85fc2ec0\$@bluewin.ch> Message-ID: On Wed, Apr 13, 2016 at 12:41 PM, marcus l?tolf wrote: > Hello experts > > I'am working exercise 5. of 'Practical Programming 2nd edition, .....using Python 3' (operations on lists). > The following code get's me wrong results: > >>>> metals = [['beryllium', 4],['magnesium', 12], ['calcium', 20], ['strontium', 38], ['barium', 56], ['radium', 88]] >>>> max(metals) > ['strontium', 38] >>>> min(metals) > ['barium', 56] When comparing list structures, Python uses a lexicographic ordering. http://mathworld.wolfram.com/LexicographicOrder.html > It should return > ['radium', 88] and > ['beryllium', 4] respectively If you want this, you have to tell Python not to use its default lexicographic ordering. See: https://wiki.python.org/moin/HowTo/Sorting. In particular, pay special attention to the section here: https://wiki.python.org/moin/HowTo/Sorting#Key_Functions, because it's very relevant to your question. If you have questions, please feel free to ask! From dyoo at hashcollision.org Sat Apr 16 19:46:22 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Sat, 16 Apr 2016 16:46:22 -0700 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: On Wed, Apr 13, 2016 at 12:15 PM, Eben Stockman wrote: > could you please help because it is really important as it counts towards my Gcse Just to add: please try to avoid saying this detail in the future. It's much more helpful to talk about what you've tried, what parts you understand, and what parts you don't understand. We'd rather you be clear-headed and interested in learning, so that you can learn to solve these problems. For more about this, see: http://www.catb.org/esr/faqs/smart-questions.html#idm45974142363472. Spend more effort in describing the the problem solving strategies you've tried so far. What kinds of problems you've already solved that might be similar to the one you're stuck on? What parts of the program actually do work as you expect? And what parts do not? Do you have any guesses as to what you're confused about? A large part of learning to program has nothing to do with syntax: it has to do with learning strategies for solving problems. Hope that makes sense! From rusek at gybon.cz Sun Apr 17 06:09:31 2016 From: rusek at gybon.cz (=?UTF-8?Q?Ond=C5=99ej?= Rusek) Date: Sun, 17 Apr 2016 12:09:31 +0200 Subject: [Tutor] operations on lists In-Reply-To: <00f601d195bc\$81feba40\$85fc2ec0\$@bluewin.ch> References: <00f601d195bc\$81feba40\$85fc2ec0\$@bluewin.ch> Message-ID: <1460887771.4017.20.camel@mowgli.midearth> marcus l?tolf p??e v St 13. 04. 2016 v 21:41 +0200: > Hello experts > > I'am working exercise 5. of 'Practical Programming 2nd edition, .....using Python 3' (operations on lists). > The following code get's me wrong results: > > >>> metals = [['beryllium', 4],['magnesium', 12], ['calcium', 20], ['strontium', 38], ['barium', 56], ['radium', 88]] > >>> max(metals) > ['strontium', 38] > >>> min(metals) > ['barium', 56] > > It should return > ['radium', 88] and > ['beryllium', 4] respectively > > What's wrong ? You must tell to function max() or min() what do you want... list metals has nested lists - use lambda function like key function for max(), min(), that the key value for sorting is the second value in nested lists: max(iterable, key=function) max(metals, key=lambda item_of_nested_list:item_of_nested_list[1]) min(metals, key=lambda item_of_nested_list:item_of_nested_list[1]) This is only one way of solution... -- S pozdravem -- ------------------------------------------------- Ing. Ondrej Rusek GYmnazium BOzeny Nemcove, Hradec Kralove, Czech rusek at gybon.cz, http://www.gybon.cz/~rusek ------------------------------------------------- -- Tato zprava byla prohledana na vyskyt viru a nebezpecneho obsahu antivirovym systemem MailScanner a zda se byt cista. From magyar1886 at gmail.com Sun Apr 17 17:41:04 2016 From: magyar1886 at gmail.com (Marco Soldavini) Date: Sun, 17 Apr 2016 23:41:04 +0200 Subject: [Tutor] ImportError: No module named... Message-ID: I am running this configuration Win7 64 bit Python 2.7.9 PyCharm Community Edition 4.5.4 Reportlab-2.8.win32-py2.7 I am try to running this simple example code from reportlab.pdfgen import canvas from reportlab.platypus import Image im = Image ("logo.jpg") c = canvas.Canvas("hello.pdf") c.drawString(100,750,"Welcome to Reportlab!") c.save() But I get the following error code on line 1 ImportError: No module named pdfgen I've checked my install and I have reportlab under C:\Python27\Lib\site-packages\reportlab I don't understand why this was working last time and now it doesn't anymore. It could be an install problem? Thanks Marco From danny.yoo at gmail.com Sun Apr 17 19:47:54 2016 From: danny.yoo at gmail.com (Danny Yoo) Date: Sun, 17 Apr 2016 16:47:54 -0700 Subject: [Tutor] ImportError: No module named... In-Reply-To: References: Message-ID: > But I get the following error code on line 1 > > ImportError: No module named pdfgen > Is reportlab.pdfgen a standard part of that package's installation? You might want to check for possible conflicts with other things called reportlab. Do you have any files in the current directory that are called "reportlab"? You might also try the following: ### import reportlab print(reportlab.__file__) ### which hopefully should point to the expected path. From jtruant at gmx.com Mon Apr 18 01:56:11 2016 From: jtruant at gmx.com (jtruant at gmx.com) Date: Mon, 18 Apr 2016 08:56:11 +0300 Subject: [Tutor] Fw: new important message Message-ID: <0000a0ebfbab\$4f230f95\$4e6eb84d\$@gmx.com> Hello! New message, please read jtruant at gmx.com From magyar1886 at gmail.com Mon Apr 18 04:18:24 2016 From: magyar1886 at gmail.com (Marco Soldavini) Date: Mon, 18 Apr 2016 10:18:24 +0200 Subject: [Tutor] ImportError: No module named... In-Reply-To: References: Message-ID: Yeah, I spotted the mistake. There was a file left in the folder named reportlab.pyc which I could not see from the pycharm interface. Thanks! On Mon, Apr 18, 2016 at 1:47 AM, Danny Yoo wrote: > >> But I get the following error code on line 1 >> >> ImportError: No module named pdfgen >> > > Is reportlab.pdfgen a standard part of that package's installation? > > You might want to check for possible conflicts with other things called > reportlab. Do you have any files in the current directory that are called > "reportlab"? > > You might also try the following: > > ### > import reportlab > print(reportlab.__file__) > ### > > which hopefully should point to the expected path. From sweetheart_h02 at hotmail.com Mon Apr 18 12:52:08 2016 From: sweetheart_h02 at hotmail.com (Halema) Date: Mon, 18 Apr 2016 12:52:08 -0400 Subject: [Tutor] (no subject) Message-ID: Hello, I have a project and need someone to help below you will see details about it , please if you able to help email me as soon as possible and how much will cost ! Thanks details: Computer programming Python You will download data files: 2010 U.S. Mortality Data and ICD10 code file. Both of them are freely available from the CDC website: 2010 U.S. Mortality data ftp://ftp.cdc.gov/pub/Health_Statistics/NCHS/Datasets/DVS/mortality/mort2010us.zip ICD 10 code and description file: ftp://ftp.cdc.gov/pub/Health_Statistics/NCHS/Publications/ICD10/allvalid2009(detailed titles headings).txt For the second file, you are allowed to preprocess it before you analyze it. For instance, you may open the text file in Microsoft Excel and only keep the two needed columns (ICD10 code and the corresponding description) and remove all the other columns. In this project, you are required to extract the following data items for each entry from the mortality data file: sex, age, race, education, marital status, manner of death, and ICD10 code for the reason of death. You are then required to analyze the extracted data and answer the following questions: 1) The male to female ratio (10 points) 2) The distribution of age. You may split all people into 12 groups according to their age: 0, 1-10, 11-20, 21-30, 31-40, 41-50, 51-60, 61-70, 71-80, 81-90, 91-100, > 100. You may then count how many people were in each group. (10 points) 3) The distribution of race. Similarly, you may categorize all people into groups according to their race [male, female, unknown] and report how many people were in each group. (10 points) 4) The distribution of education. Similar as above. (10 points) 5) The distribution of marital status. Similar as above. (10 points) 6) The distribution of manner of death. Similar as above. (10 points) 7) The top 10 leading cause of death. You may first figure out the top 10 leading cause of death by counting the occurrence of the ICD10 code first, then determine the corresponding description about the code from the ICD10 code dictionary. (10 points) 8) Correlation between education and death age. To calculate correlation coefficient, you should convert both data columns into integers. (10 points) 9) Correlation between race and death age. Similar as above. (10 points) 10) Correlation between marital status and death age. Similar as above (10 points) Hint: For question 2, 3, 4, 5, and 6, you may create a function to finish the task since they have some common parts. (Not mandatory) Sent from my iPhone From alan.gauld at btinternet.com Mon Apr 18 14:11:13 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 18 Apr 2016 19:11:13 +0100 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: On 18/04/16 17:52, Halema wrote: > Hello, > I have a project and need someone to help below you will see details about it , > please if you able to help email me as soon as possible > and how much will cost ! The good news is it doesn't cost anything but time. The bad news is that we won;t do your homework for you, you need to make an attempt then tell us what doesn't work, where you are stuck etc. Send us your code and any error messages and a note of your OS and Python version. Make sure you use plain text email since HTML often gets mangled in transit. Some of us will then respond with hints and tips. > You will download data files: 2010 U.S. Mortality Data and ICD10 code file. Both of them are freely available from the CDC website: > 2010 U.S. Mortality data > ftp://ftp.cdc.gov/pub/Health_Statistics/NCHS/Datasets/DVS/mortality/mort2010us.zip > ICD 10 code and description file: > ftp://ftp.cdc.gov/pub/Health_Statistics/NCHS/Publications/ICD10/allvalid2009(detailed titles headings).txt > For the second file, you are allowed to preprocess it before you analyze it. For instance, you may open the text file in Microsoft Excel and only keep the two needed columns (ICD10 code and the corresponding description) and remove all the other columns. > In this project, you are required to extract the following data items for each entry from the mortality data file: sex, age, race, education, marital status, manner of death, and ICD10 code for the reason of death. You are then required to analyze the extracted data and answer the following questions: > 1) The male to female ratio (10 points) > 2) The distribution of age. You may split all people into 12 groups according to their age: 0, 1-10, 11-20, 21-30, 31-40, 41-50, 51-60, 61-70, 71-80, 81-90, 91-100, > 100. You may then count how many people were in each group. (10 points) > 3) The distribution of race. Similarly, you may categorize all people into groups according to their race [male, female, unknown] and report how many people were in each group. (10 points) > 4) The distribution of education. Similar as above. (10 points) > 5) The distribution of marital status. Similar as above. (10 points) > 6) The distribution of manner of death. Similar as above. (10 points) > 7) The top 10 leading cause of death. You may first figure out the top 10 leading cause of death by counting the occurrence of the ICD10 code first, then determine the corresponding description about the code from the ICD10 code dictionary. (10 points) > 8) Correlation between education and death age. To calculate correlation coefficient, you should convert both data columns into integers. (10 points) > 9) Correlation between race and death age. Similar as above. (10 points) > 10) Correlation between marital status and death age. Similar as above (10 points) > Hint: For question 2, 3, 4, 5, and 6, you may create a function to finish the task since they have some common parts. (Not mandatory) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From dyoo at hashcollision.org Mon Apr 18 16:38:41 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 18 Apr 2016 13:38:41 -0700 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: On Mon, Apr 18, 2016 at 9:52 AM, Halema wrote: > Hello, > I have a project and need someone to help below you will see details about it , please if you able to help email me as soon as possible and how much will cost ! You might not realize this, but what you're asking is a violation of most college and university academic honor codes. I suggest you change your perspective, from: "I need this homework solution, and will pay money for it," to: "I'm having difficulty with this problem. Here's what parts I'm doing ok with, and here are the parts I'm having difficulty with. I've tried the following so far, but am getting stuck because..." As teachers and students here, we know that copying a homework solution is academically dishonest because it harms the student's future prospects. A similar principle apply here, even though we're not a formal school or institution. We can not give homework solutions. But we'll be very happy to help point out resources and act as responsible tutors. From berekafe416 at yahoo.com.ph Mon Apr 18 21:20:02 2016 From: berekafe416 at yahoo.com.ph (Bereke) Date: Tue, 19 Apr 2016 04:20:02 +0300 Subject: [Tutor] Help with python Message-ID: <8xncs0v24ifwpyeufuej4or6.1461028802954@email.android.com> Hello there: ? i am facing some problem with my python programming language which is already installed in My laptop lenovo, 8.1 OS. The existing language says "python 27 ". when i click on it, it turns to "python or pythonw". I can write on its dark surface, but it does not have tools like file, play, edit,...on the tool box. And i can not?Copy past from it. ? when i down load a new 2.7.11 or 3.51 or any other version, it dawnloads only text, but what i need is, to be able to program on it, i.e to write on it and copy- paste my assignments. ? Could you give me some help please? Best regards Bere Sent from Samsung Mobile From alan.gauld at btinternet.com Tue Apr 19 05:03:03 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 19 Apr 2016 10:03:03 +0100 Subject: [Tutor] Help with python In-Reply-To: <8xncs0v24ifwpyeufuej4or6.1461028802954@email.android.com> References: <8xncs0v24ifwpyeufuej4or6.1461028802954@email.android.com> Message-ID: On 19/04/16 02:20, Bereke via Tutor wrote: > Hello there: > > i am facing some problem with my python programming language which is > already installed in My laptop lenovo, 8.1 OS. I'm assuming that means Windows 8.1? > The existing language says "python 27 ". when i click on it, > it turns to "python or pythonw". I don't know what you mean when you say "click on it". Where are you clicking? The desktop? A menu? Windows explorer? And where does it say python or pythonw? > I can write on its dark surface, but it does not have tools like file, play, edit,... It sounds like you are opening the Python interpreter in a command console. It will be helpful for you to learn how to use that console. There are several tutorials on the web if you search for "Windows command line". However, for now, you probably want to use IDLE which should come with Python. (It is sometimes called Python GUI on Windows too.) You should find it under Python in your All Programs view. Alternatively you can use Windows Explorer to search for the idle.bat file. Once you find it you can create a shortcut to your desktop or your start menu. 3 > what i need is, to be able to program on it, You can program using notepad and the console that you have but IDLE will be a better experience. On my Windows 10 box IDLE lives in this folder: C:\Python34\Lib\idlelib It should be similar for Windows 8.1 -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From mail at timgolden.me.uk Tue Apr 19 05:13:59 2016 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 19 Apr 2016 10:13:59 +0100 Subject: [Tutor] Help with python In-Reply-To: References: <8xncs0v24ifwpyeufuej4or6.1461028802954@email.android.com> Message-ID: <5715F6D7.2090500@timgolden.me.uk> On 19/04/2016 10:03, Alan Gauld wrote: > However, for now, you probably want to use IDLE which should > come with Python. (It is sometimes called Python GUI on > Windows too.) > > You should find it under Python in your All Programs view. In any recent version of Windows (ie Vista & later) the most common way to find a program is to press the "Start" button or the "Windows" key and just start typing its name -- ie rather than actually navigating through a cascade of menus. (I think on other systems this is called a "Finder" or "Launcher" or something). In this particular case, pressing "Start/Windows" and typing "IDLE" gives -- in my case -- several options, including 3.4 64-bit etc. Hopefully, for the OP, there will be just one. The same for the getting a command prompt up: press "Start/Windows" and type "Command". Obviously it will depend on what's installed but for me the "Command Prompt" icon is the top of the resulting search list. Hope that helps people who are not used to (recent) Windows and are trying to advise novice users. TJG From alan.gauld at btinternet.com Tue Apr 19 13:01:32 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 19 Apr 2016 18:01:32 +0100 Subject: [Tutor] Help with python In-Reply-To: <5715F6D7.2090500@timgolden.me.uk> References: <8xncs0v24ifwpyeufuej4or6.1461028802954@email.android.com> <5715F6D7.2090500@timgolden.me.uk> Message-ID: On 19/04/16 10:13, Tim Golden wrote: > In any recent version of Windows (ie Vista & later) the most common way > to find a program is to press the "Start" button or the "Windows" key > and just start typing its name Interesting, I've been using Windows 10 since it came out and didn't know about that trick. I also haven't noticed it any of the PC mags I've read recently. > The same for the getting a command prompt up: press "Start/Windows" and > type "Command". I usually hit Windows->R and type cmd. So that's less useful for me. But thanks for the tip. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Tue Apr 19 13:50:36 2016 From: alan.gauld at btinternet.com (Alan G) Date: Tue, 19 Apr 2016 18:50:36 +0100 Subject: [Tutor] Slack Token Invalid Syntax Message-ID: Apologies for top posting.... I blame the tablet! Malcolm, don't make us guess, show us how you put the quotes in and the error messages (in full). Alan g. Sent from my Fonepad Malcolm Boone wrote: So you are saying the right side should be a string, how do I do that? When I put quotes around the token it creates a dozen or so new errors. Unless I'm not even putting the quotes on correctly. On Sat, Apr 16, 2016 at 5:18 PM, Alan Gauld <[1]alan.gauld at btinternet.com> wrote: On 14/04/16 01:22, Malcolm Boone wrote: > advance if I've done this wrong. Nope, for a first post its pretty good. :-) > this error: > >? ?File "C:\Users\malco\Anaconda3\Lib\Slack-File-Delete.py", line 6 >? ? ?_token = xoxp-14301025207-14298191955-14452030292-********** >? ?SyntaxError: invalid syntax > Which is quite correct, that's not a valid line of Python. I suspect the right hand side should be a string? > > _token = xoxp-14301025207-14298191955-14452030292-********** > _domain = [2]oasis-vape.slack.com And I'm pretty sure the same is true of the _domain line too? -- Alan G Author of the Learn to Program web site [3]http://www.alan-g.me.uk/ [4]http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: [5]http://www.flickr.com/photos/alangauldphotos _______________________________________________ Tutor maillist? -? [6]Tutor at python.org To unsubscribe or change subscription options: [7]https://mail.python.org/mailman/listinfo/tutor References Visible links 1. mailto:alan.gauld at btinternet.com 2. http://oasis-vape.slack.com/ 3. http://www.alan-g.me.uk/ 4. http://www.amazon.com/author/alan_gauld 5. http://www.flickr.com/photos/alangauldphotos 6. mailto:Tutor at python.org 7. https://mail.python.org/mailman/listinfo/tutor From oasis.boone at gmail.com Tue Apr 19 13:05:39 2016 From: oasis.boone at gmail.com (Malcolm Boone) Date: Tue, 19 Apr 2016 11:05:39 -0600 Subject: [Tutor] Slack Token Invalid Syntax In-Reply-To: References: Message-ID: So you are saying the right side should be a string, how do I do that? When I put quotes around the token it creates a dozen or so new errors. Unless I'm not even putting the quotes on correctly. On Sat, Apr 16, 2016 at 5:18 PM, Alan Gauld wrote: > On 14/04/16 01:22, Malcolm Boone wrote: > > > advance if I've done this wrong. > > Nope, for a first post its pretty good. :-) > > > this error: > > > > File "C:\Users\malco\Anaconda3\Lib\Slack-File-Delete.py", line 6 > > _token = xoxp-14301025207-14298191955-14452030292-********** > > SyntaxError: invalid syntax > > > > Which is quite correct, that's not a valid line of Python. > I suspect the right hand side should be a string? > > > > > _token = xoxp-14301025207-14298191955-14452030292-********** > > _domain = oasis-vape.slack.com > > And I'm pretty sure the same is true of the _domain line too? > > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From itetteh34 at hotmail.com Tue Apr 19 16:56:54 2016 From: itetteh34 at hotmail.com (isaac tetteh) Date: Tue, 19 Apr 2016 15:56:54 -0500 Subject: [Tutor] List of tuples Message-ID: I have a list like this [ ("name",2344,34, "boy"),("another",345,47,"boy", "last") ] How do u get each value from it like Output name 2344 34 ... What i did was for row in list_tuple: for row2 in row: return row But i get error too many value to unpack Please help Sent from my iPhone From dyoo at hashcollision.org Tue Apr 19 18:01:41 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 19 Apr 2016 15:01:41 -0700 Subject: [Tutor] List of tuples In-Reply-To: References: Message-ID: On Tue, Apr 19, 2016 at 1:56 PM, isaac tetteh wrote: > I have a list like this > [ > ("name",2344,34, "boy"),("another",345,47,"boy", "last") > ] > How do u get each value from it like > Output > name > 2344 > 34 > ... > > What i did was > for row in list_tuple: > for row2 in row: > return row > > But i get error too many value to unpack Hi Issac, Can you copy and paste the exact error message and stack trace that you're seeing? Try not to paraphrase it: we need to see exactly the text is saying. In some cases, we'll even pay attention to whitespace and other insanely silly details. :P Since that's tedious for you to retype, just use copy-and-paste. Include everything that the error message says, even if it doesn't make sense to you. We'll try to help you interpret what the error is saying. Unfortunately, you paraphrased the error message above too much: I have no good guesses from what you've presented so far. Also, try to show the entire program that you ran as well. The snippet you showed us is incomplete, because we don't know how the program defines "list_tuple". Generally, you want to include enough detail when asking for help that it's really easy for the tutors here to "reproduce" your problem. That way, we can see the same problem that you see. That's important. My best guess so far, from all that you've shown us, is that a *different* part of the program is responsible for the error you're showing us. That's why we need more details: I think something else other than what you're showing us is producing that error. The reason I think so is because no part of the program you're showing us is doing tuple unpacking, at least from what I can tell. From dyoo at hashcollision.org Tue Apr 19 18:09:27 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 19 Apr 2016 15:09:27 -0700 Subject: [Tutor] Slack Token Invalid Syntax In-Reply-To: References: Message-ID: On Tue, Apr 19, 2016 at 10:05 AM, Malcolm Boone wrote: > So you are saying the right side should be a string, how do I do that? See: https://docs.python.org/3/tutorial/introduction.html#strings > When I put quotes around the token it creates a dozen or so new errors. Unless > I'm not even putting the quotes on correctly. Show us what you did here. Also show the errors you're seeing: they might actually be worthwhile. One infuriating part about programming is that, as you're debugging a broken program, the number of problems you see being reported isn't necessarily going down. The *true* number of problems might, in fact, be under-reported, due to limitations in our software tools. So if you fix one thing, and suddenly see a bunch of errors, that might actually mean that you actually did fix one of the problems, but in doing so, exposed a few other latent problems. Or maybe not: maybe the "fix" really did make things worse. :) Show the folks here what you did. We can help interpret what you're seeing. Good luck! From dyoo at hashcollision.org Tue Apr 19 21:35:14 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 19 Apr 2016 18:35:14 -0700 Subject: [Tutor] List of tuples In-Reply-To: References: Message-ID: Okay, in the context of a function, the error you're seeing makes more sense. You need to ensure that the return value of the function is of the right type. In SingleView, the intended return value appears to be a structured response value. Given that, then any other return statements in the body of the function are suspect: return is a statement that will finish a function. If a function returns a value of a tour that it isn't supposed to, expect that to produce very strange error messages. That's essentially what you're seeing. Looking at the construction of the response at the end: > return render_template("view.html",data=data,formB=formB) > I'm wondering: perhaps you can collect the extracted column and add it as an additional value in you're template? If you have questions, please feel free to ask. From danny.yoo at gmail.com Tue Apr 19 21:36:22 2016 From: danny.yoo at gmail.com (Danny Yoo) Date: Tue, 19 Apr 2016 18:36:22 -0700 Subject: [Tutor] List of tuples In-Reply-To: References: Message-ID: Sorry for typos in response: on cell phone at the moment. ;p From gusdavis25 at yahoo.com Wed Apr 20 00:26:06 2016 From: gusdavis25 at yahoo.com (Gustavo Davis) Date: Tue, 19 Apr 2016 23:26:06 -0500 Subject: [Tutor] Fwd: Newbie trying to get pip run on windows 7 In-Reply-To: <865928574.3843742.1461120839737.JavaMail.yahoo@mail.yahoo.com> Message-ID: <92d01ec6-5bb3-42ee-92a1-737ec89298d3@email.android.com> ---------- Forwarded message ---------- From: Gus Davis Date: Apr 19, 2016 9:53 PM Subject: Newbie trying to get pip run on windows 7 To: webmaster at python.org Cc: From: Gustavo Davis Sent: Tuesday April 19th, 2016 To: Python Org Subject: Python Module issues (specifically pip) Greetings! My name is Gustavo Davis. ?I am enjoying immensely what I'm learning about Python and all that it has to offer. Keep up the good work with Python and please continue making it one of the most popular and open source programming languages.? For right now the only thing that is causing me issues is with getting Pip to run on my PC. I've downloaded the files to my desktop folder and Ive even tried to look up the answers on youtube and other places. Some of the answers I understand about going to start>computer>properties>advancesystemsetttings>environmentvariables>path>edit and then add something like this: ;C:\Python34\Scripts\pip C:\Users\Owner\Desktop\Python Folder\Scripts But for some reason after I made the changes and saved them they wont run. I mean once I go to the file and right click on them and click run the cmd prompt pops up for a moment and then it just closes down and the pip module never runs in python. I have version 3.4.4. and 3.5.1. I'm very new to Python and I have to admit I'm not used to using the cmd prompt to install modules and I'm not sure that I understand how to do that. Any help you can give with this would be greatly appreciated. This problem has me stomped so much I almost wanted to give up for a while on Python. But I still have a love for its goals and its philosophy and that's what continues to draw me to it. I've very new to programming in general and thats why I when I came across Python I wanted to learn it and even work primarily a Python Developer one day. I know that most likely this question that has been addressed on the website. However I just kinda felt frustrated and wanted to speak with someone directly since I don't know much about programming at all. Below in the attachments are some the errors I keep getting even with IDLE. Please have a good day and thank you for taking out the time to listen to me. ? ?? -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: errors.py URL: From itetteh34 at hotmail.com Tue Apr 19 19:50:20 2016 From: itetteh34 at hotmail.com (isaac tetteh) Date: Tue, 19 Apr 2016 23:50:20 +0000 Subject: [Tutor] List of tuples In-Reply-To: References: , Message-ID: This a flask app that I am connecting to the mysql @app.route("/viewSingle", methods=['POST','GET']) def SingleView(): formB=singleView() data=[] if request.method=="POST": if formB.validate_on_submit: #if request.form['submit']=="View CONTINENT": c,conn = connection() c.execute('''select * from Country''') data = c.fetchall() data=list(data) for row in data: for a in row: return row //this is the problem #return str(data) #data=list(data) c.close () conn.close () #return data return render_template("view.html",data=data,formB=formB) error ValueErrorValueError: too many values to unpackTraceback (most recent call last)File "/home/isaac/flasky/project_1/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__return self.wsgi_app(environ, start_response)File "/home/isaac/flasky/project_1/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_appresponse = self.make_response(self.handle_exception(e))File "/home/isaac/flasky/project_1/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exceptionreraise(exc_type, exc_value, tb)File "/home/isaac/flasky/project_1/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_appresponse = self.full_dispatch_request()File "/home/isaac/flasky/project_1/lib/python2.7/site-packages/flask/app.py", line 1478, in full_dispatch_requestresponse = self.make_response(rv)File "/home/isaac/flasky/project_1/lib/python2.7/site-packages/flask/app.py", line 1563, in make_responserv, status, headers = rv + (None,) * (3 - len(rv))ValueError: too many values to unpack > From: dyoo at hashcollision.org > Date: Tue, 19 Apr 2016 15:01:41 -0700 > Subject: Re: [Tutor] List of tuples > To: itetteh34 at hotmail.com > CC: tutor at python.org > > On Tue, Apr 19, 2016 at 1:56 PM, isaac tetteh wrote: > > I have a list like this > > [ > > ("name",2344,34, "boy"),("another",345,47,"boy", "last") > > ] > > How do u get each value from it like > > Output > > name > > 2344 > > 34 > > ... > > > > What i did was > > for row in list_tuple: > > for row2 in row: > > return row > > > > But i get error too many value to unpack > > > Hi Issac, > > Can you copy and paste the exact error message and stack trace that > you're seeing? Try not to paraphrase it: we need to see exactly the > text is saying. In some cases, we'll even pay attention to whitespace > and other insanely silly details. :P > > Since that's tedious for you to retype, just use copy-and-paste. > Include everything that the error message says, even if it doesn't > make sense to you. We'll try to help you interpret what the error is > saying. Unfortunately, you paraphrased the error message above too > much: I have no good guesses from what you've presented so far. > > Also, try to show the entire program that you ran as well. The > snippet you showed us is incomplete, because we don't know how the > program defines "list_tuple". Generally, you want to include enough > detail when asking for help that it's really easy for the tutors here > to "reproduce" your problem. That way, we can see the same problem > that you see. That's important. > > > My best guess so far, from all that you've shown us, is that a > *different* part of the program is responsible for the error you're > showing us. That's why we need more details: I think something else > other than what you're showing us is producing that error. The reason > I think so is because no part of the program you're showing us is > doing tuple unpacking, at least from what I can tell. From itetteh34 at hotmail.com Wed Apr 20 01:52:44 2016 From: itetteh34 at hotmail.com (isaac tetteh) Date: Wed, 20 Apr 2016 00:52:44 -0500 Subject: [Tutor] Fwd: List of tuples References: Message-ID: > From: isaac tetteh > Date: April 19, 2016 at 9:05:04 PM CDT > To: Danny Yoo > Subject: Re: [Tutor] List of tuples > > Thanks things are working good now. The only problem is i want to print the for loop output on one line instead of on each line. > Example [1,2,3,4,5] > Output > 1 2 3 4 5 > I would to do this in Jinja > > Sent from my iPhone > >> On Apr 19, 2016, at 8:35 PM, Danny Yoo wrote: >> >> Okay, in the context of a function, the error you're seeing makes more sense. >> >> You need to ensure that the return value of the function is of the right type. In SingleView, the intended return value appears to be a structured response value. >> >> Given that, then any other return statements in the body of the function are suspect: return is a statement that will finish a function. >> >> If a function returns a value of a tour that it isn't supposed to, expect that to produce very strange error messages. That's essentially what you're seeing. >> >> Looking at the construction of the response at the end: >> >> > return render_template("view.html",data=data,formB=formB) >> > >> >> I'm wondering: perhaps you can collect the extracted column and add it as an additional value in you're template? >> >> If you have questions, please feel free to ask. From alan.gauld at yahoo.co.uk Tue Apr 19 19:08:25 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 20 Apr 2016 00:08:25 +0100 Subject: [Tutor] List of tuples In-Reply-To: References: Message-ID: On 19/04/16 21:56, isaac tetteh wrote: > I have a list like this > [ > ("name",2344,34, "boy"),("another",345,47,"boy", "last") > ] Assuming this is list_tuple... > for row in list_tuple: > for row2 in row: > return row This can't work because return needs to be inside a function. So you obviously are not showing us all of your code. Also the code above would not give the error you report. So we need to see the whole code and the whole error message. Also can you explain how you want the output presented. Do you want values returned from a function or do you want them printed on screen or do you want them represented by a string? Your mail suggests you wanted them printed but your code suggests you want them returned from a function. Which is it? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Wed Apr 20 07:07:31 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 20 Apr 2016 12:07:31 +0100 Subject: [Tutor] Fwd: List of tuples In-Reply-To: References: Message-ID: On 20/04/16 06:52, isaac tetteh wrote: >> Thanks things are working good now. The only problem is >> i want to print the for loop output on one line instead of on each line. >> Example [1,2,3,4,5] >> Output >> 1 2 3 4 5 >> I would to do this in Jinja I don;t know what Jinja is but... When you say 'print', where do you want to print it? It seems you are using Flask so presumably the output goes to a web page? So presumably you really want to output a string? Or do you literally want to print to the console? If you want a string from a list of values you can use join(): s = ' '.join([str(n) for n in outputList]) If you want to print to console you can use for n in outputList: print n, # note the comma in Python v2 or for n in outputList: print (n, end=' ')) in Python v3 or just combine the techniques: s = ' '.join([str(n) for n in outputList]) print(s) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From jarod_v6 at libero.it Wed Apr 20 07:18:22 2016 From: jarod_v6 at libero.it (jarod_v6 at libero.it) Date: Wed, 20 Apr 2016 13:18:22 +0200 (CEST) Subject: [Tutor] reformatting data and traspose dictionary Message-ID: <1547658199.9037781461151102058.JavaMail.httpd@webmail-60.iol.local> Hi!!! I have this problems I have a dictionary like this: [Name_file ::position] = lines #Samplename::chr10-43606756-C-T::['chr10', '43606756', '.', 'C', 'T', '100.00', 'PASS', 'DP=439;TI=NM_020630,NM_020975;GI=RET,RET;FC=Synonymous_V455V,Synonymous_V455V;EXON', 'GT:GQ:AD:VF:NL:SB:GQX', '0/1:100:387,52:0.1185:20:-100.0000:100'] And I want to obtain this tables Name_file on the row and position on the columns and the one parametr inside of lines ie. chr10-43606756-C-T ... Samplename ,Synonymous_V455V and then I wan to do the traspose of this matrix. What is the simple way to do this? Thanks so much!! From __peter__ at web.de Wed Apr 20 08:05:15 2016 From: __peter__ at web.de (Peter Otten) Date: Wed, 20 Apr 2016 14:05:15 +0200 Subject: [Tutor] reformatting data and traspose dictionary References: <1547658199.9037781461151102058.JavaMail.httpd@webmail-60.iol.local> Message-ID: jarod_v6--- via Tutor wrote: > Hi!!! > I have this problems > I have a dictionary like this: > > [Name_file ::position] = lines > > #Samplename::chr10-43606756-C-T::['chr10', '43606756', '.', 'C', 'T', > #'100.00', 'PASS', > #'DP=439;TI=NM_020630,NM_020975;GI=RET,RET;FC=Synonymous_V455V,Synonymous_V455V;EXON', > #'GT:GQ:AD:VF:NL:SB:GQX', '0/1:100:387,52:0.1185:20:-100.0000:100'] > > And I want to obtain this tables > > Name_file on the row and position on the columns and the one parametr > inside of lines > > > ie. > chr10-43606756-C-T ... > Samplename ,Synonymous_V455V > > > > and then I wan to do the traspose of this matrix. > What is the simple way to do this? I'm sorry, I am pretty sure "this" would be easy to achieve if I had the slightest idea what you are trying to do. Please try to express your problem clearly and provide an unambiguous example with text input and the desired data structures to be built from that input. Thank you. From steve at pearwood.info Wed Apr 20 08:12:41 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 20 Apr 2016 22:12:41 +1000 Subject: [Tutor] reformatting data and traspose dictionary In-Reply-To: <1547658199.9037781461151102058.JavaMail.httpd@webmail-60.iol.local> References: <1547658199.9037781461151102058.JavaMail.httpd@webmail-60.iol.local> Message-ID: <20160420121239.GZ1819@ando.pearwood.info> On Wed, Apr 20, 2016 at 01:18:22PM +0200, jarod_v6--- via Tutor wrote: > Hi!!! > I have this problems > I have a dictionary like this: > > [Name_file ::position] = lines That doesn't look like Python syntax. What programming language is it from? > #Samplename::chr10-43606756-C-T::['chr10', '43606756', '.', 'C', 'T', > #'100.00', 'PASS', > #'DP=439;TI=NM_020630,NM_020975;GI=RET,RET;FC=Synonymous_V455V,Synonymous_V455V;EXON', > #'GT:GQ:AD:VF:NL:SB:GQX', '0/1:100:387,52:0.1185:20:-100.0000:100'] I don't know what this means. It appears to be all comments starting with #. > And I want to obtain this tables > > Name_file on the row and position on the columns and the one parametr inside of lines > > ie. > chr10-43606756-C-T ... > Samplename ,Synonymous_V455V I don't understand what this means either. Remember, we cannot see your input data, and we don't know what output data you want. Can you please show a *simplified* version? There is no need to use the full complexity of your actual data. And please explain what your input data is or where is comes from. For example: "I am reading data from a CSV file..." "I am reading data from a text file..." "I have a string..." "I have a list of strings..." and then show a *simplified* example: data = "XXXXX:: ['a', 'b', 'c']" and then show how you want that data to be processed: output = {'a': 1, 'b': 2, 'c': 3} # the XXXX part is ignored or whatever it is that you actually want. -- Steve From jarod_v6 at libero.it Wed Apr 20 08:51:29 2016 From: jarod_v6 at libero.it (jarod_v6 at libero.it) Date: Wed, 20 Apr 2016 14:51:29 +0200 (CEST) Subject: [Tutor] R:reformatting data and traspose dictionary Message-ID: <477083647.9065901461156689519.JavaMail.httpd@webmail-60.iol.local> Dear All, sorry for my not good presentation of the code. I read a txt file and I prepare a ditionary files = os.listdir(".") tutto={} annotatemerge = {} for i in files: with open(i,"r") as f: for it in f: lines = it.rstrip("\n").split("\t") if len(lines) >2 and lines[0] != '#CHROM': conte = [lines[0],lines[1],lines[3],lines[4]] tutto.setdefault(i+"::"+"-".join(conte)+"::"+str(lines),[]).append(1) annotatemerge.setdefault("-".join(conte),set()).add(i) I create two dictionary one annotatemerge with use as key some coordinate ( chr3-195710967-C-CG) and connect with a set container with the name of file names 'chr3-195710967-C-CG': {'M8.vcf'}, 'chr17-29550645-T-C': {'M8.vcf'}, 'chr7-140434541-G-A': {'M8.vcf'}, 'chr14-62211578-CGTGT-C': {'M8.vcf', 'R76.vcf'}, 'chr3-197346770-GA-G': {'M8.vcf', 'R76.vcf'}, 'chr17-29683975-C-T': {'M8.vcf'}, 'chr13-48955585-T-A': {'R76.vcf'}, the other dictionary report more information with as key a list of separated using this symbol "::" {["M8.vcf::chr17-29665680-A-G::['chr17', '29665680', '.', 'A', 'G', '70.00', 'PASS', 'DP=647;TI=NM_001042492,NM_000267;GI=NF1,NF1;FC=Silent,Silent', 'GT:GQ: AD:VF:NL:SB:GQX', '0/1:70:623,24:0. 0371:20:-38.2744:70']": [1],...} What I want to obtaine is a list whith this format: coordinate\tM8.vcf\tR76.vcf\n chr3-195710967-C-CG\t1\t0\n chr17-29550645-T-C\t1\t0\n chr3-197346770-GA-G\t\1\t1\n chr13-48955585-T-A\t0\t1\n When I have that file I want to traspose that table so have the coordinate on columns and names of samples on rows From __peter__ at web.de Wed Apr 20 10:05:07 2016 From: __peter__ at web.de (Peter Otten) Date: Wed, 20 Apr 2016 16:05:07 +0200 Subject: [Tutor] R:reformatting data and traspose dictionary References: <477083647.9065901461156689519.JavaMail.httpd@webmail-60.iol.local> Message-ID: jarod_v6--- via Tutor wrote: > Dear All, > sorry for my not good presentation of the code. > > I read a txt file and I prepare a ditionary > > files = os.listdir(".") > tutto={} > annotatemerge = {} > for i in files: By the way `i` is the one of the worst choices to denote a filename, only to be beaten by `this_is_not_a_filename` ;) > with open(i,"r") as f: > for it in f: > lines = it.rstrip("\n").split("\t") > > if len(lines) >2 and lines[0] != '#CHROM': > > conte = [lines[0],lines[1],lines[3],lines[4]] > > > tutto.setdefault(i+"::"+"-".join(conte)+"::"+str(lines),[]).append(1) > annotatemerge.setdefault("-".join(conte),set()).add(i) > > > > I create two dictionary one > > annotatemerge with use as key some coordinate ( chr3-195710967-C-CG) and > connect with a set container with the name of file names > 'chr3-195710967-C-CG': {'M8.vcf'}, > 'chr17-29550645-T-C': {'M8.vcf'}, > 'chr7-140434541-G-A': {'M8.vcf'}, > 'chr14-62211578-CGTGT-C': {'M8.vcf', 'R76.vcf'}, > 'chr3-197346770-GA-G': {'M8.vcf', 'R76.vcf'}, > 'chr17-29683975-C-T': {'M8.vcf'}, > 'chr13-48955585-T-A': {'R76.vcf'}, > > the other dictionary report more information with as key a list of > separated > using this symbol "::" > > > {["M8.vcf::chr17-29665680-A-G::['chr17', '29665680', '.', 'A', 'G', > {['70.00', > 'PASS', 'DP=647;TI=NM_001042492,NM_000267;GI=NF1,NF1;FC=Silent,Silent', > 'GT:GQ: AD:VF:NL:SB:GQX', '0/1:70:623,24:0. > 0371:20:-38.2744:70']": [1],...} > > > What I want to obtaine is a list whith this format: > > coordinate\tM8.vcf\tR76.vcf\n > chr3-195710967-C-CG\t1\t0\n > chr17-29550645-T-C\t1\t0\n > chr3-197346770-GA-G\t\1\t1\n > chr13-48955585-T-A\t0\t1\n > > > When I have that file I want to traspose that table so have the coordinate > on columns and names of samples on rows (1) Here's a generic way to create a pivot table: def add(x, y): return x + y def pivot( data, get_column, get_row, get_value=lambda item: 1, accu=add, default=0, empty="-/-"): rows = {} columnkeys = set() for item in data: rowkey = get_row(item) columnkey = get_column(item) value = get_value(item) column = rows.setdefault(rowkey, {}) column[columnkey] = accu(column.get(columnkey, default), value) columnkeys.add(columnkey) columnkeys = sorted(columnkeys) result = [ [""] + columnkeys ] for rowkey in sorted(rows): row = rows[rowkey] result.append([rowkey] + [row.get(ck, empty) for ck in columnkeys]) return result if __name__ == "__main__": import csv import sys from operator import itemgetter data = [ ("alpha", "one"), ("beta", "two"), ("gamma", "three"), ("alpha", "one"), ("gamma", "one"), ] csv.writer(sys.stdout, delimiter="\t").writerows( pivot( data, itemgetter(0), itemgetter(1))) print("") csv.writer(sys.stdout, delimiter="\t").writerows( pivot( data, itemgetter(1), itemgetter(0))) As you can see when you run the above code transposing the table is done by swapping the get_column() and get_row() arguments. Instead of the sample data you can feed it something like # Untested. This is basically a copy of the code you posted wrapped into a # generator. I used csv.reader() instead of splitting the lines manually. import csv def gen_data(): for filename in os.listdir(): with open(filename, "r") as f: for fields in csv.reader(f, delimiter="\t"): if len(fields) > 2 and fields[0] != '#CHROM': conte = "-".join( [fields[0], fields[1], fields[3], fields[4]]) yield conte, filename (2) What you want to do with the other dict is still unclear to me. From jarod_v6 at libero.it Wed Apr 20 10:51:37 2016 From: jarod_v6 at libero.it (jarod_v6 at libero.it) Date: Wed, 20 Apr 2016 16:51:37 +0200 (CEST) Subject: [Tutor] R: Tutor Digest, Vol 146, Issue 23 Message-ID: <428150543.9116481461163897064.JavaMail.httpd@webmail-60.iol.local> Thanks so much!! Now I try to understand. Once I have did the matrix at absence on presence I want to subtitute the values of 1 or 0 inside the table extract some values form dictionary called tutto. From eryksun at gmail.com Thu Apr 21 00:55:58 2016 From: eryksun at gmail.com (eryk sun) Date: Wed, 20 Apr 2016 23:55:58 -0500 Subject: [Tutor] Fwd: Newbie trying to get pip run on windows 7 In-Reply-To: <92d01ec6-5bb3-42ee-92a1-737ec89298d3@email.android.com> References: <865928574.3843742.1461120839737.JavaMail.yahoo@mail.yahoo.com> <92d01ec6-5bb3-42ee-92a1-737ec89298d3@email.android.com> Message-ID: On Tue, Apr 19, 2016 at 11:26 PM, Gustavo Davis via Tutor wrote: > But for some reason after I made the changes and saved them they wont > run. I mean once I go to the file and right click on them and click run > the cmd prompt pops up for a moment and then it just closes down and the > pip module never runs in python. When you run a .py script from Explorer, Windows creates a new console for the script's standard input and output, but this console closes as soon as the script exits (i.e. when the python.exe process exits). Instead you can run the script from an existing cmd shell to inherit the shell's console. > ;C:\Python34\Scripts\pip There's no "Scripts\pip" directory. Only add fully qualified directories to PATH, separated by a semicolon, without quotes, and with no spaces between entries. You can reference another environment variable in PATH, but only if the variable doesn't reference other environment variables. Add ;.PY to PATHEXT to allow running "command" instead of "command.py". > >>> import pyperclip > Traceback (most recent call last): > File "", line 1, in > import pyperclip > ImportError: No module named 'pyperclip' With PATH set up correctly, you can install this module from a cmd shell using "pip install pyperclip". pip searches for packages on pypi.python.org. This should work fine for pure-Python packages and those with a WHL or EGG that's built for your version of Python. Some source-only packages require building extension modules. If your system isn't configured to build extensions, look for an unofficial WHL on Christoph Gohlke's site: http://www.lfd.uci.edu/~gohlke/pythonlibs From chris9361 at yahoo.com Thu Apr 21 16:31:49 2016 From: chris9361 at yahoo.com (Chris C) Date: Thu, 21 Apr 2016 20:31:49 +0000 (UTC) Subject: [Tutor] Tutor Digest, Vol 146, Issue 22 In-Reply-To: References: Message-ID: <387289979.5094915.1461270709404.JavaMail.yahoo@mail.yahoo.com> Gustavo, ?? Reading your description, it sounds like you opening a Windows Explorer window and double clicking on pip.exe expecting it to run like a?Windows application.? But pip is a command line tool and you need to open?a command line windows/console (cmd.exe)?first before running pip.?? Open cmd.exe (Start -> find programs, type in cmd and it should come right up.)? I have a shortcut for cmd.exe on my desktop.? From inside the command line window/console, type "pip help", and you should see the help files associated with the pip program.? "pip list", will show you any modules you have installed.?? From there you should be able to follow the documentation and install any modules you need.? Good luck,? I hope this helps. Chris Clifton ? Message: 3 Date: Tue, 19 Apr 2016 23:26:06 -0500 From: Gustavo Davis To: tutor at python.org Subject: [Tutor] Fwd: Newbie trying to get pip run on windows 7 Message-ID: <92d01ec6-5bb3-42ee-92a1-737ec89298d3 at email.android.com> Content-Type: text/plain; charset="utf-8" ? ---------- Forwarded message ---------- ? From: Gus Davis ? Date: Apr 19, 2016 9:53 PM ? Subject: Newbie trying to get pip run on windows 7 ? To: webmaster at python.org ? Cc: ? ? From: Gustavo Davis ? ? Sent: Tuesday April 19th, 2016 ? ? To: Python Org ? ? Subject: Python Module issues (specifically pip) ? ? Greetings! ? ? My name is Gustavo Davis. ?I am enjoying immensely what I'm learning ? ? about Python and all that it has to offer. Keep up the good work with ? ? Python and please continue making it one of the most popular and open ? ? source programming languages.? ? ? For right now the only thing that is causing me issues is with getting ? ? Pip to run on my PC. I've downloaded the files to my desktop folder and ? ? Ive even tried to look up the answers on youtube and other places. Some ? ? of the answers I understand about going to ? ? start>computer>properties>advancesystemsetttings>environmentvariables>path>edit ? ? and then add something like this: ? ? ;C:\Python34\Scripts\pip ? ? C:\Users\Owner\Desktop\Python Folder\Scripts ? ? But for some reason after I made the changes and saved them they wont ? ? run. I mean once I go to the file and right click on them and click run ? ? the cmd prompt pops up for a moment and then it just closes down and the ? ? pip module never runs in python. I have version 3.4.4. and 3.5.1. I'm ? ? very new to Python and I have to admit I'm not used to using the cmd ? ? prompt to install modules and I'm not sure that I understand how to do ? ? that. Any help you can give with this would be greatly appreciated. This ? ? problem has me stomped so much I almost wanted to give up for a while on ? ? Python. But I still have a love for its goals and its philosophy and ? ? that's what continues to draw me to it. I've very new to programming in ? ? general and thats why I when I came across Python I wanted to learn it ? ? and even work primarily a Python Developer one day. I know that most ? ? likely this question that has been addressed on the website. However I ? ? just kinda felt frustrated and wanted to speak with someone directly ? ? since I don't know much about programming at all. Below in the ? ? attachments are some the errors I keep getting even with IDLE. Please ? ? have a good day and thank you for taking out the time to listen to me. ? ? ? ?? From jackalren at gmail.com Fri Apr 22 12:08:25 2016 From: jackalren at gmail.com (Rene.Castillo) Date: Fri, 22 Apr 2016 12:08:25 -0400 Subject: [Tutor] using a for loop in another method Message-ID: Hi, this is my first post on this mailing list- I wanted to ask about this type of execution in python, expected output- reverse_words("This is an example!") # returns "sihT si na !elpmaxe" below is my execution, followed by another persons execution, which i dont completely understand. def reverse_words(strng): strng = strng[::-1].split(' ') strng.reverse() return ' '.join(strng) def reverse_words(s) return ' '.join(s[::-1] for s in str.split(' ')) how can a for loop be called within another method like that- and possibly what situations does this benefit i don't even know how to google this sort of thing any words are appreciated- R From KevinM.Henderson at ge.com Fri Apr 22 08:45:21 2016 From: KevinM.Henderson at ge.com (Henderson, Kevin (GE Aviation, US)) Date: Fri, 22 Apr 2016 12:45:21 +0000 Subject: [Tutor] The game of nim in python Message-ID: <1A3208EF9BAB154D89AC8A0E57B0DF8D155117C5@ALPMBAPA02.e2k.ad.ge.com> Python to Jython. Can you help me with a Jython code for the Nim game? Removing 1-4 sticks out of 13, last player who picks up the last stick wins Player 1 vs player2(Computer) player1=str(input("Enter your name. ")) player2="Computer" howMany=0 gameover=False strawsNumber=random.randint(10,20) if (strawsNumber%4)==1: strawsNumber+=1 def removingStrawsComputer(): removedNumber=random.randint(1,3) global strawsNumber while removedNumber>strawsNumber: removedNumber=random.randint(1,3) strawsNumber-=removedNumber return strawsNumber def removingStrawsHuman(): global strawsNumber strawsNumber-=howMany return strawsNumber def humanLegalMove(): global howMany legalMove=False while not legalMove: print("It's your turn, ",player1) howMany=int(input("How many straws do you want to remove?(from 1 to 3) ")) if howMany>3 or howMany<1: print("Enter a number between 1 and 3.") else: legalMove=True while howMany>strawsNumber: print("The entered number is greater than a number of straws remained.") howMany=int(input("How many straws do you want to remove?")) return howMany def checkWinner(player): if strawsNumber==0: print(player," wins.") global gameover gameover=True return gameover def resetGameover(): global gameover gameover=False return gameover def game(): while gameover==False: print("It's ",player2,"turn. The number of straws left: ",removingStrawsComputer()) checkWinner(player1) if gameover==True: break humanLegalMove() print("The number of straws left: ",removingStrawsHuman()) checkWinner(player2) game() From mail at timgolden.me.uk Fri Apr 22 15:44:30 2016 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 22 Apr 2016 20:44:30 +0100 Subject: [Tutor] using a for loop in another method In-Reply-To: References: Message-ID: <571A7F1E.1010207@timgolden.me.uk> On 22/04/2016 17:08, Rene.Castillo wrote: > Hi, this is my first post on this mailing list- > > I wanted to ask about this type of execution in python, > > expected output- > reverse_words("This is an example!") # returns "sihT si na !elpmaxe" > > > below is my execution, followed by another persons execution, which i dont > completely understand. > > def reverse_words(strng): > strng = strng[::-1].split(' ') > strng.reverse() > return ' '.join(strng) > > > def reverse_words(s) > return ' '.join(s[::-1] for s in str.split(' ')) > > > > how can a for loop be called within another method like that- and possibly > what situations does this benefit > i don't even know how to google this sort of thing > any words are appreciated- It's tricky, isn't it? Once I give you the magic phrase, you'll find examples and explanations all over the place: list comprehension (strictly, the example you're showing is a "generator comprehension" but you'll probably get more hits for the slightly older "list comprehension"). TJG From alan.gauld at yahoo.co.uk Fri Apr 22 17:57:33 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 22 Apr 2016 22:57:33 +0100 Subject: [Tutor] The game of nim in python In-Reply-To: <1A3208EF9BAB154D89AC8A0E57B0DF8D155117C5@ALPMBAPA02.e2k.ad.ge.com> References: <1A3208EF9BAB154D89AC8A0E57B0DF8D155117C5@ALPMBAPA02.e2k.ad.ge.com> Message-ID: On 22/04/16 13:45, Henderson, Kevin (GE Aviation, US) wrote: > Python to Jython. > > Can you help me with a Jython code for the Nim game? > There shouldn't be much difference between a Jython or Python implementation - unless you are building a GUI of course! > Removing 1-4 sticks out of 13, last player who picks up the last stick wins Ive no idea how nim is played although I re,em,ber my math teacher talking about it as being the only practical use of binary outside computing... But what kind of help do you need? Does your code work? Is there an error (if so send us the full text)? Do you want a general code review? What exactly do you want from us? > player1=str(input("Enter your name. ")) > player2="Computer" > howMany=0 > gameover=False > strawsNumber=random.randint(10,20) > > if (strawsNumber%4)==1: > strawsNumber+=1 > > def removingStrawsComputer(): > removedNumber=random.randint(1,3) > global strawsNumber > while removedNumber>strawsNumber: > removedNumber=random.randint(1,3) > strawsNumber-=removedNumber > return strawsNumber > > def removingStrawsHuman(): > global strawsNumber > strawsNumber-=howMany > return strawsNumber > > def humanLegalMove(): > global howMany > legalMove=False > while not legalMove: > print("It's your turn, ",player1) > howMany=int(input("How many straws do you want to remove?(from 1 to 3) ")) > if howMany>3 or howMany<1: > print("Enter a number between 1 and 3.") > else: > legalMove=True > while howMany>strawsNumber: > print("The entered number is greater than a number of straws remained.") > howMany=int(input("How many straws do you want to remove?")) > return howMany > > def checkWinner(player): > if strawsNumber==0: > print(player," wins.") > global gameover > gameover=True > return gameover > > def resetGameover(): > global gameover > gameover=False > return gameover > > def game(): > while gameover==False: > print("It's ",player2,"turn. The number of straws left: ",removingStrawsComputer()) > checkWinner(player1) > if gameover==True: > break > humanLegalMove() > print("The number of straws left: ",removingStrawsHuman()) > checkWinner(player2) > game() -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From michael.selik at gmail.com Fri Apr 22 16:09:35 2016 From: michael.selik at gmail.com (Michael Selik) Date: Fri, 22 Apr 2016 20:09:35 +0000 Subject: [Tutor] The game of nim in python In-Reply-To: <1A3208EF9BAB154D89AC8A0E57B0DF8D155117C5@ALPMBAPA02.e2k.ad.ge.com> References: <1A3208EF9BAB154D89AC8A0E57B0DF8D155117C5@ALPMBAPA02.e2k.ad.ge.com> Message-ID: What's the problem you're trying to solve? Did you get an error? Here's a quick revision. There's probably a more elegant way, but this seems to work. #/usr/bin/env python from __future__ import print_function import random try: input = raw_input except NameError: pass # already using Python 3 player = input('Enter your name: ') straws = random.randint(10, 20) if straws % 4 == 1: straws += 1 while straws: print("It's the Computer's turn. {} straws left.".format(straws)) n = random.randint(1, min(3, straws)) straws -= n print("The Computer removes {} straws.".format(n)) if not straws: print("The Computer won!") break print("It's your turn, {}. There are {} straws left.".format(player, straws)) n = None while not n: print("You can remove between 1 and {} straws.".format(min(3, straws))) try: n = int(input('How many straws do you want to remove? ')) if n < 1 or n > min(3, straws): n = None except ValueError: pass straws -= n print("You removed {} straws.".format(n)) if not straws: print("You won!") break On Fri, Apr 22, 2016 at 1:58 PM Henderson, Kevin (GE Aviation, US) < KevinM.Henderson at ge.com> wrote: > Python to Jython. > > Can you help me with a Jython code for the Nim game? > > Removing 1-4 sticks out of 13, last player who picks up the last stick wins > > Player 1 vs player2(Computer) > > player1=str(input("Enter your name. ")) > player2="Computer" > howMany=0 > gameover=False > strawsNumber=random.randint(10,20) > > if (strawsNumber%4)==1: > strawsNumber+=1 > > def removingStrawsComputer(): > removedNumber=random.randint(1,3) > global strawsNumber > while removedNumber>strawsNumber: > removedNumber=random.randint(1,3) > strawsNumber-=removedNumber > return strawsNumber > > def removingStrawsHuman(): > global strawsNumber > strawsNumber-=howMany > return strawsNumber > > def humanLegalMove(): > global howMany > legalMove=False > while not legalMove: > print("It's your turn, ",player1) > howMany=int(input("How many straws do you want to remove?(from 1 > to 3) ")) > if howMany>3 or howMany<1: > print("Enter a number between 1 and 3.") > else: > legalMove=True > while howMany>strawsNumber: > print("The entered number is greater than a number of straws > remained.") > howMany=int(input("How many straws do you want to remove?")) > return howMany > > def checkWinner(player): > if strawsNumber==0: > print(player," wins.") > global gameover > gameover=True > return gameover > > def resetGameover(): > global gameover > gameover=False > return gameover > > def game(): > while gameover==False: > print("It's ",player2,"turn. The number of straws left: > ",removingStrawsComputer()) > checkWinner(player1) > if gameover==True: > break > humanLegalMove() > print("The number of straws left: ",removingStrawsHuman()) > checkWinner(player2) > game() > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From michael.selik at gmail.com Fri Apr 22 16:31:02 2016 From: michael.selik at gmail.com (Michael Selik) Date: Fri, 22 Apr 2016 20:31:02 +0000 Subject: [Tutor] using a for loop in another method In-Reply-To: References: Message-ID: On Fri, Apr 22, 2016 at 1:57 PM Rene.Castillo wrote: > expected output- > reverse_words("This is an example!") # returns "sihT si na !elpmaxe" > > def reverse_words(strng): > strng = strng[::-1].split(' ') > strng.reverse() > return ' '.join(strng) > Let's walk through each step that you wrote. First, I'd rather use the variable name ``s`` than ``strng``. It's just as readable in small snippets of code like this. ``s`` gets passed in. We'll go ahead and assume it's a str, or something str-like. There's no need to check the type. That's for more paranoid languages. s = s[::-1].split() This reverses the string via slicing, then splits on whitespace, assigning the resulting list back over the variable ``s``. If ``s`` (or previously, ``strng``) suggests that the variable refers to a str, we now have some confusion as it's referring to a list, not a str. s.reverse() In-place reversal of a list. When I see this line without paying attention, I think it's a bug. The str type does not have a reverse method! But of course, I was misled by the variable name and the code indeed works. ' '.join(s) Again, this looks like a bug, but since ``s`` is a list, it works just fine. Now let's look at your friend's code, which actually has a little bug in it. ' '.join( ... ) We already know what that does, joins a list of strings on a ' ' separator. s[::-1] for s in str.split(' ') Looking at the first bit, there's a ``s[::-1]`` so that must reverse a string. Then there's ``for s in ...`` and that looks like a regular for-loop, assigning to a variable ``s`` for each iteration. And finally, ``str.split(' ')`` is where we find the bug. They probably meant ``strng.split()`` and intended to keep the parameter named ``strng``. There's no need to pass any input to the split method, as it splits on whitespace by default. Tim Golden already mentioned that this technique is a comprehension. It is equivalent to writing like this: def reverse_words(sentence): reversals = [] for word in sentence.split(): reversals.append(word[::-1]) return ' '.join(reversals) Note how using more meaningful variable names avoids confusion. Instead of using names like "intgr" or "strng" you should probably name things after their meanings instead of their data types. > def reverse_words(s) > return ' '.join(s[::-1] for s in str.split(' ')) > > > > how can a for loop be called within another method like that- and possibly > what situations does this benefit > i don't even know how to google this sort of thing > any words are appreciated- > > > > R > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From dyoo at hashcollision.org Fri Apr 22 22:58:49 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 22 Apr 2016 19:58:49 -0700 Subject: [Tutor] The game of nim in python In-Reply-To: <1A3208EF9BAB154D89AC8A0E57B0DF8D155117C5@ALPMBAPA02.e2k.ad.ge.com> References: <1A3208EF9BAB154D89AC8A0E57B0DF8D155117C5@ALPMBAPA02.e2k.ad.ge.com> Message-ID: On Fri, Apr 22, 2016 at 5:45 AM, Henderson, Kevin (GE Aviation, US) wrote: > Python to Jython. > > Can you help me with a Jython code for the Nim game? If you can say more about what you're like help with, we can tailor advice toward what you want. I'll treat this as a quick-and-dirty design review. ... ok, I see a lot of globals. It might make sense to consider modifying the functions that take in and produce values. For example, your computer player: > def removingStrawsComputer(): > removedNumber=random.randint(1,3) > global strawsNumber > while removedNumber>strawsNumber: > removedNumber=random.randint(1,3) > strawsNumber-=removedNumber > return strawsNumber essentially depends on the initial strawsNumber, and returns an updated strawsNumber to represent how the computer is playing. Rather than have it work on the 'strawsNumber' global directly, you can pass in the value as an argument. ####################################### def removingStrawsComputer(strawsNumber): removedNumber=random.randint(1,3) while removedNumber>strawsNumber: removedNumber=random.randint(1,3) strawsNumber-=removedNumber return strawsNumber ####################################### How would this change affect the rest of the program? It would touch callers of removingStrawsComputer, and in that case, that's the main game() function. It would change: ########################################################## def game(): while gameover==False: print("It's ",player2,"turn. The number of straws left: ", removingStrawsComputer()) ... ########################################################## to: ########################################################## def game(): while gameover==False: currentStraws = removingStrawsComputer(currentStraws) print("It's ",player2,"turn. The number of straws left: ", currentStraws) ... ########################################################## I would argue that the revised version is better for readability because it's more clear that we're calling removingStrawsComputer so that we can change currentStraws. The other thing that caught my eye is related to game() too. This line: print("It's ",player2,"turn. The number of straws left: ", removingStrawsComputer()) Yes, we looked at this line earlier. :P I think this is too clever, believe it or not. I'd recommend breaking this out into two separate statements. currentStraws = removingStrawsComputer() print("It's ",player2,"turn. The number of straws left: ", currentStraws) The reason is because the original is calling removingStrawsComputer() for an essential side-effect, which is ok normally, except this is being done in the context of a print statement. That's the part that can be error-prone. Print statements are often added and removed to make things look nicer. I would think that commenting out a print statement would be mostly harmless, for example, but in this case, it's *crucial* that we don't in this situation, because it affects the state of the game. In general, when using print(), avoid putting in side-effecting things as arguments. It's one of those code smells that a programmer learns to avoid. From python.org at mjch.net Fri Apr 22 20:15:52 2016 From: python.org at mjch.net (Malcolm Herbert) Date: Sat, 23 Apr 2016 10:15:52 +1000 Subject: [Tutor] python equivalents for perl list operators? Message-ID: <20160423001551.GC13122@phobos.mjch.net> hey folks - I've been a long time perl programmer and only recently tried my hand a python, so it's probable that these questions are non-sensical in this context but for the moment I'm trying to stay afloat I've been dabbling a bit with some lists and trying to work out how best to abitrarily sort and filter these. Perl has a number of operators that help with this in map(), grep() and sort() as follows: @raw = (2, 1, 4, 3); @grepped = grep { \$_ >= 3 } @raw; # (4, 3) @mapped = map { \$_ + 1 } @raw; # (3, 2, 5, 4) @sorted = sort { \$a > \$b } @raw; # (1, 2, 3, 4) in this case: grep() will return all list items for which the code block returns true map() will return all list items as modified by the code block sort() will return a sorted list of items, using the code block to compare them (where \$a and \$b represent two items to be compared) so - I've been able to at least work out the map() case above with a list comprehension raw = [2, 1, 4, 3] mapped = [ x + 1 for x in raw] # [3, 2, 5, 4] and I know that .sorted() would do what I want in this limited example, but I'm after the ability to put abitrary code in here to determine sort order or test an item for filtering (because the items they're testing may be complex structures rather than these simple integers, for example) these seem so useful things to want to do that I'd imagine they're probably a basic part of the language, but so far I've not seen anything that might cover them with the exeption of map() as above - I am slowly trawling my way through Learning Python (5ed) so I might yet get to something related, I don't know does anyone have any pointers? ta Regards, Malcolm -- Malcolm Herbert mjch at mjch.net From alan.gauld at yahoo.co.uk Sat Apr 23 03:48:36 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 23 Apr 2016 08:48:36 +0100 Subject: [Tutor] python equivalents for perl list operators? In-Reply-To: <20160423001551.GC13122@phobos.mjch.net> References: <20160423001551.GC13122@phobos.mjch.net> Message-ID: On 23/04/16 01:15, Malcolm Herbert wrote: > @raw = (2, 1, 4, 3); > @grepped = grep { \$_ >= 3 } @raw; # (4, 3) grepped = [item for item in raw if item >= 3] > @mapped = map { \$_ + 1 } @raw; # (3, 2, 5, 4) mapped = [item +1 for item in raw] or mapped = map(lambda x: x+1, raw) > @sorted = sort { \$a > \$b } @raw; # (1, 2, 3, 4) raw.sort() # sorts in place _sorted = sorted(raw) You can add parameters to both functions to specify sort characteristics, for example: raw2 = [(1,'p'),(2,'e'),(3,'r'),(4,'l')] lexical = sorted(raw2,key=lambda t:t[1]) You can use the interpreter to find out some of this by using the help() function help([]) # help on all list methods help([].sort) # help on the sort method There are also some modules that might be of interest to you such as itertools and functools. You might also find the Functional Programming topic in my tutorial useful (see below). hth -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From martin at linux-ip.net Sat Apr 23 04:57:06 2016 From: martin at linux-ip.net (Martin A. Brown) Date: Sat, 23 Apr 2016 01:57:06 -0700 Subject: [Tutor] python equivalents for perl list operators? In-Reply-To: <20160423001551.GC13122@phobos.mjch.net> References: <20160423001551.GC13122@phobos.mjch.net> Message-ID: Greetings and welcome Malcolm, >hey folks - I've been a long time perl programmer and only recently >tried my hand a python, so it's probable that these questions are >non-sensical in this context but for the moment I'm trying to stay >afloat Although I wrote Python first, I spent years writing in both Python and Perl, so I may be able to offer a tip or two. OK, so on to your questions. I'll paste my examples from an interactive Python3 shell. I hope you have already found that you can simply run an interactive interpreter: \$ python3 Python 3.4.1 (default, May 23 2014, 17:48:28) [GCC] on linux Type "help", "copyright", "credits" or "license" for more information. >>> >I've been dabbling a bit with some lists and trying to work out how best >to abitrarily sort and filter these. Perl has a number of operators that >help with this in map(), grep() and sort() as follows: > > @raw = (2, 1, 4, 3); > @grepped = grep { \$_ >= 3 } @raw; # (4, 3) > @mapped = map { \$_ + 1 } @raw; # (3, 2, 5, 4) > @sorted = sort { \$a > \$b } @raw; # (1, 2, 3, 4) > >in this case: > >grep() will return all list items for which the code block returns true Use 'filter' in Python. https://docs.python.org/3/library/functions.html#filter Vaguely Perl-like invocation: >>> list(filter(lambda x: x >= 3, [2, 1, 4, 3])) [4, 3] Old-school Pythonic way: >>> def gt3(x): ... return x >= 3 >>> list(filter(gt3, [2, 1, 4, 3])) [4, 3] New-school Pythonic way: >>> [x for x in [2, 1, 4, 3] if x >= 3] [4, 3] [But, also, please see my readability remarks below on the immediately preceding example.] >map() will return all list items as modified by the code block Use 'map' in Python, too. https://docs.python.org/3/library/functions.html#map Vaguely Perl-like invocation: >>> list(map(lambda x: x + 1, [2, 1, 4, 3])) [3, 2, 5, 4] Old-school Pythonic way: >>> def plus1(x): ... return x + 1 >>> list(map(plus1, [2, 1, 4, 3])) [3, 2, 5, 4] New-school Pythonic way (which you already discovered): >>> [x+1 for x in [2, 1, 4, 3]] [3, 2, 5, 4] >sort() will return a sorted list of items, using the code block to >compare them (where \$a and \$b represent two items to be compared) Use 'sorted' in Python. https://docs.python.org/3/library/functions.html#sorted Or, sort a list in place with the method .sort(). https://docs.python.org/3/library/stdtypes.html#list.sort What's the difference, you ask? I'll generate a list of random integers and then show you: >>> import random >>> raw = [random.randint(0, 100) for _ in range(10)] >>> raw [91, 79, 4, 89, 17, 83, 89, 50, 74, 71] >>> new = sorted(raw) >>> new [4, 17, 50, 71, 74, 79, 83, 89, 89, 91] >>> raw [91, 79, 4, 89, 17, 83, 89, 50, 74, 71] >>> raw.sort() >>> raw [4, 17, 50, 71, 74, 79, 83, 89, 89, 91] You may have gotten accustomed to writing your own function (or a block) for each call to Perl's sort. This technique is far less common in Python. The notion of the Schwartzian transform in Perl is referred to be a more general name in Python-lands. It's called the Decorate-Sort-Undecorate (DSU) technique. Much more often, though, you will see a developer pass key= to the sort() method or the sorted() function. >so - I've been able to at least work out the map() case above with a >list comprehension > > raw = [2, 1, 4, 3] > mapped = [ x + 1 for x in raw] # [3, 2, 5, 4] Yes! Another way to do it. You are using something called a list comprehension. (You see I used it to generate random numbers.) This is a wonderful idiomatic technique to use in Python. I mentioned that I would remark about readability. When writing in Python, readability matters an awful lot to the majority of Python programmers. So, I refer again to my example: [x for x in [2, 1, 4, 3] if x >= 3] The 'if' condition is pretty far away from the action, and as such, I generally, don't like to use an 'if' condition like this in a more complex list comprehension. It takes me longer to figure out when I read it later. So, I would make this into two lines, or use a different approach entirely. l = [2, 1, 4, 3] [x for x in l if x >= 3] >and I know that .sorted() would do what I want in this limited >example, but I'm after the ability to put abitrary code in here to >determine sort order or test an item for filtering (because the >items they're testing may be complex structures rather than these >simple integers, for example) You definitely want to read this: https://docs.python.org/3/howto/sorting.html >these seem so useful things to want to do that I'd imagine they're >probably a basic part of the language, but so far I've not seen >anything that might cover them with the exeption of map() as above >- I am slowly trawling my way through Learning Python (5ed) so I >might yet get to something related, I don't know Python's sort() is pretty darned good. Additionally, there's plenty of flexibility with the key parameter. Here's an example. I'm going to create a dead-simple object using a module you probably haven't heard of before, but hopefully, this is enough like a dict() [a Perl hash) or an object (did you use the grafted-on OO in Perl?) that it'll make sense. Now, I'll omit the interactive shell prompts (for easier pasting). If I run this code to create a Pilot and store it in 'p' ... from collections import namedtuple Pilot = namedtuple('Pilot', ['surname', 'age', 'biplane']) p = Pilot('Vernon', 32, 'Pander') Then, p looks like this (if I were to print it): Pilot(surname='Vernon', age=32, biplane='Pander') So, now, I'll take a few of these Pilot()s and put them in a list and show you how you can sort based on any of the attributes of the Pilot: aces = list() aces.append(Pilot('Vernon', 32, 'Pander')) aces.append(Pilot('Ehringhaus', 41, 'Curtiss')) aces.append(Pilot('Wilkins', 28, 'Sopwith')) aces.append(Pilot('Tessler', 37, 'de Havilland')) Our flying aces are lined up! Which ones are wearing blue? aces.sort(key=attrgetter('surname')) Now the order would look like this: [Pilot(surname='Ehringhaus', age=41, biplane='Curtiss'), Pilot(surname='Tessler', age=37, biplane='de Havilland'), Pilot(surname='Vernon', age=32, biplane='Pander'), Pilot(surname='Wilkins', age=28, biplane='Sopwith')] But, that's no good... I really wanted to order them by plane: aces.sort(key=attrgetter('surname')) And now: [Pilot(surname='Ehringhaus', age=41, biplane='Curtiss'), Pilot(surname='Vernon', age=32, biplane='Pander'), Pilot(surname='Wilkins', age=28, biplane='Sopwith'), Pilot(surname='Tessler', age=37, biplane='de Havilland')] But, when choosing who gets to drive off the airfield first, it's always done by age: aces.sort(key=attrgetter('age'), reverse=True) So, the story ends: [Pilot(surname='Ehringhaus', age=41, biplane='Curtiss'), Pilot(surname='Tessler', age=37, biplane='de Havilland'), Pilot(surname='Vernon', age=32, biplane='Pander'), Pilot(surname='Wilkins', age=28, biplane='Sopwith')] I will make one other note about thinking in Perl vs. thinking in Python. (This is something that I found strange and occasionally quite convenient in Perl.) Perl will flatten your lists when you pass them into functions. If you pass two lists into a function. &some_func(@a, @b) In some_func, there's just a list of arguments, and all distinction between the two lists is lost. That's why I saw (and wrote) much more often: &some_func(\@a, \@b) In Python, the list is not flattened (thank goodness). It's just like any other variable. It may contain any type, basic, derived, class, function, whatever. I do not know if other people have found this list behaviour surprising when writing in both languages, but I do like the Python approach better on the list handling. The standard library contains a wider assortment of tools than the Perl standard library, so when you are looking for a toolkit to handle something, have a peek in the standard library list of modules; it may already be there. https://docs.python.org/3/py-modindex.html If not, check out PyPI (the Python equivalent of CPAN): https://pypi.python.org/PyPI Best of luck, Malcom, and welcome to the world of Python where everything is a first class object. -Martin import pprint from operator import attrgetter from collections import namedtuple Pilot = namedtuple('Pilot', ['surname', 'age', 'biplane']) aces = list() aces.append(Pilot('Vernon', 32, 'Pander')) aces.append(Pilot('Ehringhaus', 41, 'Curtiss')) aces.append(Pilot('Wilkins', 28, 'Sopwith')) aces.append(Pilot('Tessler', 37, 'de Havilland')) l = sorted(aces, key=attrgetter('surname')) pprint.pprint(l) l = sorted(aces, key=attrgetter('age')) pprint.pprint(l) l = sorted(aces, key=attrgetter('biplane')) pprint.pprint(l) -- Martin A. Brown http://linux-ip.net/ From steve at pearwood.info Sat Apr 23 05:37:48 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 23 Apr 2016 19:37:48 +1000 Subject: [Tutor] python equivalents for perl list operators? In-Reply-To: <20160423001551.GC13122@phobos.mjch.net> References: <20160423001551.GC13122@phobos.mjch.net> Message-ID: <20160423093748.GD13497@ando.pearwood.info> Hi Malcolm, and welcome! On Sat, Apr 23, 2016 at 10:15:52AM +1000, Malcolm Herbert wrote: > I've been dabbling a bit with some lists and trying to work out how best > to abitrarily sort and filter these. Perl has a number of operators that > help with this in map(), grep() and sort() as follows: > > @raw = (2, 1, 4, 3); > @grepped = grep { \$_ >= 3 } @raw; # (4, 3) > @mapped = map { \$_ + 1 } @raw; # (3, 2, 5, 4) > @sorted = sort { \$a > \$b } @raw; # (1, 2, 3, 4) > > in this case: > > grep() will return all list items for which the code block returns true > > map() will return all list items as modified by the code block > > sort() will return a sorted list of items, using the code block to > compare them (where \$a and \$b represent two items to be compared) Thank you for explaining what the Perl code does! Python doesn't have a compact short-cut for arbitrarily complex code blocks. If the code can be written as a single expression, you can embed it in a list comprehension, or use a "lambda" short-cut for creating a function. But for code blocks with multiple statements, you will need to predefine a function first. The "grep" example can be done using either a list comprehension or the filter() function. Here is a version using a pre-defined function: def big_enough(num): return num >= 3 raw = (2, 1, 4, 3) grepped = filter(big_enough, raw) We can skip the "big_enough" function and write it in place using a lambda: grepped = filter(lambda num: num >= 3, raw) (The name "lambda" comes from theoretical computer science -- google for "lambda calculus" if you care. But in Python, it is syntactic sugar for creating a function on the fly, as an expression, rather than as a statement. So unlike "def", lambda can be embedded in other expressions, but it is limited to a body consisting of a single expression.) Here's a version using a list comprehension: grepped = [num for num in raw if num >= 3] List comprehensions are syntactic sugar for for-loops, based on "set builder notation" from mathematics. You can read the above as more or less equivalent to: grepped = [] # Empty list. for num in raw: if num >= 3: grepped.append(num) except more compact. The map example: > @mapped = map { \$_ + 1 } @raw; # (3, 2, 5, 4) is similar in Python. You can use the map() function, or a list comprehension: mapped = map(lambda n: n+1, raw) mapped = [n+1 for n in raw] The sort example: > @sorted = sort { \$a > \$b } @raw; # (1, 2, 3, 4) can be done two ways, either in-place, or copying the list into a new list. By default, sort goes from smallest to largest: # in-place raw.sort() # copy to a new list, then sort newlist = sorted(raw) Both the sort method and the sorted function allow you to specify how the sort is done. In Python 2, you have a choice of using a comparison function (but beware, that tends to be slow for large lists) or a key function. In Python 3, you can only use a key function. The comparison function specifies a function which takes two elements, and then returns -1, 0 or 1 depending on whether the first is less than, equal to, or greater than the second. So sorting odd and even numbers separately: def odds_evens(a, b): if a%2 == b%2 == 0: # Both even, sort smaller to larger. return cmp(a, b) elif a%2 == b%2 == 1: # Both odd, sort larger to smaller. return -cmp(a, b) else: # Odd numbers first. if a%2 == 1: # a is odd, so it comes first. return -1 # Otherwise b is odd, so it comes first. return 1 And here is an example of how to use it: py> import random py> numbers = range(10) py> random.shuffle(numbers) py> print numbers [1, 0, 2, 9, 7, 4, 5, 6, 8, 3] py> print sorted(numbers, odds_evens) [9, 7, 5, 3, 1, 0, 2, 4, 6, 8] Alternatively, you can specify a key function, using a keyword argument. This implements the DSU (decorate-sort-undecorate) idiom that you might be familiar with under the name "Schwartzian transform". Here's how I might sort a bunch of strings by length: py> strings = ['aaa', 'bbbb', 'c', 'dd', 'eeeeee', 'fffff'] py> print sorted(strings, key=len) ['c', 'dd', 'aaa', 'bbbb', 'fffff', 'eeeeee'] Notice that I can just use the built-in len() function as the key= argument. [...] > but I'm after the ability to put abitrary code in here to determine > sort order or test an item for filtering (because the items they're > testing may be complex structures rather than these simple integers, for > example) As I mentioned above, you can't embed arbitrarily complex multi-statement code blocks in function calls. If your test is complex enough that it needs more than one expression, you have to put it in a function first, like the odds_evens example above. -- Steve From magyar1886 at gmail.com Mon Apr 25 12:24:46 2016 From: magyar1886 at gmail.com (Marco Soldavini) Date: Mon, 25 Apr 2016 18:24:46 +0200 Subject: [Tutor] XML and ElementTree Message-ID: I've a few questions about parsing XML. I wrote some code that works but I want to know which are the most intelligent data structures to parse data to Consider that my XML file is something like the following: 1 XXX .... .... .... So root element can have station child element from 1 to n Each station element have unique child elements apart from groups which may have more group child element each with a few tags Now I want to parse this xml file and get the tag values into variables in python I could have 1 station element or 2 or 3 I could append all data in a long list, but is this good? Could it be better to build a dictionary for each station element and then build a list of dictionary Which method you suggest to find data and use it after parsing it? If later in the program I want to access a variable value I want to do it with the xml tag name and not with an index like Settings[10] for example but something like Settings['tag'].... But what if I have more than one structure like station which has the same keys? Following is part of my code for now. Thanks! marco try: import xml.etree.cElementTree as ET except ImportError: import xml.etree.ElementTree as ET # Settings XML File Parsing tree = ET.parse('settingstest.xml') root = tree.getroot() stations = len(root) print "Found ",stations, " stations configured in settings file" Settings = [] for station in root: StationId = station.find('StationId') Settings.append(StationId) ..... From alan.gauld at yahoo.co.uk Mon Apr 25 20:05:38 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 26 Apr 2016 01:05:38 +0100 Subject: [Tutor] XML and ElementTree In-Reply-To: References: Message-ID: On 25/04/16 17:24, Marco Soldavini wrote: > I've a few questions about parsing XML. I wrote some code that works > but I want to know which are the most intelligent data structures to > parse data to Answer: The ones that suit what you want to do with it. But you haven't told us what you plan on using it for so we can't tell you what is suitable. > > > 1 > XXX > > > .... > > > .... > > > > > .... > > > > So root element can have station child element from 1 to n > Each station element have unique child elements apart from groups > which may have more group child element each with a few tags > > Now I want to parse this xml file and get the tag values into > variables in python > I could have 1 station element or 2 or 3 So you could have a list or a dictionary of Stations. Each station might be simple values, or tuples, or dictionaries or an instance of a Station class. > I could append all data in a long list, but is this good? It all depends on what you want to do. If you just want to process all the stations sequentially then yes, a long list is good. (Unless its too long in which case you may be better with a database or a flat file.) > If later in the program I want to access a variable value I want to do > it with the xml tag name and not with an index like Settings[10] for > example but something like Settings['tag'].... That suggests a dictionary or class would be best. (Although a named tuple or database may also be appropriate.) > But what if I have more than one structure like station which has the same keys? Figuring out object identity is always tricky when the data is similar. a Database solution offers row ids to disambiguate similar entries. A class based solution has an id (usually the memory address), a list has its index. Its really up to you to determine the best option based on your needs. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From colbychristensen at hotmail.com Tue Apr 26 00:30:38 2016 From: colbychristensen at hotmail.com (Colby Christensen) Date: Tue, 26 Apr 2016 00:30:38 -0400 Subject: [Tutor] Using a dictionary to map functions Message-ID: I am a novice self taught programmer learning with Python. I am working on a program to calculate coordinate geometry. The input file is a list of commands. A number is assigned to each command and followed by various inputs required to make the calculation. The input has the following format: 5 201 1496.0423 1234.5678 (this command stores the last two numbers as the coordinates for point 201; 5 = store point command) comments lines begin with # Each command can take 3 to 7 arguments depending on the calculation.? Currently I am building each command as a separate module that I can import into the main program. My main program reads the input file and separates the commands from blank and comment lines. As it reads the input file, it splits the command and appends it to a list. I'm thinking of having a dictionary that maps the commands/functions to each number. My conundrum is how to use the dictionary mapping to call the functions and pass the arguments. In the case below, I would pass the arguments pt_table and line. In the function store_point, I break the list, line, into components to make the calculation. By passing the entire line, I can validate the command in the corresponding function.? import re from store_point import store_point try: ? ? infile = open(raw_input("Enter input file name; name.txt:"),'r') except: ? ? print "Invalid filename" ? ? exit() templist = [] pt_table = {} cmd_table = {5:"store_point", 19: "line_line_int"} count = 0 for line in infile: ? ? #print line ? ? line = line.rstrip() ? ? if re.search('^[0-9]+', line): ? ? ? ? a = line.split() ? ? ? ? templist.append(a) for line in templist: ? ? #use dictionary to call and pass arguments to function As a novice programmer, I am also open to suggestions to do this more effectively.? Thank you Colby From santanu01 at gmail.com Tue Apr 26 03:01:28 2016 From: santanu01 at gmail.com (Santanu Jena) Date: Tue, 26 Apr 2016 12:31:28 +0530 Subject: [Tutor] def __init__(self): Message-ID: Hi, Pls let me why " def __init__(self): " declaration required, what's the use of this one.Pls explain me in details. Thanks in advance. From alan.gauld at yahoo.co.uk Tue Apr 26 04:42:37 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 26 Apr 2016 09:42:37 +0100 Subject: [Tutor] Using a dictionary to map functions In-Reply-To: References: Message-ID: On 26/04/16 05:30, Colby Christensen wrote: > import re > from store_point import store_point > > try: > infile = open(raw_input("Enter input file name; name.txt:"),'r') > except: > print "Invalid filename" > exit() > > templist = [] > pt_table = {} > cmd_table = {5:"store_point", 19: "line_line_int"} Almost... You need to store the actual function name not a string: cmd_table = { 5 : store_point, 19 : line_line_int # etc... } Notice, no quotes. > for line in infile: > #print line > line = line.rstrip() > if re.search('^[0-9]+', line): > a = line.split() > templist.append(a) > > for line in templist: > #use dictionary to call and pass arguments to function HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Tue Apr 26 04:55:17 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 26 Apr 2016 09:55:17 +0100 Subject: [Tutor] def __init__(self): In-Reply-To: References: Message-ID: On 26/04/16 08:01, Santanu Jena wrote: > Hi, > > Pls let me why > " > def __init__(self): > > " > declaration required, what's the use of this one.Pls explain me in > details. It is used to initialise object instances. For example if you define a class Rectangle that has a length and width and a method to calculate the area:. class Rectangle: length = 0 # defaults in case we forget to add them width = 0 def area(self): return self.length * self.width That works after a fashion: r = Rectangle() r.length = 20 r.width = 10 print r.area() # prints 200 But it is clumsy. It would be better to define the length and width as part of the object creation. To do that we add an __init__() method: class Rectangle: def __init__(self, len, width): self.length = len self.width = width def area(self): return self.length * self.width r = Rectangle(20,10) print r.area() # prints 200 So the init method allows us to initialise the values of the data attributes of our objects at the time of creation. (You can also call other methods inside init() of course but that is less common) You can read more about __init__() in my tutorial at the end of the Raw Materials topic and again in the OOP topic. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Tue Apr 26 04:37:11 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 26 Apr 2016 09:37:11 +0100 Subject: [Tutor] XML and ElementTree In-Reply-To: References: Message-ID: <571F28B7.5030305@yahoo.co.uk> Forwarding to tutor list. Please always use "Reply All" or "Reply List" when responding to the tutor list. On 26/04/16 09:24, Marco Soldavini wrote: > On Tue, Apr 26, 2016 at 2:05 AM, Alan Gauld via Tutor wrote: >> On 25/04/16 17:24, Marco Soldavini wrote: >>> I've a few questions about parsing XML. I wrote some code that works >>> but I want to know which are the most intelligent data structures to >>> parse data to >> Answer: The ones that suit what you want to do with it. >> But you haven't told us what you plan on using it for so >> we can't tell you what is suitable. >> > Let's say I would use the tag values as argument of function call in > the subsequent part of the program. > > For example one tag will contain a server address. In the program I'll > have a function which will use this address to perform a connection. > -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From oliver at bestwalter.de Tue Apr 26 04:44:48 2016 From: oliver at bestwalter.de (Oliver Bestwalter) Date: Tue, 26 Apr 2016 08:44:48 +0000 Subject: [Tutor] def __init__(self): In-Reply-To: References: Message-ID: Hi Santanu, without knowing from which level of understanding you are asking, it is hard to say what we should answer here, so let me ask a few questions: Do you understand the concept of classes already? Maybe from other programming languages, or are you a complete beginner? If you are a beginner you might be moving a bit fast and not actually not need to know about the internal mechanics of classes. Did you read the documentation about classes already? https://docs.python.org/3.5/tutorial/classes.html Did you read the documentation about the __init__ method already? https://docs.python.org/3.5/reference/datamodel.html#object.__init__ cheers Oliver On Tue, 26 Apr 2016 at 10:29 Santanu Jena wrote: > Hi, > > Pls let me why > " > def __init__(self): > > " > declaration required, what's the use of this one.Pls explain me in > details. > > Thanks in advance. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From __peter__ at web.de Tue Apr 26 08:13:56 2016 From: __peter__ at web.de (Peter Otten) Date: Tue, 26 Apr 2016 14:13:56 +0200 Subject: [Tutor] Using a dictionary to map functions References: Message-ID: Colby Christensen wrote: > templist = [] > pt_table = {} > cmd_table = {5:"store_point", 19: "line_line_int"} As Alan says, the values should be functions rather than function names. You could use string keys to save both the re.search() check and the conversion to integer. > count = 0 > > for line in infile: > #print line > line = line.rstrip() > if re.search('^[0-9]+', line): > a = line.split() > templist.append(a) > > for line in templist: > #use dictionary to call and pass arguments to function You could put parsing and evaluation into the same loop, and avoid the temporary list: cmd_table = {"5": store_point, ...} for line in infile: args = line.split() cmd = args.pop(0) # remove the first item from args if cmd in cmd_table: func = cmd_table[cmd] func(*args) # see below else: # optional, but may help with debugging print("Command {!r} not recognized. " "Skipping line {!r}.".format(cmd, line), file=sys.stderr) Given a list 'args' with N items the expression func(*args) is equivalent to func(args[0], args[1], ..., args[N-1]) e. g. foo = ["one", "two"] bar(*foo) passes the same arguments as bar("one", "two") From steve at pearwood.info Tue Apr 26 08:17:53 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 26 Apr 2016 22:17:53 +1000 Subject: [Tutor] Using a dictionary to map functions In-Reply-To: References: Message-ID: <20160426121751.GJ13497@ando.pearwood.info> Hi Colby, and welcome! On Tue, Apr 26, 2016 at 12:30:38AM -0400, Colby Christensen wrote: > try: > ? ? infile = open(raw_input("Enter input file name; name.txt:"),'r') > except: > ? ? print "Invalid filename" > ? ? exit() I'm afraid that code is misleading: your error message lies. It may not be an "invalid filename". It could be any of the following: - an invalid file name (a file name prohibited by the operating system); - a valid file name that just doesn't exist; - a valid file name that you don't have permission to access; - a valid file name that you can access, but a disk error occurred; - a valid file name on a network drive, but a network error occurred; and probably more. There are few things more frustrating than dealing with programs that lie to you: "What do you mean, invalid filename? The file is right there, I can see it! How can this stupid program not find it? I've tried a dozen times, double and triple checked that the file name is correct, and it still says the file is invalid." Because the real error is *permission denied*, not invalid file name. Python spends a lot of effort to give detailed and useful error messages when an error occurs. For example, if you try to open a file that doesn't exist, Python reports: IOError: [Errno 2] No such file or directory and tells you the name of the file that you tried to open. If you don't have permission to access it, it reports: IOError: [Errno 13] Permission denied and again reports exactly what went wrong. Python provides you with a detailed error message telling you exactly what went wrong, and you throw that away, replacing it with a generic message which will be wrong more often than right. Please don't do that -- trust me, you will come to regret it. In this case, the right way to deal with errors opening the file is... not to deal with them at all. Instead of this: try: infile = open(raw_input("Enter input file name; name.txt:"),'r') except: ? ? print "Invalid filename" ? ? exit() just write this: infile = open(raw_input("Enter input file name; name.txt:"),'r') (There are alternatives that are even better, but you probably haven't learned about them yet.) -- Steve From lwaters at flinthill.org Tue Apr 26 10:55:24 2016 From: lwaters at flinthill.org (Lisa Hasler Waters) Date: Tue, 26 Apr 2016 10:55:24 -0400 Subject: [Tutor] Revised question-Make an object disappear Message-ID: Dear Tutors, I have a student who is creating a game in TKinter. He wants the ball (object) to disappear when it hits when it hits the wall. He continues to get a syntax error message when trying to print the coordinates (he was printing the coordinates because he wanted to use its output to use again as inputs). He also wants to define the x-coordinates. He's running OSX 10.5, Python 3.5.1. I am pasting his code and the syntax error. Any assistance would be appreciated: from tkinter import * >>> import random >>> import time >>> tk = Tk() >>> tk.title("Game") '' >>> tk.resizable(0, 0) '' >>> tk.wm_attributes("-topmost", 1) '' >>> canvas = Canvas(tk, width=1400, height=835, bd=0, highlightthickness=0) >>> canvas.pack() >>> tk.update() >>> class dot: def __init__(self, canvas, color): self.canvas = canvas canvas.create_oval(10, 10, 25, 25, fill='Blue', tags='dot1') >>> this = dot(canvas, 'blue') >>> print canvas.coords('dot1') SyntaxError: invalid syntax >>> print canvas.coords('dot1', x, y) SyntaxError: invalid syntax >>> print Canvas.coords('dot1', x, y) SyntaxError: invalid syntax >>> print canvas.coords('dot1', x, y) SyntaxError: invalid syntax >>> def ball(n, x, y): canvas.move(n, x, y) >>> print coords('dot1', x, y) SyntaxError: invalid syntax >>> print canvas.coords('dot1', x, y) SyntaxError: invalid syntax >>> Canvas(master=None) >>> print canvas.coords('dot1', x, y) SyntaxError: invalid syntax >>> print canvas.coords('dot1') SyntaxError: invalid syntax >>> ================ RESTART: /Users/BScherer/Desktop/MazeTest.py ================ Traceback (most recent call last): File "/Users/BScherer/Desktop/MazeTest.py", line 16, in restart() File "/Users/BScherer/Desktop/MazeTest.py", line 14, in restart if canvas.coords('dot1', x >= 500, y >= 500): NameError: name 'x' is not defined >>> ================ RESTART: /Users/BScherer/Desktop/MazeTest.py ================ >>> ================ RESTART: /Users/BScherer/Desktop/MazeTest.py ================ Traceback (most recent call last): File "/Users/BScherer/Desktop/MazeTest.py", line 17, in restart() File "/Users/BScherer/Desktop/MazeTest.py", line 14, in restart if canvas.coords('dot1', x > 500, y > 500): NameError: name 'x' is not defined >>> ================ RESTART: /Users/BScherer/Desktop/MazeTest.py ================ >>> ================ RESTART: /Users/BScherer/Desktop/MazeTest.py ================ Traceback (most recent call last): File "/Users/BScherer/Desktop/MazeTest.py", line 17, in restart() File "/Users/BScherer/Desktop/MazeTest.py", line 14, in restart if canvas.coords('dot1', x > 500, y > 500): NameError: name 'x' is not defined >>> ================ RESTART: /Users/BScherer/Desktop/MazeTest.py ================ Traceback (most recent call last): File "/Users/BScherer/Desktop/MazeTest.py", line 17, in restart() File "/Users/BScherer/Desktop/MazeTest.py", line 14, in restart if canvas.coords('dot1', x, y) == ('dot1', x >= 300, y>= 300): NameError: name 'x' is not defined >>> ================ RESTART: /Users/BScherer/Desktop/MazeTest.py ================ Traceback (most recent call last): File "/Users/BScherer/Desktop/MazeTest.py", line 17, in restart() File "/Users/BScherer/Desktop/MazeTest.py", line 14, in restart while canvas.coords('dot1', x, y) == ('dot1', x >= 300, y>= 300): NameError: name 'x' is not defined >>> ================ RESTART: /Users/BScherer/Desktop/MazeTest.py ================ Traceback (most recent call last): File "/Users/BScherer/Desktop/MazeTest.py", line 17, in restart(x, y) NameError: name 'x' is not defined >>> ================ RESTART: /Users/BScherer/Desktop/MazeTest.py ================ >>> ================ RESTART: /Users/BScherer/Desktop/MazeTest.py ================ >>> ================ RESTART: /Users/BScherer/Desktop/MazeTest.py ================ Traceback (most recent call last): File "/Users/BScherer/Desktop/MazeTest.py", line 21, in restart2() File "/Users/BScherer/Desktop/MazeTest.py", line 18, in restart2 if restart(x, y) == restart(x > 500, y > 500): NameError: name 'x' is not defined >>> Thanks for any help you can give! -- Lisa Waters, PhD Technology Integration Flint Hill School From steve at pearwood.info Tue Apr 26 11:22:15 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 27 Apr 2016 01:22:15 +1000 Subject: [Tutor] Revised question-Make an object disappear In-Reply-To: References: Message-ID: <20160426152215.GK13497@ando.pearwood.info> On Tue, Apr 26, 2016 at 10:55:24AM -0400, Lisa Hasler Waters wrote: > Dear Tutors, > > I have a student who is creating a game in TKinter. He wants the ball > (object) to disappear when it hits when it hits the wall. He continues to > get a syntax error message when trying to print the coordinates (he was > printing the coordinates because he wanted to use its output to use again > as inputs). He also wants to define the x-coordinates. > > He's running OSX 10.5, Python 3.5.1. Python 3 no longer treats print as a special statement. It is now an ordinary function, like len(), so you need parentheses (round brackets). > >>> print canvas.coords('dot1') > SyntaxError: invalid syntax Change that to print(canvas.coords('dot1')) and it should work. > ================ RESTART: /Users/BScherer/Desktop/MazeTest.py > ================ > Traceback (most recent call last): > File "/Users/BScherer/Desktop/MazeTest.py", line 16, in > restart() > File "/Users/BScherer/Desktop/MazeTest.py", line 14, in restart > if canvas.coords('dot1', x >= 500, y >= 500): > NameError: name 'x' is not defined It is hard to say what is happening here. The error is clear: the name "x" is not defined, but I'm not sure why it is not defined (apart from the obvious "the student hasn't defined it yet") or where it needs to be defined in order to work in the restart() function. -- Steve From __peter__ at web.de Tue Apr 26 11:39:34 2016 From: __peter__ at web.de (Peter Otten) Date: Tue, 26 Apr 2016 17:39:34 +0200 Subject: [Tutor] Revised question-Make an object disappear References: Message-ID: Lisa Hasler Waters wrote: > Dear Tutors, > > I have a student who is creating a game in TKinter. He wants the ball > (object) to disappear when it hits when it hits the wall. He continues to > get a syntax error message when trying to print the coordinates (he was > printing the coordinates because he wanted to use its output to use again > as inputs). He also wants to define the x-coordinates. Having Python newbie questions channelled by someone who himself doesn't know the language makes meaningful communication a bit harder. Perhaps you can convince your student and/or yourself to let the student ask directly. We bite, but are careful to avoid permanent marks... > He's running OSX 10.5, Python 3.5.1. > > I am pasting his code and the syntax error. Any assistance would be > appreciated: > >>>> print canvas.coords('dot1') The above is Python 2.x syntax. In Python 3 print is a function -- you need parentheses around its arguments: print(canvas.coord("dot1")) > if canvas.coords('dot1', x > 500, y > 500): > NameError: name 'x' is not defined Here x and y are part of expressions passed as arguments. As no variable called x exists Python fails at runtime. What you want is probably the bounding box which is returned by the coords method as a list of four floats. dot_bbox = canvas.coords("dot1") The basic way to extract values from a list is x = dot_bbox[0] # left coord of the bounding box y = dot_bbox[1] # top coord ... (You can extract right and bottom in the same way) Now you have variables x and y and can perform tests like if x > 500 or y > 500: ... # whatever From colbychristensen at hotmail.com Tue Apr 26 10:44:10 2016 From: colbychristensen at hotmail.com (Colby Christensen) Date: Tue, 26 Apr 2016 10:44:10 -0400 Subject: [Tutor] Using a dictionary to map functions In-Reply-To: References: , Message-ID: Thank you! This is what I was hoping to accomplish. > To: tutor at python.org > From: __peter__ at web.de > Date: Tue, 26 Apr 2016 14:13:56 +0200 > Subject: Re: [Tutor] Using a dictionary to map functions > > Colby Christensen wrote: > > > templist = [] > > pt_table = {} > > cmd_table = {5:"store_point", 19: "line_line_int"} > > As Alan says, the values should be functions rather than function names. > You could use string keys to save both the re.search() check and the > conversion to integer. > > > count = 0 > > > > for line in infile: > > #print line > > line = line.rstrip() > > if re.search('^[0-9]+', line): > > a = line.split() > > templist.append(a) > > > > for line in templist: > > #use dictionary to call and pass arguments to function > > You could put parsing and evaluation into the same loop, and avoid the > temporary list: > > cmd_table = {"5": store_point, ...} > for line in infile: > args = line.split() > cmd = args.pop(0) # remove the first item from args > if cmd in cmd_table: > func = cmd_table[cmd] > func(*args) # see below > else: > # optional, but may help with debugging > print("Command {!r} not recognized. " > "Skipping line {!r}.".format(cmd, line), file=sys.stderr) > > > Given a list 'args' with N items the expression > > func(*args) > > is equivalent to > > func(args[0], args[1], ..., args[N-1]) > > e. g. > > foo = ["one", "two"] > bar(*foo) > > passes the same arguments as > > bar("one", "two") > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From colbychristensen at hotmail.com Tue Apr 26 10:44:54 2016 From: colbychristensen at hotmail.com (Colby Christensen) Date: Tue, 26 Apr 2016 10:44:54 -0400 Subject: [Tutor] Using a dictionary to map functions In-Reply-To: <20160426121751.GJ13497@ando.pearwood.info> References: , <20160426121751.GJ13497@ando.pearwood.info> Message-ID: Thank you for your input. You have given me some more to consider. > Date: Tue, 26 Apr 2016 22:17:53 +1000 > From: steve at pearwood.info > To: tutor at python.org > Subject: Re: [Tutor] Using a dictionary to map functions > > Hi Colby, and welcome! > > On Tue, Apr 26, 2016 at 12:30:38AM -0400, Colby Christensen wrote: > > > try: > > infile = open(raw_input("Enter input file name; name.txt:"),'r') > > except: > > print "Invalid filename" > > exit() > > I'm afraid that code is misleading: your error message lies. > > It may not be an "invalid filename". It could be any of the following: > > - an invalid file name (a file name prohibited by the operating system); > - a valid file name that just doesn't exist; > - a valid file name that you don't have permission to access; > - a valid file name that you can access, but a disk error occurred; > - a valid file name on a network drive, but a network error occurred; > > and probably more. There are few things more frustrating than dealing > with programs that lie to you: > > "What do you mean, invalid filename? The file is right there, I > can see it! How can this stupid program not find it? I've tried > a dozen times, double and triple checked that the file name is > correct, and it still says the file is invalid." > > Because the real error is *permission denied*, not invalid file name. > > Python spends a lot of effort to give detailed and useful error messages > when an error occurs. For example, if you try to open a file that > doesn't exist, Python reports: > > IOError: [Errno 2] No such file or directory > > and tells you the name of the file that you tried to open. If you don't > have permission to access it, it reports: > > IOError: [Errno 13] Permission denied > > and again reports exactly what went wrong. > > Python provides you with a detailed error message telling you exactly > what went wrong, and you throw that away, replacing it with a generic > message which will be wrong more often than right. Please don't do that > -- trust me, you will come to regret it. > > In this case, the right way to deal with errors opening the file is... > not to deal with them at all. Instead of this: > > try: > infile = open(raw_input("Enter input file name; name.txt:"),'r') > except: > print "Invalid filename" > exit() > > just write this: > > infile = open(raw_input("Enter input file name; name.txt:"),'r') > > (There are alternatives that are even better, but you probably haven't > learned about them yet.) > > > > -- > Steve > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From murarkakanika at gmail.com Tue Apr 26 09:47:19 2016 From: murarkakanika at gmail.com (Kanika Murarka) Date: Tue, 26 Apr 2016 19:17:19 +0530 Subject: [Tutor] Detect the folder of a file Message-ID: Hi, I want to detect whether a 'file1.py' belongs to virtual environment folder( generally 'venv') or not ( considering different people may have different names for virtual environment folder.). I am able to detect it on my machine, but how to make it generalized. I am not getting anything on Internet. :( Thank You From santanu01 at gmail.com Tue Apr 26 05:32:04 2016 From: santanu01 at gmail.com (Santanu Jena) Date: Tue, 26 Apr 2016 15:02:04 +0530 Subject: [Tutor] def __init__(self): In-Reply-To: References: Message-ID: Hi Oliver. I have idea regarding " __init__" method/ class.but still I have confusion on "def __init__(self): " Please share your under standing. Thanks & Regards, San On Tue, Apr 26, 2016 at 2:14 PM, Oliver Bestwalter wrote: > Hi Santanu, > > without knowing from which level of understanding you are asking, it is > hard to say what we should answer here, so let me ask a few questions: > > Do you understand the concept of classes already? Maybe from other > programming languages, or are you a complete beginner? If you are a > beginner you might be moving a bit fast and not actually not need to know > about the internal mechanics of classes. > > Did you read the documentation about classes already? > https://docs.python.org/3.5/tutorial/classes.html > > Did you read the documentation about the __init__ method already? > https://docs.python.org/3.5/reference/datamodel.html#object.__init__ > > cheers > Oliver > > On Tue, 26 Apr 2016 at 10:29 Santanu Jena wrote: > >> Hi, >> >> Pls let me why >> " >> def __init__(self): >> >> " >> declaration required, what's the use of this one.Pls explain me in >> details. >> >> Thanks in advance. >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> > From dyoo at hashcollision.org Tue Apr 26 15:27:23 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 26 Apr 2016 12:27:23 -0700 Subject: [Tutor] Detect the folder of a file In-Reply-To: References: Message-ID: On Tue, Apr 26, 2016 at 6:47 AM, Kanika Murarka wrote: > Hi, > I want to detect whether a 'file1.py' belongs to virtual environment > folder( generally 'venv') or not ( considering different people may have > different names for virtual environment folder.). I think we need more information on what a "virtual environment folder" is. I do not know what that term means. From dyoo at hashcollision.org Tue Apr 26 15:34:50 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 26 Apr 2016 12:34:50 -0700 Subject: [Tutor] def __init__(self): In-Reply-To: References: Message-ID: On Tue, Apr 26, 2016 at 2:32 AM, Santanu Jena wrote: > Hi Oliver. > I have idea regarding " __init__" method/ class.but still I have confusion > on "def __init__(self): " Please share your under standing. A big point of an entry point, conceptually, is to establish properties that we'd like to hold. Without such entry points, we don't have any real knowledge on what the shape of our data is at any given point, and our code becomes more complicated because we have to deal with the state of our ignorance. One question we might have is the following: Have we already prepared the program's data to something we expect? Initialization is a particular entry point that guarantees that the only values we get of a particular type are prepared in a certain way. In Python, classes provide an __init__() as an initialization entry point. Without initialization, the rest of our program has this persistent burden of needing to account for what the shape of our data is or isn't. It ends up being a big mosquito of an itch, and a needless one. Rather than pay that cost, we'd rather just eliminate the possibility altogether. That's what initialization is for. From ben+python at benfinney.id.au Tue Apr 26 16:51:10 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 27 Apr 2016 06:51:10 +1000 Subject: [Tutor] def __init__(self): References: Message-ID: <8560v4m6v5.fsf@benfinney.id.au> Santanu Jena writes: > I have idea regarding " __init__" method/ class.but still I have > confusion on "def __init__(self): " What is the confusion? Please say what you are expecting, and what is happening instead that confuses you. (Also, please don't top-post. Instead, post with replies interleaved and remove quoted material to which you are not responding.) > Please share your under standing. The ?__init__? method is the object initialiser. During the construction of an object, the constructor ?__new__? is called (to construct the object and return it), but before it is returned the new instance's ?__init__? method is called. This allows the constructed instance to perform any of its own custom initialisation. -- \ ?If I haven't seen as far as others, it is because giants were | `\ standing on my shoulders.? ?Hal Abelson | _o__) | Ben Finney From dyoo at hashcollision.org Tue Apr 26 18:52:09 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 26 Apr 2016 15:52:09 -0700 Subject: [Tutor] Detect the folder of a file In-Reply-To: References: Message-ID: On Tue, Apr 26, 2016 at 3:43 PM, Kanika Murarka wrote: > The folder which we create using command > \$ Virtualenv venv Hi Kanika, I think you need to ask the virtualenv folks; it seems to be virtualenv-specific. Their forum is: https://groups.google.com/forum/#!forum/python-virtualenv Good luck! From steve at pearwood.info Tue Apr 26 19:42:43 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 27 Apr 2016 09:42:43 +1000 Subject: [Tutor] def __init__(self): In-Reply-To: References: Message-ID: <20160426234242.GP13497@ando.pearwood.info> On Tue, Apr 26, 2016 at 12:31:28PM +0530, Santanu Jena wrote: > Hi, > > Pls let me why > " > def __init__(self): > > " > declaration required, what's the use of this one.Pls explain me in > details. Let's say that you have a class with a method: # A talking bird, says "Polly wants a cracker" (or some other name). class Parrot: def talk(self): message = "%s wants a cracker!" % self.name print(message) Now that we have the class, we need to create at least one individual parrot. So we can say: polly = Parrot() # create an instance of the class polly.name = "Polly" polly.talk() # => prints "Polly wants a cracker!" my_parrot = Parrot() # makes a second instance, a new parrot my_parrot.talk() # oops, we forgot to give it a name # => raises AttributeError, instance has no attribute "name" This is bad, because we might forget to set all the attributes of the instance and prepare it for use. With just one thing to set, the name, it is not too bad, but imagine if there were twenty things that needed to be done: my_parrot.name = "Peter" my_parrot.colour = "red" and so on. Fortunately, there is an alternative. When you create an instance by calling the class: my_parrot = Parrot() Python will call the special method "__init__" if it exists. This special method is called the "initialiser" or sometimes "constructor", because it is used to initialise the instance. We can give it arguments, and have it set up the instance's attributes: class Parrot: def __init__(self, name, colour="blue"): self.name = name self.colour = colour def talk(self): message = "%s wants a cracker!" % self.name print(message) polly = Parrot("Polly") # uses the default colour "blue" my_parrot = Parrot("Peter", "red") Python will automatically call the __init__ methods, which sets the name and colour attributes, so that the talk() method will work. -- Steve From murarkakanika at gmail.com Tue Apr 26 18:43:10 2016 From: murarkakanika at gmail.com (Kanika Murarka) Date: Wed, 27 Apr 2016 04:13:10 +0530 Subject: [Tutor] Detect the folder of a file In-Reply-To: References: Message-ID: The folder which we create using command \$ Virtualenv venv On 27 Apr 2016 00:57, "Danny Yoo" wrote: On Tue, Apr 26, 2016 at 6:47 AM, Kanika Murarka wrote: > Hi, > I want to detect whether a 'file1.py' belongs to virtual environment > folder( generally 'venv') or not ( considering different people may have > different names for virtual environment folder.). I think we need more information on what a "virtual environment folder" is. I do not know what that term means. From murarkakanika at gmail.com Tue Apr 26 19:02:22 2016 From: murarkakanika at gmail.com (Kanika Murarka) Date: Wed, 27 Apr 2016 04:32:22 +0530 Subject: [Tutor] Detect the folder of a file In-Reply-To: References: Message-ID: Thanks Danny On 27 Apr 2016 04:22, "Danny Yoo" wrote: > On Tue, Apr 26, 2016 at 3:43 PM, Kanika Murarka > wrote: > > The folder which we create using command > > \$ Virtualenv venv > > > Hi Kanika, > > > I think you need to ask the virtualenv folks; it seems to be > virtualenv-specific. Their forum is: > > https://groups.google.com/forum/#!forum/python-virtualenv > > Good luck! > From oliver at bestwalter.de Tue Apr 26 19:16:47 2016 From: oliver at bestwalter.de (Oliver Bestwalter) Date: Tue, 26 Apr 2016 23:16:47 +0000 Subject: [Tutor] Detect the folder of a file In-Reply-To: References: Message-ID: Hi, >>> import sys >>> sys.base_exec_prefix == sys.prefix False In a virtualenv those are different: https://docs.python.org/3/library/sys.html#sys.base_exec_prefix >>> sys.executable '/home/obestwalter/.pyenv/versions/3.4.4/envs/tmp/bin/python3.4' >>> sys.prefix '/home/obestwalter/.pyenv/versions/3.4.4/envs/tmp' This is the path to the virtualenv >>> os.path.split(sys.prefix)[-1] 'tmp' Gives you the name of the folder. cheers Oliver On Wed, 27 Apr 2016 at 00:52 Danny Yoo wrote: > On Tue, Apr 26, 2016 at 3:43 PM, Kanika Murarka > wrote: > > The folder which we create using command > > \$ Virtualenv venv > > > Hi Kanika, > > > I think you need to ask the virtualenv folks; it seems to be > virtualenv-specific. Their forum is: > > https://groups.google.com/forum/#!forum/python-virtualenv > > Good luck! > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From akleider at sonic.net Tue Apr 26 22:15:28 2016 From: akleider at sonic.net (Alex Kleider) Date: Tue, 26 Apr 2016 19:15:28 -0700 Subject: [Tutor] Detect the folder of a file In-Reply-To: References: Message-ID: <6553cfb329696cf0af811372403c575a@sonic.net> On 2016-04-26 16:16, Oliver Bestwalter wrote: >>>> sys.executable > '/home/obestwalter/.pyenv/versions/3.4.4/envs/tmp/bin/python3.4' Not sure if this helps but perhaps: alex at X301:~/Py\$ which python /usr/bin/python alex at X301:~/Py\$ . venv/bin/activate (venv)alex at X301:~/Py\$ which python /home/alex/Py/venv/bin/python (venv)alex at X301:~/Py\$ [Ubuntu 14.04 LTS] From paulrsmith7777 at gmail.com Wed Apr 27 08:47:14 2016 From: paulrsmith7777 at gmail.com (Paul Smith) Date: Wed, 27 Apr 2016 08:47:14 -0400 Subject: [Tutor] Python "password" securely hashed in script In-Reply-To: References: Message-ID: So creating small programs that automate my day specifically logins, how can one "hash" or hide the user and pass items in the python script itself? I need to prevent someone from easily seeing or accessing these if they happen to gain access to my python files. Thanks in advance. From j2 at mupp.net Wed Apr 27 09:24:19 2016 From: j2 at mupp.net (Jan Johansson) Date: Wed, 27 Apr 2016 13:24:19 +0000 Subject: [Tutor] Python "password" securely hashed in script In-Reply-To: References: , Message-ID: <53823EF3F5911F4D823DFD09156AD728D5F53478@ex01.kontinuitet.local> >I need to prevent someone from easily seeing or accessing these if they >happen to gain access to my python files. Thanks in advance. If they can read your script, they can also reverse engineed the code and decode your user/pass. (Also, "hashing" is a one way destructive operation, you can not retreive the original pass phrase) From __peter__ at web.de Wed Apr 27 09:41:09 2016 From: __peter__ at web.de (Peter Otten) Date: Wed, 27 Apr 2016 15:41:09 +0200 Subject: [Tutor] Python "password" securely hashed in script References: Message-ID: Paul Smith wrote: > So creating small programs that automate my day specifically logins, how > can one "hash" or hide the user and pass items in the python script > itself? I need to prevent someone from easily seeing or accessing these if > they happen to gain access to my python files. Thanks in advance. They can copy your script to gain access and just replace the part where you do something once you are logged in. From steve at pearwood.info Wed Apr 27 12:44:38 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 28 Apr 2016 02:44:38 +1000 Subject: [Tutor] Python "password" securely hashed in script In-Reply-To: References: Message-ID: <20160427164437.GQ13497@ando.pearwood.info> On Wed, Apr 27, 2016 at 08:47:14AM -0400, Paul Smith wrote: > So creating small programs that automate my day specifically logins, how > can one "hash" or hide the user and pass items in the python script itself? You can't, really. For *low security* passwords, or a trusted environment, you may be able to use a .netrc file to store the password. See the netrc module for more information: https://docs.python.org/2/library/netrc.html https://docs.python.org/3/library/netrc.html but remember, if the attacker has access to your account and can read your files, she can read your .netrc file as well. The one advantage to this scheme is that you can treat the .netrc file as the only secret that needs protecting, and the python scripts as "low security" because they contain no passwords. You can't hash the passwords, because you cannot reverse a hash to get the passwords back. Hashing is one-way. -- Steve From murarkakanika at gmail.com Wed Apr 27 21:02:04 2016 From: murarkakanika at gmail.com (Kanika Murarka) Date: Thu, 28 Apr 2016 06:32:04 +0530 Subject: [Tutor] Detect the folder of a file In-Reply-To: <6553cfb329696cf0af811372403c575a@sonic.net> References: <6553cfb329696cf0af811372403c575a@sonic.net> Message-ID: Thanks Oliver and Alex, I didnt know about these commands :D Oliver, When i typed print filename print sys.executable print sys.prefix print os.path.split(sys.prefix)[-1] my output was /home/kanikaa/pydsa7/venv/lib/python2.7/site-packages/ipython_genutils/tests/test_tempdir.py /usr/bin/python /usr usr but i want to know weather file belongs to 'venv' folder or not. Alex, Yup, that was helpful, but I want to do it without activating the environment. Thanks Again Kanika On 27 April 2016 at 07:45, Alex Kleider wrote: > > > On 2016-04-26 16:16, Oliver Bestwalter wrote: > > sys.executable >>>>> >>>> '/home/obestwalter/.pyenv/versions/3.4.4/envs/tmp/bin/python3.4' >> > > Not sure if this helps but perhaps: > > alex at X301:~/Py\$ which python > /usr/bin/python > alex at X301:~/Py\$ . venv/bin/activate > (venv)alex at X301:~/Py\$ which python > /home/alex/Py/venv/bin/python > (venv)alex at X301:~/Py\$ > > [Ubuntu 14.04 LTS] > > From oscar.j.benjamin at gmail.com Thu Apr 28 04:57:19 2016 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 28 Apr 2016 09:57:19 +0100 Subject: [Tutor] Detect the folder of a file In-Reply-To: References: <6553cfb329696cf0af811372403c575a@sonic.net> Message-ID: On 28 April 2016 at 02:02, Kanika Murarka wrote: > Thanks Oliver and Alex, I didnt know about these commands :D > > Oliver, > When i typed > print filename > print sys.executable > print sys.prefix > print os.path.split(sys.prefix)[-1] > > my output was > > /home/kanikaa/pydsa7/venv/lib/python2.7/site-packages/ipython_genutils/tests/test_tempdir.py > /usr/bin/python > /usr > usr > but i want to know weather file belongs to 'venv' folder or not. You can check if the 'venv' folder is part of a path using: import os.path dirpath = os.path.dirname(filename) dirnames = [] while dirpath: dirpath, dirname = os.path.split(dirpath) dirnames.append(dirname) if 'venv' in dirnames: # do whatever But how would you know that 'venv' is the name of a virtual environment folder? A virtual environment folder can be called anything. You can write some code to test if a particular path represents the base directory of a virtual environment but I expect it would probably be fragile. Without knowing why you want to do this I suggest that you might want to find a different general approach to your real problem. -- Oscar From __peter__ at web.de Thu Apr 28 05:44:32 2016 From: __peter__ at web.de (Peter Otten) Date: Thu, 28 Apr 2016 11:44:32 +0200 Subject: [Tutor] Detect the folder of a file References: <6553cfb329696cf0af811372403c575a@sonic.net> Message-ID: Oscar Benjamin wrote: > On 28 April 2016 at 02:02, Kanika Murarka wrote: >> Thanks Oliver and Alex, I didnt know about these commands :D >> >> Oliver, >> When i typed >> print filename >> print sys.executable >> print sys.prefix >> print os.path.split(sys.prefix)[-1] >> >> my output was >> >> /home/kanikaa/pydsa7/venv/lib/python2.7/site- packages/ipython_genutils/tests/test_tempdir.py >> /usr/bin/python >> /usr >> usr >> but i want to know weather file belongs to 'venv' folder or not. > > You can check if the 'venv' folder is part of a path using: > > import os.path > > dirpath = os.path.dirname(filename) > dirnames = [] > while dirpath: > dirpath, dirname = os.path.split(dirpath) > dirnames.append(dirname) > > if 'venv' in dirnames: > # do whatever > > But how would you know that 'venv' is the name of a virtual > environment folder? A virtual environment folder can be called > anything. > > You can write some code to test if a particular path represents the > base directory of a virtual environment but I expect it would probably > be fragile. Without knowing why you want to do this I suggest that you > might want to find a different general approach to your real problem. You could look for bin/activate. Yes, it's fragile, but in practice it might be good enough: import pathlib import sys path = sys.argv[1] for p in pathlib.Path(path).parents: if p.joinpath("bin/activate").is_file(): print("potential virtual environment:") print(p) break \$ python3 check_venv.py /home/nemo/virt/docopt/lib/python2.7/site- packages/docopt.py potential virtual environment: /home/nemo/virt/docopt From steve at pearwood.info Thu Apr 28 06:11:56 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 28 Apr 2016 20:11:56 +1000 Subject: [Tutor] Detect the folder of a file In-Reply-To: References: <6553cfb329696cf0af811372403c575a@sonic.net> Message-ID: <20160428101156.GS13497@ando.pearwood.info> On Thu, Apr 28, 2016 at 09:57:19AM +0100, Oscar Benjamin wrote: > You can write some code to test if a particular path represents the > base directory of a virtual environment but I expect it would probably > be fragile. Without knowing why you want to do this I suggest that you > might want to find a different general approach to your real problem. You know, some day I must learn why people use virtual environments. Its a total mystery to me. It makes a sort-of sense to me if you're talking about old versions of Python before per-user site-packages were added, but that's been available since version 2.6. So I don't get it. -- Steve From oscar.j.benjamin at gmail.com Thu Apr 28 09:24:00 2016 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 28 Apr 2016 14:24:00 +0100 Subject: [Tutor] Detect the folder of a file In-Reply-To: <20160428101156.GS13497@ando.pearwood.info> References: <6553cfb329696cf0af811372403c575a@sonic.net> <20160428101156.GS13497@ando.pearwood.info> Message-ID: On 28 April 2016 at 11:11, Steven D'Aprano wrote: > On Thu, Apr 28, 2016 at 09:57:19AM +0100, Oscar Benjamin wrote: > >> You can write some code to test if a particular path represents the >> base directory of a virtual environment but I expect it would probably >> be fragile. Without knowing why you want to do this I suggest that you >> might want to find a different general approach to your real problem. > > You know, some day I must learn why people use virtual environments. Its > a total mystery to me. It makes a sort-of sense to me if you're talking > about old versions of Python before per-user site-packages were added, > but that's been available since version 2.6. So I don't get it. They're useful for installing different versions of different packages without conflicting. Here's a typical example: I want to write a patch for sympy. First I need to check the latest git master to see if my patch is appropriate and then I need to write a patch against master. So I could install from master but maybe I already have some version of sympy installed that I don't want to mess with as I use it for other things. So I can create a virtual environment for this purpose: \$ py3.5 -m virtualenv sympyvenv Using base prefix '/users/enojb/.python/python3.5.1' New python executable in /users/enojb/sympyvenv/bin/py3.5 Also creating executable in /users/enojb/sympyvenv/bin/python Installing setuptools, pip, wheel...done. Let's have a look at this: \$ cd sympyvenv/ \$ ls bin include lib pip-selfcheck.json Now we can activate it. This puts it on PATH so that e.g. "python" runs the python from this venv (likewise pip, ipython etc.). The PS1 prompt is changed to remind you that it is active: \$ . bin/activate (sympyvenv) \$ Now clone sympy here: (sympyvenv) \$ git clone github.com:sympy/sympy.git # Or maybe your own fork Cloning into 'sympy'... remote: Counting objects: 179582, done. remote: Compressing objects: 100% (8/8), done. remote: Total 179582 (delta 0), reused 0 (delta 0), pack-reused 179574 Receiving objects: 100% (179582/179582), 75.12 MiB | 17.05 MiB/s, done. Resolving deltas: 100% (142458/142458), done. We can now install sympy in "editable" mode: (sympyvenv) \$ pip install -e sympy/ Obtaining file:///users/enojb/sympyvenv/sympy Collecting mpmath>=0.19 (from sympy==1.0.1.dev0) Installing collected packages: mpmath, sympy Running setup.py develop for sympy Successfully installed mpmath-0.19 sympy At this point I've installed the VCS checkout of sympy within the virtual environment. I can go edit the code for sympy at will and test it out. It doesn't matter if I break sympy in this virtual environment as I only use it for working on sympy. You can create a different virtual environment for everything that you're working on and there's no need for them to share versions of any packages. Another case would be to build up some code that does something and then pin the versions of all the libraries it uses so that if you come back and run it in 3 years time then it won't have been broken by any updates to these libraries. -- Oscar From joel.goldstick at gmail.com Thu Apr 28 11:54:49 2016 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 28 Apr 2016 11:54:49 -0400 Subject: [Tutor] Detect the folder of a file In-Reply-To: References: <6553cfb329696cf0af811372403c575a@sonic.net> <20160428101156.GS13497@ando.pearwood.info> Message-ID: On Thu, Apr 28, 2016 at 9:24 AM, Oscar Benjamin wrote: > On 28 April 2016 at 11:11, Steven D'Aprano wrote: >> On Thu, Apr 28, 2016 at 09:57:19AM +0100, Oscar Benjamin wrote: >> >> You know, some day I must learn why people use virtual environments. Its >> a total mystery to me. It makes a sort-of sense to me if you're talking >> about old versions of Python before per-user site-packages were added, >> but that's been available since version 2.6. So I don't get it. > I work with Django. If I have a project that was written with, say django 1.4, and it works I can leave that code to run in a virtual environment that uses django 1.4. Then I can create another environment for a new project that uses django 1.9. If I loaded the new version of django as a system level package, this would break the first project. -- Joel Goldstick http://joelgoldstick.com/blog http://cc-baseballstats.info/stats/birthdays From yeh at whoosh.cn Thu Apr 28 09:53:05 2016 From: yeh at whoosh.cn (Yeh) Date: Thu, 28 Apr 2016 21:53:05 +0800 Subject: [Tutor] Is there a library which has this object? Message-ID: Hi, Is there a library which can return some numbers continuously? It will be better to be found in the standard library. If there is not, I'm going to write the function. But, I have no ideas about it yet. (I'm absolutely a beginner.) I want to have a function which may has three arguments including startNumber, stopNumber and durition. if startNumber = 0, stopNumber = 2, and durition = 10, it will output 0 to 2 during 10ms continuously, such as: 0.00000...0.00001...0.00002...||until...||2.00000... and I also want to have another function which may has two arguments including freq and mul.and It will output numbers as an oscillator. (from 0 to 1, and back to 0, and go to -1, and -1 return to 0.) I'm thinking there is a library, maybe It just is inside standard library. But, I don't know it yet... So, thanks for all indeed! Yeh Z From alan.gauld at yahoo.co.uk Thu Apr 28 13:38:08 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 28 Apr 2016 18:38:08 +0100 Subject: [Tutor] Detect the folder of a file In-Reply-To: <20160428101156.GS13497@ando.pearwood.info> References: <6553cfb329696cf0af811372403c575a@sonic.net> <20160428101156.GS13497@ando.pearwood.info> Message-ID: On 28/04/16 11:11, Steven D'Aprano wrote: > You know, some day I must learn why people use virtual environments. Me too :-) My co-author included a section in one of her chapters of our recent book, and I duly played with them while reviewing that chapter. But at the end I just deleted it all and thought "Hmmmm....?" I know why they are useful in theory, but I've never found a practical use for them myself. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Thu Apr 28 13:46:33 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 28 Apr 2016 18:46:33 +0100 Subject: [Tutor] Is there a library which has this object? In-Reply-To: References: Message-ID: On 28/04/16 14:53, Yeh wrote: > Hi, > Is there a library which can return some numbers continuously? You probably want to look at the itertools module. There you can find among others the count() generator function. Others of possible interest include cycle() and repeat() -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From yeh at whoosh.cn Thu Apr 28 14:08:50 2016 From: yeh at whoosh.cn (Yeh) Date: Fri, 29 Apr 2016 02:08:50 +0800 Subject: [Tutor] Is there a library which has this object? In-Reply-To: References: , Message-ID: Thank you! > You probably want to look at the itertools module. > > There you can find among others the count() generator function. > Others of possible interest include cycle() and repeat() Yeah, I'm going to check them now.and I just solved my first question by using numpy, as below: import timeimport numpy as np start = input("please input the value of start: ")end = input("please input the value of end: ")dur = input("please input the value of dur: ")array = np.linspace(float(start),float(end),1000)dur = float(dur)/len(array)for i in array: print(float(i)) time.sleep(dur) But, how to make it become a function?I tried to:def myFunction(start,end,dur):...........for i in array: return i time.sleep(dur) as you see, I failed... Thanks again! From alan.gauld at yahoo.co.uk Thu Apr 28 18:35:36 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 28 Apr 2016 23:35:36 +0100 Subject: [Tutor] Is there a library which has this object? In-Reply-To: References: Message-ID: On 28/04/16 19:08, Yeh wrote: > I just solved my first question by using numpy, as below: You need to post in plain text otherwise the mail system mangles your code, as you can see. > import timeimport numpy as np > start = input("please input the value of start: ")end = input("please input the value of end: ")dur = input("please input the value of dur: ")array = np.linspace(float(start),float(end),1000)dur = float(dur)/len(array)for i in array: print(float(i)) time.sleep(dur) > But, how to make it become a function? > I tried to: > def myFunction(start,end,dur):...........for i in array: return i time.sleep(dur) > as you see, I failed... We can't see. We don't know what the dots are, and we don't know where the return is. Most of all we don't know if you get an error, or what the error says. The more specific information you give us the more chance we have of helping you. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From craigdan at msu.edu Thu Apr 28 19:27:43 2016 From: craigdan at msu.edu (Craig, Daniel Joseph) Date: Thu, 28 Apr 2016 23:27:43 +0000 Subject: [Tutor] vpython help Message-ID: To whom it may concern, I am writing a program where I have a ball with a position and velocity reach a wall in 3D space. I am able to drag the ball around after it is done moving but I would like to be able to move the ball prior to it moving towards the wall. Is there a way to do this, any help would be much appreciated. From itetteh34 at hotmail.com Thu Apr 28 17:19:20 2016 From: itetteh34 at hotmail.com (isaac tetteh) Date: Thu, 28 Apr 2016 16:19:20 -0500 Subject: [Tutor] Is there a library which has this object? In-Reply-To: References: Message-ID: Im sure its not working because array is not in function. paste the error message here im sure someone will give u a better answer Sent from my iPhone > On Apr 28, 2016, at 4:07 PM, Yeh wrote: > > Thank you! > >> You probably want to look at the itertools module. >> >> There you can find among others the count() generator function. >> Others of possible interest include cycle() and repeat() > Yeah, I'm going to check them now.and I just solved my first question by using numpy, as below: > import timeimport numpy as np > start = input("please input the value of start: ")end = input("please input the value of end: ")dur = input("please input the value of dur: ")array = np.linspace(float(start),float(end),1000)dur = float(dur)/len(array)for i in array: print(float(i)) time.sleep(dur) > But, how to make it become a function?I tried to:def myFunction(start,end,dur):...........for i in array: return i time.sleep(dur) > as you see, I failed... > Thanks again! > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From alan.gauld at yahoo.co.uk Fri Apr 29 04:20:11 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 29 Apr 2016 09:20:11 +0100 Subject: [Tutor] vpython help In-Reply-To: References: Message-ID: On 29/04/16 00:27, Craig, Daniel Joseph wrote: > I am writing a program where I have a ball with a position and velocity > reach a wall in 3D space. Well done, but vpython is a bit off topic for this list which deals with the core python language and libraries. I notice there is a vpython user forum, you might get more/better answers there: https://groups.google.com/forum/?fromgroups&hl=en#!forum/vpython-users > I am able to drag the ball around after it is done moving > but I would like to be able to move the ball prior to > it moving towards the wall. I'm not clear what you mean by that. I'm sure it will be possible but it sounds very vpython specific. If you ask on the vpython forum you should probably include some code to show what you have done so far. And include any error messages too. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Fri Apr 29 06:02:07 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 29 Apr 2016 20:02:07 +1000 Subject: [Tutor] vpython help In-Reply-To: References: Message-ID: <20160429100206.GV13497@ando.pearwood.info> Hi Daniel, and welcome, On Thu, Apr 28, 2016 at 11:27:43PM +0000, Craig, Daniel Joseph wrote: > To whom it may concern, > > > I am writing a program where I have a ball with a position and > velocity reach a wall in 3D space. I am able to drag the ball around > after it is done moving but I would like to be able to move the ball > prior to it moving towards the wall. Is there a way to do this, any > help would be much appreciated. I'm sure there is a way, but please put yourself in our shoes. Read your message above, and, imagine that you know NOTHING else about your program than what you write above. What answer would you give? "Yes, there is a way to do this. Write some more program code." Please tell us what you have actually done. What graphics library are you using? How did you create the ball? What version of Python are you using, on what operating system (Linux, Mac OS, Windows, Android, something else)? -- Steve From 79135751678 at ya.ru Fri Apr 29 09:10:28 2016 From: 79135751678 at ya.ru (=?koi8-r?B?8MHXxcwg7M/QwdTJzg==?=) Date: Fri, 29 Apr 2016 16:10:28 +0300 Subject: [Tutor] (no subject) Message-ID: <8830861461935428@web18j.yandex.ru> Hello, I downloaded Python 3.4.3 from python.org, installed it, but when I tried to run it on my notebook a message appeared IDLE's subprocess didn't make connection. Either IDLE can't start a subprocess or personal firewall software is blocking the connection. There was a button OK. I clicked it and Python closed. There is operating system Windows XP on my notebook. On the ordinary personal computer this Python worked. With best regards, Pavel From Peter.Tees at ethosenergygroup.com Fri Apr 29 09:15:02 2016 From: Peter.Tees at ethosenergygroup.com (Tees, Peter (EthosEnergy)) Date: Fri, 29 Apr 2016 13:15:02 +0000 Subject: [Tutor] pytsk Message-ID: Hi folks I'm pretty new to Python and programming, I've done the first four modules of the Python course at Coursera.org to get started Now I want to put what I've learned to good use, based on the articles by David Cowen at the Hacking Exposed blog and in particular his series "Automating DFIR - How to series on programming libtsk with Python" (which is Python 2.7, same as Coursera.org) The very first thing to be done, after installing Python, is to grab a Windows installer for the pytsk library from here https://github.com/log2timeline/l2tbinaries/blob/master/win32/pytsk3-4.1.3-20140506.win32-py2.7.msi But that link doesn't work (Page 404), and any other downloads I've seen so far refer either to binding to The Sleuthkit or refer to pytsk3 which I don't think is what I need Can anyone point me to a Windows 32-bit installer for a pytsk library that will work with Python 2.7? Thanks & regards Peter Tees IT Compliance & Forensic Analyst D: +44 (0) 1224 367212 peter.tees at ethosenergygroup www.ethosenergygroup.com [cid:image002.png at 01D1A221.84A5E4A0] Follow Us! [cid:image001.jpg at 01D04497.89DA9B20] [cid:image002.jpg at 01D04497.89DA9B20] [cid:image003.jpg at 01D04497.89DA9B20] [cid:image004.jpg at 01D04497.89DA9B20] [cid:image005.jpg at 01D04497.89DA9B20] This email and its attachments may contain information which is confidential and/or legally privileged. If you are not the intended recipient of this email please notify the sender immediately by email and delete this email and its attachments from your computer and IT systems. You must not copy, re-transmit, use or disclose (other than to the sender) the existence or contents of this email or its attachments or permit anyone else to do so. ------------------------------ This email is confidential and may be protected by legal privilege. If you are not the intended recipient you should not copy it, re-transmit it, use it or disclose its contents, but should return it to the sender immediately and delete your copy from your system. Internet emails are not necessarily secure. The company does not accept responsibility for changes made to this message after it was sent. While all reasonable care has been taken to avoid the transmission of viruses, it is the responsibility of the recipient to ensure that the onward transmission, opening or use of this message and any attachments will not adversely affect its systems or data. No responsibility is accepted by the company in this regard and the recipient should carry out such virus and other checks as it considers appropriate. This email has been scanned for Virus and Spam content by EthosEnergy. From alan.gauld at yahoo.co.uk Fri Apr 29 12:52:04 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 29 Apr 2016 17:52:04 +0100 Subject: [Tutor] (no subject) In-Reply-To: <8830861461935428@web18j.yandex.ru> References: <8830861461935428@web18j.yandex.ru> Message-ID: On 29/04/16 14:10, ????? ??????? wrote: > Hello, > I downloaded Python 3.4.3 from python.org, installed it, > but when I tried to run it on my notebook a message appeared The error is about IDLE rather than about Python so its probably worth checking whether python itself runs first. Open a CMD console WindowsKey-R (Or Start->Run) Type cmd and hit ok. In the window that appears type python3 You should see a prompt that looks something like Python 3.4.3 (default, Oct 14 2015, 20:28:29) [GCC 4.8.4] on linux Type "help", "copyright", "credits" or "license" for more information. >>> Except yours will say Windows rather than linux, etc. If so then python is working OK and we can then look into the IDLE issues. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From colin.ross.dal at gmail.com Fri Apr 29 13:15:13 2016 From: colin.ross.dal at gmail.com (Colin Ross) Date: Fri, 29 Apr 2016 14:15:13 -0300 Subject: [Tutor] Extracting bits from an array Message-ID: Hello, I have an array that takes on the following form: x = [1000,1001,1011,1111] The array elements are meant to be binary representation of integers. Goal: Access array elements and extract the first two bits. e.g. Final result would look something like this: x_new = [10,10,10,11] What I have tried: data_indices = range(4) # Set up array of values to loop over for idx in data_indices: f = x[idx] # Index into array of x values f_idx = f[:2] # Extract first two elements print f_idx I then receive the following error: IndexError: invalid index to scalar variable. Any help with accomplishing my outline dgoal would be greatly appreciated. Thank you. Colin From colin.ross.dal at gmail.com Fri Apr 29 13:42:56 2016 From: colin.ross.dal at gmail.com (Colin Ross) Date: Fri, 29 Apr 2016 14:42:56 -0300 Subject: [Tutor] Extracting bits from an array In-Reply-To: <32B9A03E-F6B3-446B-8A09-6DC1A3CCEFCD@gmail.com> References: <32B9A03E-F6B3-446B-8A09-6DC1A3CCEFCD@gmail.com> Message-ID: Thank you Michael, this is exactly what I was looking for! Clears things up on multiple fronts : ) On Fri, Apr 29, 2016 at 2:29 PM, Michael Selik wrote: > > > > On Apr 29, 2016, at 1:15 PM, Colin Ross > wrote: > > > > Hello, > > > > I have an array that takes on the following form: > > > > x = [1000,1001,1011,1111] > > > > The array elements are meant to be binary representation of integers. > > > > Goal: Access array elements and extract the first two bits. > > > > e.g. Final result would look something like this: > > > > x_new = [10,10,10,11] > > > > What I have tried: > > > > data_indices = range(4) # Set up array of values to loop over > > > > for idx in data_indices: > > f = x[idx] # Index into array of x values > > Instead of looping over a range of indices, you should loop over the data > itself. > > for number in x: > s = bin(number) > print s > > > f_idx = f[:2] # Extract first two elements > > You couldn't slice an integer. First convert to the binary representation > in string form. You can strip off the prefix if you just want the digits. > > s = bin(number).lstrip('0b') > > Then you can slice off the first two digits if you want. Remember, it's a > str of digits, not a number. > > > print f_idx > > > > I then receive the following error: > > > > IndexError: invalid index to scalar variable. > > > > Any help with accomplishing my outline dgoal would be greatly > appreciated. > > > > Thank you. > > > > Colin > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor > From __peter__ at web.de Fri Apr 29 13:47:38 2016 From: __peter__ at web.de (Peter Otten) Date: Fri, 29 Apr 2016 19:47:38 +0200 Subject: [Tutor] Extracting bits from an array References: Message-ID: Colin Ross wrote: > Hello, > > I have an array that takes on the following form: > > x = [1000,1001,1011,1111] But these are actually integers in decimal representation. You could treat them as binary, but I recommend that you use integers in binary representation to avoid confusion: >>> x = [0b1000, 0b1001, 0b1011, 0b1111] >>> x [8, 9, 11, 15] > The array elements are meant to be binary representation of integers. > > Goal: Access array elements and extract the first two bits. Is the number of bits fixed to four? If so you can shift the bits to the right: >>> y = [v>>2 for v in x] >>> y [2, 2, 2, 3] >>> y [2, 2, 2, 3] All that is left to do now is to convert the result to binary for display purposes: >>> for v in y: print "{:02b}".format(v) ... 10 10 10 11 > e.g. Final result would look something like this: > > x_new = [10,10,10,11] > > What I have tried: > > data_indices = range(4) # Set up array of values to loop over > > for idx in data_indices: > f = x[idx] # Index into array of x values > f_idx = f[:2] # Extract first two elements This works for strings and sequences, but not for numbers. > print f_idx > > I then receive the following error: > > IndexError: invalid index to scalar variable. From alan.gauld at yahoo.co.uk Fri Apr 29 15:00:06 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 29 Apr 2016 20:00:06 +0100 Subject: [Tutor] pytsk In-Reply-To: References: Message-ID: On 29/04/16 14:15, Tees, Peter (EthosEnergy) wrote: > Now I want to put what I've learned to good use, based on the > articles by David Cowen at the Hacking Exposed blog > and in particular his series "Automating DFIR - How to series > on programming libtsk with Python" > Can anyone point me to a Windows 32-bit installer Nope, I can only find the Github site which requires you to build it from source. And given it appears to be written in C that may be too advanced a topic for you just now. Maybe you should start with something simpler? Or find a different library to do what you want to do... > for a pytsk library that will work with Python 2.7? I did find a v3 pytsk, which presumably is for Python v3. I didn't notice a Win32 installer for it though. Normally I'd refer you to the pytsk community for further support since its really outside the scope of this list, but I didn't see any links to such a group. You may be best emailing the author (or the author of the tutorial you were reading) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From sunithanc at gmail.com Fri Apr 29 15:19:16 2016 From: sunithanc at gmail.com (SM) Date: Fri, 29 Apr 2016 15:19:16 -0400 Subject: [Tutor] pytsk In-Reply-To: References: Message-ID: I often refer to the same blog (hacking exposed), and find many of the links broken, even though there is a lot of very useful information there. I use pytsk on Linux and always build it from source from here: https://github.com/py4n6/pytsk/releases/download/<>/pytsk-<>.tgz e.g: https://github.com/py4n6/pytsk/releases/download/20150406/pytsk-20150406.tgz -Sunita On Fri, Apr 29, 2016 at 9:15 AM, Tees, Peter (EthosEnergy) < Peter.Tees at ethosenergygroup.com> wrote: > Hi folks > > I'm pretty new to Python and programming, I've done the first four modules > of the Python course at Coursera.org to get started > > Now I want to put what I've learned to good use, based on the articles by > David Cowen at the Hacking Exposed blog and in particular his series > "Automating DFIR - How to series on programming libtsk with Python" (which > is Python 2.7, same as Coursera.org) > > The very first thing to be done, after installing Python, is to grab a > Windows installer for the pytsk library from here > https://github.com/log2timeline/l2tbinaries/blob/master/win32/pytsk3-4.1.3-20140506.win32-py2.7.msi > > But that link doesn't work (Page 404), and any other downloads I've seen > so far refer either to binding to The Sleuthkit or refer to pytsk3 which I > don't think is what I need > > Can anyone point me to a Windows 32-bit installer for a pytsk library that > will work with Python 2.7? > > Thanks & regards > > Peter Tees > IT Compliance & Forensic Analyst > > D: +44 (0) 1224 367212 > peter.tees at ethosenergygroup > www.ethosenergygroup.com > > [cid:image002.png at 01D1A221.84A5E4A0] > Follow Us! [cid:image001.jpg at 01D04497.89DA9B20] < > https://www.linkedin.com/company/ethosenergy> > [cid:image002.jpg at 01D04497.89DA9B20] < > https://www.youtube.com/channel/UCMP35rfJ-hkeETNrQbxPZ4w> > [cid:image003.jpg at 01D04497.89DA9B20] < > https://www.facebook.com/EthosEnergyPPS> > [cid:image004.jpg at 01D04497.89DA9B20] < > https://plus.google.com/110364885156198751003/posts?gpinv=AMIXal-_9u3UwfxLb8KZ2DC-RzET6qMa_DF0n7FxQ_Qi6dpzq-cF3aS9Lfyij0Fzj2TO7jdOxp4S_A96oFmZ-kat-Bs_aBbwRs_CwM34wY_GOVaTZlEUNH0&cfem=1> > [cid:image005.jpg at 01D04497.89DA9B20] > This email and its attachments may contain information which is > confidential and/or legally privileged. If you are not the intended > recipient of this email please notify the sender immediately by email and > delete this email and its attachments from your computer and IT systems. > You must not copy, re-transmit, use or disclose (other than to the sender) > the existence or contents of this email or its attachments or permit anyone > else to do so. > > ------------------------------ This email is confidential and may be > protected by legal privilege. If you are not the intended recipient you > should not copy it, re-transmit it, use it or disclose its contents, but > should return it to the sender immediately and delete your copy from your > system. Internet emails are not necessarily secure. The company does not > accept responsibility for changes made to this message after it was sent. > While all reasonable care has been taken to avoid the transmission of > viruses, it is the responsibility of the recipient to ensure that the > onward transmission, opening or use of this message and any attachments > will not adversely affect its systems or data. No responsibility is > accepted by the company in this regard and the recipient should carry out > such virus and other checks as it considers appropriate. This email has > been scanned for Virus and Spam content by EthosEnergy. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From zachary.ware+pytut at gmail.com Fri Apr 29 15:40:18 2016 From: zachary.ware+pytut at gmail.com (Zachary Ware) Date: Fri, 29 Apr 2016 14:40:18 -0500 Subject: [Tutor] pytsk In-Reply-To: References: Message-ID: Hi Peter, On Fri, Apr 29, 2016 at 8:15 AM, Tees, Peter (EthosEnergy) wrote: > Hi folks > > I'm pretty new to Python and programming, I've done the first four modules of the Python course at Coursera.org to get started > > Now I want to put what I've learned to good use, based on the articles by David Cowen at the Hacking Exposed blog and in particular his series "Automating DFIR - How to series on programming libtsk with Python" (which is Python 2.7, same as Coursera.org) > > The very first thing to be done, after installing Python, is to grab a Windows installer for the pytsk library from here https://github.com/log2timeline/l2tbinaries/blob/master/win32/pytsk3-4.1.3-20140506.win32-py2.7.msi > > But that link doesn't work (Page 404), and any other downloads I've seen so far refer either to binding to The Sleuthkit or refer to pytsk3 which I don't think is what I need > > Can anyone point me to a Windows 32-bit installer for a pytsk library that will work with Python 2.7? I can't find one easily, but it does look like pytsk3 is what you want -- looking at the link you provided, the name is 'pytsk3-...'. So what should be sufficient is to install the Microsoft Visual C++ Compiler for Python 2.7 [1], then run 'python -m pip install pytsk3'. That should be enough to get you going. [1] https://aka.ms/vcpython27 Hope this helps, -- Zach From beachkidken at gmail.com Fri Apr 29 16:01:06 2016 From: beachkidken at gmail.com (Ken G.) Date: Fri, 29 Apr 2016 16:01:06 -0400 Subject: [Tutor] Sorting a list in ascending order Message-ID: <5723BD82.9000807@gmail.com> In entering five random number, how can I best sort it into ascending order, such as 0511414453? Using Linux 2.7.6 in Ubuntu 14.04.4. Thanks. number01 = "41" number02 = "11" number03 = "05" number04 = "53" number05 = "44" line = number01 + number02 + number03 + number04 + number05 print print line line.sort() print print line 4111055344 Traceback (most recent call last): File "Mega_Millions_01_Tickets_Entry_TEST_TEST.py", line 11, in print line.sort() AttributeError: 'str' object has no attribute 'sort' From meenuravi89 at gmail.com Fri Apr 29 16:58:30 2016 From: meenuravi89 at gmail.com (meenu ravi) Date: Fri, 29 Apr 2016 15:58:30 -0500 Subject: [Tutor] Sorting a list in ascending order In-Reply-To: <5723BD82.9000807@gmail.com> References: <5723BD82.9000807@gmail.com> Message-ID: Hi Ken, As the message clearly says, the string object doesn't have an attribute "sort". You are trying to join the inputs as a single string,"line" and then you are trying to sort it. But, as you want the string in the sorted format, you should sort it first and then convert it into string, as follows. number01 = "41" number02 = "11" number03 = "05" number04 = "53" number05 = "44" list1 = [number01,number02,number03,number04,number05] # Creating a list with the inputs list1.sort() # sorting the input print ''.join(list1) #making it again as a single string Hope this helps. Happy coding. Thanks, Meena On Fri, Apr 29, 2016 at 3:01 PM, Ken G. wrote: > In entering five random number, how can I best sort > it into ascending order, such as 0511414453? Using > Linux 2.7.6 in Ubuntu 14.04.4. Thanks. > > number01 = "41" > number02 = "11" > number03 = "05" > number04 = "53" > number05 = "44" > line = number01 + number02 + number03 + number04 + number05 > print > print line > line.sort() > print > print line > > > 4111055344 > > Traceback (most recent call last): > File "Mega_Millions_01_Tickets_Entry_TEST_TEST.py", line 11, in > print line.sort() > > AttributeError: 'str' object has no attribute 'sort' > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From martin at linux-ip.net Fri Apr 29 17:10:07 2016 From: martin at linux-ip.net (Martin A. Brown) Date: Fri, 29 Apr 2016 14:10:07 -0700 Subject: [Tutor] Sorting a list in ascending order In-Reply-To: <5723BD82.9000807@gmail.com> References: <5723BD82.9000807@gmail.com> Message-ID: Greetings Ken and welcome to Python, > Using Linux 2.7.6 in Ubuntu 14.04.4. Thanks. Thank you for this information. I have one tip for you: While Python 2.x will still be around for a while, if you are learning Python today, I'd suggest Python 3.x. You can read more about the differences online (or ask here), if you care. The only syntax difference that usually trips up beginners is the following: print line # Python 2.x print(line) # Python 3.x Though there are other differences, this is one of the most obvious to all Python programmers. With that said, I'll just answer your question using Python 2.x, since everything else in your example will work perfectly the same in either version. I intend to suggest what you should read, and then what you should try to run in order to address your question(s). I will paste my entire interactive Python sessions below. Did you know that you can use the Python interpreter as a shell to test out how things behave? Very handy. Try typing 'python' at the CLI and you should see this: \$ python Python 2.7.8 (default, Sep 30 2014, 15:34:38) [GCC] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> So, when you see ">>>" below, that's in the Python shell (2.7.8 in my case, 2.7.6 in yours). > In entering five random number, how can I best sort it into > ascending order, such as 0511414453? OK, so you have five random numbers, but you seem to want to print them without any visual space between them. A bit strange, but OK! Fragment #1: > number01 = "41" > number02 = "11" > number03 = "05" > number04 = "53" > number05 = "44" Observation: You define a variable called 'number01', which actually contains a string value. You can call the variable anything you want, but that will not change the type of the object to which your variable name is bound. For example: >>> number01 = "41" >>> type(number01) Suggestion #1, try this instead: >>> number01 = 41 >>> type(number01) Ah-ha! Now, we are dealing with integers (numbers). Fragment #2: > line = number01 + number02 + number03 + number04 + number05 Observation: Since all of the variables (named number01, number02, number03, etc....) contain strings, you are using string concatenation to create a new string. After the above command executes, you have this: >>> line '4111055344' >>> type(line) Comment: You don't really want a string, do you? Keep reading for a moment, and I'll come back to this. Also, I don't think you really want to add the integers. That would be 41 + 11 + 05 + 53 + 44 = 154. But, you want to keep the numbers and sort them. We will need to keep them in a list. And, Python has a data structure for you...called, obviously enough list(). Fragment #3: > print > print line > line.sort() > > Traceback (most recent call last): > File "Mega_Millions_01_Tickets_Entry_TEST_TEST.py", line 11, in > print line.sort() > > AttributeError: 'str' object has no attribute 'sort' Observation: This message is called an Exception, in Python. There are many different kinds of exceptions--this one is called AttributeError, but the message of the exception is the important part for us here. It doesn't make sense to sort a string. You can sort two strings, of course. But not a single string. Anyway, the important thing about the Exception is it tries to give you a good deal of information about which line of code did something that was problematic, and what code called that code (this is why it's called a "Traceback"). Now, I'll rewind to the beginning and try to go through the problem again, changing a few pieces of your program to get you closer to your solution. First, let's use the right datatype, an int, for each number. Second, let's use a list() to store the numbers (instead of five separate named variables; easy to mistype names). Third, let's sort it. Then, let's print it. >>> nums = [41, 11, 5, 53, 44] # -- create/populate a list >>> nums [41, 11, 5, 53, 44] # -- still looks good >>> nums.sort() # -- sort, in place! >>> nums [5, 11, 41, 44, 53] # -- Ta-da! I'm going to do the same thing a slightly different way, now, so you can see how to add stuff to a list: >>> nums = list() >>> nums.append(41) >>> nums.append(11) >>> nums.append(5) >>> nums.append(53) >>> nums.append(44) >>> nums [41, 11, 5, 53, 44] In each case the variable 'nums' still contains the same data. We just got there in a different series of steps. You may decide which makes more sense to you in any given situation. So, suggestion, play with lists, and see how they work. Now, we have to figure out how to print the contents of the list. Here's one way, but it is not the output you appear to want. >>> print nums [5, 11, 41, 44, 53] I'm guessing you want '05 11 41 44 53'. There are many ways to convert from one data type to another or to format the output of something when you want to print it. So, I will show you one or two ways, but there are many ways you could do this. It's good to learn to read them all, but you can always pick the one that works best for your situation. Conversion is one way The 'str' function converts the int (17) into a string. I store that in a variable called string_num. The 'type' function tells us that the contents of the variable string_num are of type 'str': >>> num = 17 >>> string_num = str(num) >>> string_num '17' >>> type(string_num) This is useful, but, we are not going to do that here. Detour to format strings! What I'm about to show is how you can format a value (usually in preparation for output/printing). There are many different ways to print numbers, as you may know from prior mathematics classes. (Ignoring some possibly important subtleties for a moment,) 1, 1.0, 1e0 are different ways of printing the value of 1. >>> num = 7 >>> '%d' % (num,) '7' Let's add a leading zero: >>> '%02d' % (num,) '07' I think that's what you want. Returning to your data, you might be worried about that 5, which was missing its leading zero. Well, as you can see the number is never stored with that leading zero. A number is a number. However, we can produce the leading zero when we print. >>> stringified_nums = list() >>> for x in nums: ... stringified_nums.append('%02d' % (x,)) >>> stringified_nums ['05', '11', '41', '44', '53'] Lastly, let's print the stringified_nums; do you want to print them with colons separating the numbers, semicolons, commas, a hyphen? >>> ':'.join(stringified_nums) '05:11:41:44:53' >>> ','.join(stringified_nums) '05,11,41,44,53' Now, I'm going to put it all together..... nums = [41, 11, 5, 53, 44] nums.sort() outstr = list() for x in nums: outstr.append('%02d' % (x,)) print ' '.join(outstr) Hopefully that made sense to you. I include a few links to various places in the Python project documentation that may help you. In particular, I'd recommend that you read through the Python tutorial and keep a Python interactive interpreter open while you do that, so you can play with the different datatypes and functions. If you have more questions, please ask here, there are quite a few others who are happy to help. Best of luck, -Martin Tutorial: https://docs.python.org/2/tutorial/introduction.html on numbers: https://docs.python.org/2/tutorial/introduction.html#numbers on strings: https://docs.python.org/2/tutorial/introduction.html#strings on lists: https://docs.python.org/2/tutorial/introduction.html#lists Reference: https://docs.python.org/2/library/index.html on datatypes: https://docs.python.org/2/library/stdtypes.html#numeric-types-int-float-long-complex on sequences: https://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange on functions: https://docs.python.org/2/library/functions.html (A list is a sequence. There are other types of sequences, but the section on sequences, should give you some idea of how to play with lists.) -- Martin A. Brown http://linux-ip.net/ From beachkidken at gmail.com Fri Apr 29 18:58:37 2016 From: beachkidken at gmail.com (Ken G.) Date: Fri, 29 Apr 2016 18:58:37 -0400 Subject: [Tutor] Sorting a list in ascending order [RESOLVED] In-Reply-To: References: <5723BD82.9000807@gmail.com> Message-ID: <5723E71D.60903@gmail.com> > On Fri, Apr 29, 2016 at 3:01 PM, Ken G. > wrote: > > In entering five random number, how can I best sort > it into ascending order, such as 0511414453? Using > Linux 2.7.6 in Ubuntu 14.04.4. Thanks. > > number01 = "41" > number02 = "11" > number03 = "05" > number04 = "53" > number05 = "44" > line = number01 + number02 + number03 + number04 + number05 > print > print line > line.sort() > print > print line > > > 4111055344 > > Traceback (most recent call last): > File "Mega_Millions_01_Tickets_Entry_TEST_TEST.py", line 11, in > > print line.sort() > > AttributeError: 'str' object has no attribute 'sort' > On 04/29/2016 04:58 PM, meenu ravi wrote: > Hi Ken, > > As the message clearly says, the string object doesn't have an > attribute "sort". You are trying to join the inputs as a single > string,"line" and then you are trying to sort it. But, as you want the > string in the sorted format, you should sort it first and then convert > it into string, as follows. > > number01 = "41" > number02 = "11" > number03 = "05" > number04 = "53" > number05 = "44" > list1 = [number01,number02,number03,number04,number05] # Creating a > list with the inputs > > list1.sort() # sorting the input > print ''.join(list1) #making it again as a single string > > Hope this helps. Happy coding. > > Thanks, > Meena Thanks, Meena, that is great! I changed your last line to: print "".join(list1) and it came out as below: 0511414453 Another quotation mark was needed. Again, thanks. Ken I appreciate all of everybody help. Ken From beachkidken at gmail.com Fri Apr 29 19:05:27 2016 From: beachkidken at gmail.com (Ken G.) Date: Fri, 29 Apr 2016 19:05:27 -0400 Subject: [Tutor] Sorting a list in ascending order [RESOLVED] In-Reply-To: References: <5723BD82.9000807@gmail.com> Message-ID: <5723E8B7.6090108@gmail.com> On 04/29/2016 05:10 PM, Martin A. Brown wrote: > Greetings Ken and welcome to Python, > >> Using Linux 2.7.6 in Ubuntu 14.04.4. Thanks. > Thank you for this information. I have one tip for you: While > Python 2.x will still be around for a while, if you are learning > Python today, I'd suggest Python 3.x. You can read more about the > differences online (or ask here), if you care. The only syntax > difference that usually trips up beginners is the following: > > print line # Python 2.x > print(line) # Python 3.x > > Though there are other differences, this is one of the most obvious > to all Python programmers. With that said, I'll just answer your > question using Python 2.x, since everything else in your example > will work perfectly the same in either version. > > I intend to suggest what you should read, and then what you should > try to run in order to address your question(s). > > I will paste my entire interactive Python sessions below. Did you > know that you can use the Python interpreter as a shell to test out > how things behave? Very handy. Try typing 'python' at the CLI and > you should see this: > > \$ python > Python 2.7.8 (default, Sep 30 2014, 15:34:38) [GCC] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> > > So, when you see ">>>" below, that's in the Python shell (2.7.8 in > my case, 2.7.6 in yours). > >> In entering five random number, how can I best sort it into >> ascending order, such as 0511414453? > OK, so you have five random numbers, but you seem to want to print > them without any visual space between them. A bit strange, but OK! > > Fragment #1: > >> number01 = "41" >> number02 = "11" >> number03 = "05" >> number04 = "53" >> number05 = "44" > Observation: You define a variable called 'number01', which > actually contains a string value. You can call the variable > anything you want, but that will not change the type of the object > to which your variable name is bound. For example: > > >>> number01 = "41" > >>> type(number01) > > > Suggestion #1, try this instead: > > >>> number01 = 41 > >>> type(number01) > > > Ah-ha! Now, we are dealing with integers (numbers). > > Fragment #2: > >> line = number01 + number02 + number03 + number04 + number05 > Observation: Since all of the variables (named number01, number02, > number03, etc....) contain strings, you are using string > concatenation to create a new string. After the above command > executes, you have this: > > >>> line > '4111055344' > >>> type(line) > > > Comment: You don't really want a string, do you? Keep reading for > a moment, and I'll come back to this. > > Also, I don't think you really want to add the integers. That would > be 41 + 11 + 05 + 53 + 44 = 154. But, you want to keep the numbers > and sort them. We will need to keep them in a list. And, Python > has a data structure for you...called, obviously enough list(). > > Fragment #3: > >> print >> print line >> line.sort() >> >> Traceback (most recent call last): >> File "Mega_Millions_01_Tickets_Entry_TEST_TEST.py", line 11, in >> print line.sort() >> >> AttributeError: 'str' object has no attribute 'sort' > Observation: This message is called an Exception, in Python. > There are many different kinds of exceptions--this one is called > AttributeError, but the message of the exception is the important > part for us here. It doesn't make sense to sort a string. You can > sort two strings, of course. But not a single string. > > Anyway, the important thing about the Exception is it tries to give > you a good deal of information about which line of code did > something that was problematic, and what code called that code (this > is why it's called a "Traceback"). > > Now, I'll rewind to the beginning and try to go through the problem > again, changing a few pieces of your program to get you closer to > your solution. > > First, let's use the right datatype, an int, for each number. > Second, let's use a list() to store the numbers (instead of five > separate named variables; easy to mistype names). > Third, let's sort it. > Then, let's print it. > > >>> nums = [41, 11, 5, 53, 44] # -- create/populate a list > >>> nums > [41, 11, 5, 53, 44] # -- still looks good > >>> nums.sort() # -- sort, in place! > >>> nums > [5, 11, 41, 44, 53] # -- Ta-da! > > I'm going to do the same thing a slightly different way, now, so you > can see how to add stuff to a list: > > >>> nums = list() > >>> nums.append(41) > >>> nums.append(11) > >>> nums.append(5) > >>> nums.append(53) > >>> nums.append(44) > >>> nums > [41, 11, 5, 53, 44] > > In each case the variable 'nums' still contains the same data. We > just got there in a different series of steps. You may decide which > makes more sense to you in any given situation. > > So, suggestion, play with lists, and see how they work. > > Now, we have to figure out how to print the contents of the list. > Here's one way, but it is not the output you appear to want. > > >>> print nums > [5, 11, 41, 44, 53] > > I'm guessing you want '05 11 41 44 53'. > > There are many ways to convert from one data type to another or to > format the output of something when you want to print it. So, I > will show you one or two ways, but there are many ways you could do > this. It's good to learn to read them all, but you can always pick > the one that works best for your situation. > > Conversion is one way The 'str' function converts the int (17) into > a string. I store that in a variable called string_num. The 'type' > function tells us that the contents of the variable string_num are > of type 'str': > > >>> num = 17 > >>> string_num = str(num) > >>> string_num > '17' > >>> type(string_num) > > > This is useful, but, we are not going to do that here. > > Detour to format strings! What I'm about to show is how you can > format a value (usually in preparation for output/printing). > > There are many different ways to print numbers, as you may know from > prior mathematics classes. (Ignoring some possibly important > subtleties for a moment,) 1, 1.0, 1e0 are different ways of printing > the value of 1. > > >>> num = 7 > >>> '%d' % (num,) > '7' > > Let's add a leading zero: > > >>> '%02d' % (num,) > '07' > > I think that's what you want. > > Returning to your data, you might be worried about that 5, which was > missing its leading zero. Well, as you can see the number is never > stored with that leading zero. A number is a number. However, we > can produce the leading zero when we print. > > >>> stringified_nums = list() > >>> for x in nums: > ... stringified_nums.append('%02d' % (x,)) > >>> stringified_nums > ['05', '11', '41', '44', '53'] > > Lastly, let's print the stringified_nums; do you want to print them > with colons separating the numbers, semicolons, commas, a hyphen? > > >>> ':'.join(stringified_nums) > '05:11:41:44:53' > >>> ','.join(stringified_nums) > '05,11,41,44,53' > > Now, I'm going to put it all together..... > > nums = [41, 11, 5, 53, 44] > nums.sort() > outstr = list() > for x in nums: > outstr.append('%02d' % (x,)) > print ' '.join(outstr) > > Hopefully that made sense to you. I include a few links to various > places in the Python project documentation that may help you. In > particular, I'd recommend that you read through the Python tutorial > and keep a Python interactive interpreter open while you do that, so > you can play with the different datatypes and functions. > > If you have more questions, please ask here, there are quite a few > others who are happy to help. > > Best of luck, > > -Martin > > Tutorial: https://docs.python.org/2/tutorial/introduction.html > on numbers: https://docs.python.org/2/tutorial/introduction.html#numbers > on strings: https://docs.python.org/2/tutorial/introduction.html#strings > on lists: https://docs.python.org/2/tutorial/introduction.html#lists > > Reference: https://docs.python.org/2/library/index.html > on datatypes: https://docs.python.org/2/library/stdtypes.html#numeric-types-int-float-long-complex > on sequences: https://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange > on functions: https://docs.python.org/2/library/functions.html > > (A list is a sequence. There are other types of sequences, but > the section on sequences, should give you some idea of how to play > with lists.) > Martin: I have been using Python2 for several years now and I have yet been able to change over to Python3. I am not together sure if Python3 is now more stable to use and more commonly use. If so, I will gradually change over but do realize there is a learning curve to learn. It will be slowly done but sooner or later, I will be using Python3. I wonder if there is a script to translate my Python2 programs to Python3 format. Hmm. I will some searching for such an animal. Hey, thanks for your encouragement. Much appreciated. Ken From anish198519851985 at gmail.com Fri Apr 29 15:47:37 2016 From: anish198519851985 at gmail.com (Anish Kumar) Date: Fri, 29 Apr 2016 12:47:37 -0700 Subject: [Tutor] Extracting bits from an array In-Reply-To: References: Message-ID: <1F595316-12E9-4477-AD88-35C8B52655C9@gmail.com> > >> Hello, >> >> I have an array that takes on the following form: >> >> x = [1000,1001,1011,1111] > > But these are actually integers in decimal representation. You could treat > them as binary, but I recommend that you use integers in binary > representation to avoid confusion: > >>>> x = [0b1000, 0b1001, 0b1011, 0b1111] >>>> x > [8, 9, 11, 15] > >> The array elements are meant to be binary representation of integers. >> >> Goal: Access array elements and extract the first two bits. > > Is the number of bits fixed to four? If so you can shift the bits to the > right: > >>>> y = [v>>2 for v in x] Right shifting is well defined in Python? >>>> y > [2, 2, 2, 3] >>>> y > [2, 2, 2, 3] > > All that is left to do now is to convert the result to binary for display > purposes: > >>>> for v in y: print "{:02b}".format(v) > ... > 10 > 10 > 10 > 11 > >> e.g. Final result would look something like this: >> >> x_new = [10,10,10,11] >> >> What I have tried: >> >> data_indices = range(4) # Set up array of values to loop over >> >> for idx in data_indices: >> f = x[idx] # Index into array of x values >> f_idx = f[:2] # Extract first two elements > > This works for strings and sequences, but not for numbers. > >> print f_idx >> >> I then receive the following error: >> >> IndexError: invalid index to scalar variable. > > > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > https://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 146, Issue 40 > ************************************** From itetteh34 at hotmail.com Fri Apr 29 16:29:54 2016 From: itetteh34 at hotmail.com (isaac tetteh) Date: Fri, 29 Apr 2016 15:29:54 -0500 Subject: [Tutor] Sorting a list in ascending order In-Reply-To: <5723BD82.9000807@gmail.com> References: <5723BD82.9000807@gmail.com> Message-ID: You can use sorted(line) but you result will be in a list if thats okay. Otherwise you can iterate the list. Sent from my iPhone > On Apr 29, 2016, at 3:03 PM, Ken G. wrote: > > In entering five random number, how can I best sort > it into ascending order, such as 0511414453? Using > Linux 2.7.6 in Ubuntu 14.04.4. Thanks. > > number01 = "41" > number02 = "11" > number03 = "05" > number04 = "53" > number05 = "44" > line = number01 + number02 + number03 + number04 + number05 > print > print line > line.sort() > print > print line > > > 4111055344 > > Traceback (most recent call last): > File "Mega_Millions_01_Tickets_Entry_TEST_TEST.py", line 11, in > print line.sort() > > AttributeError: 'str' object has no attribute 'sort' > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From michael.selik at gmail.com Fri Apr 29 13:29:49 2016 From: michael.selik at gmail.com (Michael Selik) Date: Fri, 29 Apr 2016 13:29:49 -0400 Subject: [Tutor] Extracting bits from an array In-Reply-To: References: Message-ID: <32B9A03E-F6B3-446B-8A09-6DC1A3CCEFCD@gmail.com> > On Apr 29, 2016, at 1:15 PM, Colin Ross wrote: > > Hello, > > I have an array that takes on the following form: > > x = [1000,1001,1011,1111] > > The array elements are meant to be binary representation of integers. > > Goal: Access array elements and extract the first two bits. > > e.g. Final result would look something like this: > > x_new = [10,10,10,11] > > What I have tried: > > data_indices = range(4) # Set up array of values to loop over > > for idx in data_indices: > f = x[idx] # Index into array of x values Instead of looping over a range of indices, you should loop over the data itself. for number in x: s = bin(number) print s > f_idx = f[:2] # Extract first two elements You couldn't slice an integer. First convert to the binary representation in string form. You can strip off the prefix if you just want the digits. s = bin(number).lstrip('0b') Then you can slice off the first two digits if you want. Remember, it's a str of digits, not a number. > print f_idx > > I then receive the following error: > > IndexError: invalid index to scalar variable. > > Any help with accomplishing my outline dgoal would be greatly appreciated. > > Thank you. > > Colin > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From alan.gauld at yahoo.co.uk Fri Apr 29 19:40:14 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 30 Apr 2016 00:40:14 +0100 Subject: [Tutor] Sorting a list in ascending order [RESOLVED] In-Reply-To: <5723E71D.60903@gmail.com> References: <5723BD82.9000807@gmail.com> <5723E71D.60903@gmail.com> Message-ID: On 29/04/16 23:58, Ken G. wrote: >> print ''.join(list1) #making it again as a single string >> > > Thanks, Meena, that is great! I changed your last line to: > > print "".join(list1) and it came out as below: > > 0511414453 > > Another quotation mark was needed. No it wasn't. Meena used two single quotes, you used two double quotes. Both will work. But the two single quotes can look like a single double quote depending on your font choices. So double quotes in this case are probably less ambiguous. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Fri Apr 29 19:48:36 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 30 Apr 2016 00:48:36 +0100 Subject: [Tutor] Sorting a list in ascending order [RESOLVED] In-Reply-To: <5723E8B7.6090108@gmail.com> References: <5723BD82.9000807@gmail.com> <5723E8B7.6090108@gmail.com> Message-ID: On 30/04/16 00:05, Ken G. wrote: > been able to change over to Python3. I am not together sure if Python3 > is now more stable to use and more commonly use. It is definitely stable and most libraries are now converted (although a few remain v2 only). Availability of libraries is now the only real reason to stick with v2 IMHO. > change over but do realize there is a learning curve to learn. The main learning is in the libraries rather than the core language. Quite a lot of modules got changed/moved/renamed etc. Also the return values of a lot of functions changed to iterators and the like. Those are the things that tend to catch you out, not the core language. > there is a script to translate my Python2 programs to Python3 format. Yes there is, although it's not foolproof, you often have to manually tweak things. It comes with v3 in, I think, the scripts folder. There is also something called six that you should investigate if you have a significant amount of v2 code to manage alongside v3. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Fri Apr 29 19:50:55 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 30 Apr 2016 00:50:55 +0100 Subject: [Tutor] Extracting bits from an array In-Reply-To: <1F595316-12E9-4477-AD88-35C8B52655C9@gmail.com> References: <1F595316-12E9-4477-AD88-35C8B52655C9@gmail.com> Message-ID: On 29/04/16 20:47, Anish Kumar wrote: >> Is the number of bits fixed to four? If so you can shift the bits to the >> right: >> >>>>> y = [v>>2 for v in x] > > Right shifting is well defined in Python? Yes, Python has good support for all the common bitwise operations, including the shift right/left operators. Read the documentation for the limitations. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From beachkidken at gmail.com Fri Apr 29 20:30:26 2016 From: beachkidken at gmail.com (Ken G.) Date: Fri, 29 Apr 2016 20:30:26 -0400 Subject: [Tutor] Sorting a list in ascending order [RESOLVED] In-Reply-To: References: <5723BD82.9000807@gmail.com> <5723E71D.60903@gmail.com> Message-ID: <5723FCA2.3040109@gmail.com> On 04/29/2016 07:40 PM, Alan Gauld via Tutor wrote: > On 29/04/16 23:58, Ken G. wrote: > >>> print ''.join(list1) #making it again as a single string >>> >> Thanks, Meena, that is great! I changed your last line to: >> >> print "".join(list1) and it came out as below: >> >> 0511414453 >> >> Another quotation mark was needed. > No it wasn't. Meena used two single quotes, you used > two double quotes. Both will work. But the two single > quotes can look like a single double quote depending > on your font choices. So double quotes in this case > are probably less ambiguous. > > Gosh, been using double quotes since the late eighties and thus, a hard habit to break when encourage to use single quote mark in Python. Thanks for the reminder of "it" being a possible double single quote when encountering a double quote at various times. Ken From meenuravi89 at gmail.com Fri Apr 29 20:31:53 2016 From: meenuravi89 at gmail.com (meenu ravi) Date: Fri, 29 Apr 2016 19:31:53 -0500 Subject: [Tutor] Sorting a list in ascending order [RESOLVED] In-Reply-To: <5723E71D.60903@gmail.com> References: <5723BD82.9000807@gmail.com> <5723E71D.60903@gmail.com> Message-ID: That's actually two single quotes:-) both single and double quotes should work. Thanks, Meena On Apr 29, 2016 5:58 PM, "Ken G." wrote: > > On Fri, Apr 29, 2016 at 3:01 PM, Ken G. wrote: > >> In entering five random number, how can I best sort >> it into ascending order, such as 0511414453? Using >> Linux 2.7.6 in Ubuntu 14.04.4. Thanks. >> >> number01 = "41" >> number02 = "11" >> number03 = "05" >> number04 = "53" >> number05 = "44" >> line = number01 + number02 + number03 + number04 + number05 >> print >> print line >> line.sort() >> print >> print line >> >> >> 4111055344 >> >> Traceback (most recent call last): >> File "Mega_Millions_01_Tickets_Entry_TEST_TEST.py", line 11, in >> print line.sort() >> >> AttributeError: 'str' object has no attribute 'sort' >> > > On 04/29/2016 04:58 PM, meenu ravi wrote: > > Hi Ken, > > As the message clearly says, the string object doesn't have an attribute > "sort". You are trying to join the inputs as a single string,"line" and > then you are trying to sort it. But, as you want the string in the sorted > format, you should sort it first and then convert it into string, as > follows. > > number01 = "41" > number02 = "11" > number03 = "05" > number04 = "53" > number05 = "44" > list1 = [number01,number02,number03,number04,number05] # Creating a list > with the inputs > > list1.sort() # sorting the input > print ''.join(list1) #making it again as a single string > > Hope this helps. Happy coding. > > Thanks, > Meena > > > Thanks, Meena, that is great! I changed your last line to: > > print "".join(list1) and it came out as below: > > 0511414453 > > Another quotation mark was needed. > > Again, thanks. > > Ken > > > > > I appreciate all of everybody help. > > Ken > From __peter__ at web.de Sat Apr 30 02:52:00 2016 From: __peter__ at web.de (Peter Otten) Date: Sat, 30 Apr 2016 08:52 +0200 Subject: [Tutor] Extracting bits from an array References: <1F595316-12E9-4477-AD88-35C8B52655C9@gmail.com> Message-ID: Anish Kumar wrote: > Right shifting is well defined in Python? Yes. What might surprise someone used to fixed-size integers: >>> -1 >> 1 -1 Any negative int will eventually end as -1: >>> -1234 >> 10 -2 >>> -1234 >> 11 -1 From __peter__ at web.de Sat Apr 30 03:12:19 2016 From: __peter__ at web.de (Peter Otten) Date: Sat, 30 Apr 2016 09:12:19 +0200 Subject: [Tutor] Extracting bits from an array References: <1F595316-12E9-4477-AD88-35C8B52655C9@gmail.com> Message-ID: Peter Otten wrote: > Anish Kumar wrote: > >> Right shifting is well defined in Python? > > Yes. What might surprise someone used to fixed-size integers: > >>>> -1 >> 1 > -1 > > Any negative int will eventually end as -1: > >>>> -1234 >> 10 > -2 >>>> -1234 >> 11 > -1 I just checked and C works the same. Sorry for spreading misinformation. From oscar.j.benjamin at gmail.com Sat Apr 30 05:09:18 2016 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sat, 30 Apr 2016 10:09:18 +0100 Subject: [Tutor] Extracting bits from an array In-Reply-To: References: <1F595316-12E9-4477-AD88-35C8B52655C9@gmail.com> Message-ID: On 30 Apr 2016 08:14, "Peter Otten" <__peter__ at web.de> wrote: > > Peter Otten wrote: > > > Anish Kumar wrote: > > > >> Right shifting is well defined in Python? > > > > Yes. What might surprise someone used to fixed-size integers: > > > >>>> -1 >> 1 > > -1 > > > > Any negative int will eventually end as -1: > > > >>>> -1234 >> 10 > > -2 > >>>> -1234 >> 11 > > -1 > > I just checked and C works the same. Sorry for spreading misinformation. Bitwise operations on signed types are undefined (hence best avoided) in C. -- Oscar From nymcity at yahoo.com Sat Apr 30 14:51:17 2016 From: nymcity at yahoo.com (Jason N.) Date: Sat, 30 Apr 2016 18:51:17 +0000 (UTC) Subject: [Tutor] "List" object is not callable References: <1105117411.4367773.1462042277993.JavaMail.yahoo.ref@mail.yahoo.com> Message-ID: <1105117411.4367773.1462042277993.JavaMail.yahoo@mail.yahoo.com> Hello, I found this simple script online but when I execute it I get the following error: "TypeError: 'list' object is not callable" Here is the code sample:import subprocess ls_output= subprocess.check_output(['dir']) I searched online and found a another similar code sample (http://www.opentechguides.com/how-to/article/python/57/python-ping-subnet.html) but when I run it on my system I get the same error.Any feedback is very much appreciated. ?Thank you. From akleider at sonic.net Sat Apr 30 15:27:16 2016 From: akleider at sonic.net (Alex Kleider) Date: Sat, 30 Apr 2016 12:27:16 -0700 Subject: [Tutor] "List" object is not callable In-Reply-To: <1105117411.4367773.1462042277993.JavaMail.yahoo@mail.yahoo.com> References: <1105117411.4367773.1462042277993.JavaMail.yahoo.ref@mail.yahoo.com> <1105117411.4367773.1462042277993.JavaMail.yahoo@mail.yahoo.com> Message-ID: <8b1d5c88b1c2523d9e7e5d561b46929b@sonic.net> On 2016-04-30 11:51, Jason N. via Tutor wrote: > Hello, > I found this simple script online but when I execute it I get the > following error: "TypeError: 'list' object is not callable" > Here is the code sample:import subprocess > > ls_output= subprocess.check_output(['dir']) It works on my system: Ubuntu 14.04LTS (venv)alex at X301:~\$ python Python 3.4.3 (default, Oct 14 2015, 20:33:09) [GCC 4.8.4] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import subprocess >>> ls_output= subprocess.check_output(['dir']) >>> ls_output b'Airbnb\tBookSite CURRENT Documents examples.desktop\tJs\t nextWIFI\t OpenWRT Py\t Solar ToDo\t WARNING\nARM\tC\t debk\t double gnupg.other\tLEFTOFF node_modules Pathagar Rachel Templates toDoAtLoft wishes\nAVR\tclosures Desktop Downloads GPL\t\tLibreboot Notes\t Pictures Sask Test Videos\t WWW\nbin\tContacts Docbook Encrypted HTML5\t\tMusic\t OLPC\t\t Public ski\t tmp\t vim_rewrap\n' >>> exit() (venv)alex at X301:~\$ dir Airbnb BookSite CURRENT Documents examples.desktop Js nextWIFI OpenWRT Py Solar ToDo WARNING ARM C debk double gnupg.other LEFTOFF node_modules Pathagar Rachel Templates toDoAtLoft wishes AVR closures Desktop Downloads GPL Libreboot Notes Pictures Sask Test Videos WWW bin Contacts Docbook Encrypted HTML5 Music OLPC Public ski tmp vim_rewrap (venv)alex at X301:~\$ man dir Perhaps you are using a linux command on a non linux (?Windows) system. From bgailer at gmail.com Sat Apr 30 17:27:36 2016 From: bgailer at gmail.com (bob gailer) Date: Sat, 30 Apr 2016 17:27:36 -0400 Subject: [Tutor] "List" object is not callable In-Reply-To: <8b1d5c88b1c2523d9e7e5d561b46929b@sonic.net> References: <1105117411.4367773.1462042277993.JavaMail.yahoo.ref@mail.yahoo.com> <1105117411.4367773.1462042277993.JavaMail.yahoo@mail.yahoo.com> <8b1d5c88b1c2523d9e7e5d561b46929b@sonic.net> Message-ID: <57252348.4050709@gmail.com> On 4/30/2016 3:27 PM, Alex Kleider wrote: > > > On 2016-04-30 11:51, Jason N. via Tutor wrote: >> Hello, >> I found this simple script online but when I execute it I get the >> following error: "TypeError: 'list' object is not callable" >> Here is the code sample:import subprocess >> >> ls_output= subprocess.check_output(['dir']) > It works on my system: Ubuntu 14.04LTS Works on my Windows 10 also. Always post the traceback. The problem must lie in check_output as there is nothing in your code that could raise that exception. From thomasolaoluwa at gmail.com Sat Apr 30 11:30:33 2016 From: thomasolaoluwa at gmail.com (Olaoluwa Thomas) Date: Sat, 30 Apr 2016 16:30:33 +0100 Subject: [Tutor] Issue with Code Message-ID: Hi, I'm new to Python and programming in general. I came across a simple exercise that is used to compute gross pay when prompted to enter number of hours and hourly rate. I've attached the scripts in question (created via Notepad++). The 1st script I wrote worked perfectly. The 2nd script makes amendments to the 1st by increasing the hourly rate by 50% when number of hours is greater than 40. The problem with this script is that the "else" statement (which is equivalent to the 1st script) does not compute gross pay accurately as seen in the attached screenshot. I would appreciate a logical explanation for why the "else" statement in the 2nd script isn't working properly. I'm running Python v2.7.8 on a Windows 7 Ultimate VM via Command prompt and my scripts are created and edited via Notepad++ v6.7.3 *Warm regards,* *Olaoluwa O. Thomas,* *+2347068392705* -------------- next part -------------- hours = raw_input ('How many hours do you work?\n') rate = raw_input ('What is your hourly rate?\n') gross = float(hours) * float(rate) print "Your Gross pay is "+str(round(gross, 4)) -------------- next part -------------- hours = raw_input ('How many hours do you work?\n') rate = raw_input ('What is your hourly rate?\n') if hours > 40: gross = ((float(hours) - 40) * (float(rate) * 1.5)) + (40 * float(rate)) else: gross = float(hours) * float(rate) print "Your Gross pay is "+str(round(gross, 4)) From thomasolaoluwa at gmail.com Sat Apr 30 17:32:14 2016 From: thomasolaoluwa at gmail.com (Olaoluwa Thomas) Date: Sat, 30 Apr 2016 22:32:14 +0100 Subject: [Tutor] Fwd: Issue with Code In-Reply-To: References: Message-ID: Hi All, I sent this forwarded email earlier but hadn't subscribed to the mailing list so I guess that's why I didn't get a response. Please review and advise. *Warm regards,* *Olaoluwa O. Thomas,* *+2347068392705* ---------- Forwarded message ---------- From: Olaoluwa Thomas Date: Sat, Apr 30, 2016 at 4:30 PM Subject: Issue with Code To: tutor at python.org Hi, I'm new to Python and programming in general. I came across a simple exercise that is used to compute gross pay when prompted to enter number of hours and hourly rate. I've attached the scripts in question (created via Notepad++). The 1st script I wrote worked perfectly. The 2nd script makes amendments to the 1st by increasing the hourly rate by 50% when number of hours is greater than 40. The problem with this script is that the "else" statement (which is equivalent to the 1st script) does not compute gross pay accurately as seen in the attached screenshot. I would appreciate a logical explanation for why the "else" statement in the 2nd script isn't working properly. I'm running Python v2.7.8 on a Windows 7 Ultimate VM via Command prompt and my scripts are created and edited via Notepad++ v6.7.3 *Warm regards,* *Olaoluwa O. Thomas,* *+2347068392705* -------------- next part -------------- hours = raw_input ('How many hours do you work?\n') rate = raw_input ('What is your hourly rate?\n') gross = float(hours) * float(rate) print "Your Gross pay is "+str(round(gross, 4)) -------------- next part -------------- hours = raw_input ('How many hours do you work?\n') rate = raw_input ('What is your hourly rate?\n') if hours > 40: gross = ((float(hours) - 40) * (float(rate) * 1.5)) + (40 * float(rate)) else: gross = float(hours) * float(rate) print "Your Gross pay is "+str(round(gross, 4)) From yeh at whoosh.cn Sat Apr 30 03:48:59 2016 From: yeh at whoosh.cn (Yeh) Date: Sat, 30 Apr 2016 15:48:59 +0800 Subject: [Tutor] Is there a library which has this object? In-Reply-To: References: , , , , , Message-ID: ?> You need to post in plain text otherwise the mail system mangles your ?> code, as you can see. I'm sorry for it. :( my code is: import time import numpy as np start = input("please input the value of start: ") end = input("please input the value of end: ") dur = input("please input the value of dur: ") array = np.linspace(float(start),float(end),1000) dur = float(dur)/len(array) for i in array: print(float(i)) time.sleep(dur) and it worked, then, I was trying to make it as a function: def myFunction(start,end,dur): ........... for i in array: return i time.sleep(dur) there is no errors. because it just post the first number in the array, even I change the order of time.sleep() and return. I have checked the cycle(), and yes, that is what I'm searching! But, I got an other question, how to stop cycle() by manual? such as press "q", then break the cycle(). and has same question to make it be a function. Thanks Yeh Z From alan.gauld at yahoo.co.uk Sat Apr 30 20:16:46 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 1 May 2016 01:16:46 +0100 Subject: [Tutor] Issue with Code In-Reply-To: References: Message-ID: On 30/04/16 16:30, Olaoluwa Thomas wrote: > I've attached the scripts in question (created via Notepad++). attachments often get stripped by the mail system as a security risk. Since your code is very short just post it in the mail message as plain text. > The problem with this script is that the "else" statement (which is > equivalent to the 1st script) does not compute gross pay accurately as seen > in the attached screenshot. The screenshot seems to have been stripped so we can't see it. Just tell us what happened and what you expected. Or better still cut 'n paste the output into the message. > I would appreciate a logical explanation for why the "else" statement in > the 2nd script isn't working properly. It almost certainly is working properly, just not as you expected it to :-) When dealing with floating point numbers remember that they will always be approximations to the whole number so calculations will similarly result in approximations. Usually if you round the results the figures will look ok. I can't see anything obviously wrong in your code although it could be simplified. Please post a sample including the inputs and outputs. Tell us what you expect to see as well as showing us what you do see. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Sat Apr 30 20:21:35 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 1 May 2016 01:21:35 +0100 Subject: [Tutor] Fwd: Issue with Code In-Reply-To: References: Message-ID: On 30/04/16 22:32, Olaoluwa Thomas wrote: > I sent this forwarded email earlier but hadn't subscribed to the mailing > list so I guess that's why I didn't get a response. When you first subscribe all messages are moderated so there is a delay. Plus remember that email is pretty much the lowest priority message type on the internet so mail can be delayed for up to 24 hours, so you may not always get an instant response even when everything is working as it should. I have now taken you off moderation which should speed things up a bit... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Sat Apr 30 20:53:51 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 1 May 2016 01:53:51 +0100 Subject: [Tutor] Is there a library which has this object? In-Reply-To: References: Message-ID: On 30/04/16 08:48, Yeh wrote: > start = input("please input the value of start: ") > end = input("please input the value of end: ") > dur = input("please input the value of dur: ") > array = np.linspace(float(start),float(end),1000) > dur = float(dur)/len(array) > for i in array: > print(float(i)) > time.sleep(dur) Since you say it works I assume you are still not posting in plain text since it would need indentation after the for loop. > and it worked, then, I was trying to make it as a function: > > def myFunction(start,end,dur): > ........... I don;t know what the dots are. They should give you an error! > for i in array: > return i > time.sleep(dur) > > there is no errors. because it just post the first number in the array, Your problem is that return always returns the value and exits the function. Next time you call the function it starts again from the beginning. I think you are looking to create a generator which is a function that returns a value but next time you call the function it carries on where it left off. The good news is that this is easy, just substitute yield for return. The next problem is to make the function increment the value each time and for that you need a loop. def make_numbers(start, end): while start <= end: yield start Notice I've removed the duration parameter because that's better done outside the function (a function should do only one thing, in this case generate numbers). We can access the numbers and introduce a delay with: for n in make_numbers(float(start),float(end)) print (n) time.sleep(float(dur)) But of course that's pretty much what the built in range() function does for you anyway. for n in range(float(start), float(end)): print(n) time.sleep(float(dur)) > I have checked the cycle(), and yes, that is what I'm searching! > how to stop cycle() by manual? > such as press "q", then break the cycle(). You will need to include a command to read the keyboard during your loop. How you do that depends on your needs and maybe your OS. You can use input() but the user then needs to hit a key every loop iteration. Or you can use getch() from curses on Linux or from msvcrt on Windows if you don't want the user to have to hit enter each time. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From matt.ruffalo at gmail.com Sat Apr 30 20:47:19 2016 From: matt.ruffalo at gmail.com (Matt Ruffalo) Date: Sat, 30 Apr 2016 20:47:19 -0400 Subject: [Tutor] Issue with Code In-Reply-To: References: Message-ID: <57255217.80805@gmail.com> On 2016-04-30 11:30, Olaoluwa Thomas wrote: > I would appreciate a logical explanation for why the "else" statement in > the 2nd script isn't working properly. > > I'm running Python v2.7.8 on a Windows 7 Ultimate VM via Command prompt and > my scripts are created and edited via Notepad++ v6.7.3 > Hi- The problem is that you're reading 'hours' and 'rate' from the user with 'raw_input', and this function returns a string containing the characters that the user typed. You convert these to floating point numbers before doing any processing of the gross pay, but in your 'GrossPayv2.py', you compare the string referred to by 'hours' to the numeric value 40. In Python 2, strings always compare as greater than integers: """ Python 2.7.11+ (default, Apr 17 2016, 14:00:29) [GCC 5.3.1 20160413] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> "60" > 40 True >>> "20" > 40 True """ This unfortunate behavior is one of the things fixed in Python 3. Unless you have a compelling reason otherwise (like a course or textbook that you're learning from), I would recommend using Python 3 instead of 2, since many of these "gotcha" behaviors have been fixed in the newer (but backward-incompatible) version of the language. Specifically: """ Python 3.5.1+ (default, Mar 30 2016, 22:46:26) [GCC 5.3.1 20160330] on linux Type "help", "copyright", "credits" or "license" for more information. >>> "60" > 40 Traceback (most recent call last): File "", line 1, in TypeError: unorderable types: str() > int() """ MMR... From alan.gauld at yahoo.co.uk Sat Apr 30 21:00:57 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 1 May 2016 02:00:57 +0100 Subject: [Tutor] Issue with Code In-Reply-To: References: Message-ID: On 01/05/16 01:16, Alan Gauld via Tutor wrote: > I can't see anything obviously wrong in your code I was too busy focusing on the calculations that I didn't check the 'if' test closely enough. You need to convert your values from strings before comparing them. hours = float(raw_input ('How many hours do you work?\n')) rate = float(raw_input ('What is your hourly rate?\n')) if hours > 40: gross = (hours-40)*(rate*1.5) + (rate*40) else: gross = hours*rate Sorry, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Sat Apr 30 23:11:45 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 1 May 2016 13:11:45 +1000 Subject: [Tutor] "List" object is not callable In-Reply-To: <1105117411.4367773.1462042277993.JavaMail.yahoo@mail.yahoo.com> References: <1105117411.4367773.1462042277993.JavaMail.yahoo.ref@mail.yahoo.com> <1105117411.4367773.1462042277993.JavaMail.yahoo@mail.yahoo.com> Message-ID: <20160501031145.GY13497@ando.pearwood.info> On Sat, Apr 30, 2016 at 06:51:17PM +0000, Jason N. via Tutor wrote: > Hello, > I found this simple script online but when I execute it I get the > following error: "TypeError: 'list' object is not callable" Here is > the code sample: > > import subprocess > ls_output= subprocess.check_output(['dir']) The code snippet works fine. Please check that the code you send is exactly the same as the code you are actually trying to run. Do not just retype the code from memory, copy and paste it. Also, please copy and paste the full traceback that you get, not just the final error message. Everything from the first "Traceback" line to the end. Finally, you should tell us what version of Python you are running, on what operating system (Linux, Mac OS, Windows XP, Windows 10, Android, something else), and whether you are using the standard Python interactive interpreter or something else (IDLE, iPython, Anaconda, PyCharm, etc.). -- Steve From steve at pearwood.info Sat Apr 30 23:22:40 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 1 May 2016 13:22:40 +1000 Subject: [Tutor] Sorting a list in ascending order [RESOLVED] In-Reply-To: <5723E8B7.6090108@gmail.com> References: <5723BD82.9000807@gmail.com> <5723E8B7.6090108@gmail.com> Message-ID: <20160501032239.GZ13497@ando.pearwood.info> On Fri, Apr 29, 2016 at 07:05:27PM -0400, Ken G. wrote: > Martin: I have been using Python2 for several years now and I have yet > been able to change over to Python3. I am not together sure if Python3 > is now more stable to use and more commonly use. If so, I will gradually > change over but do realize there is a learning curve to learn. It will > be slowly done but sooner or later, I will be using Python3. I wonder if > there is a script to translate my Python2 programs to Python3 format. Python 3 is not only stable, it has been stable since version 3.1 about five years ago. (Unfortunately, version 3.0 turned out to be broken and should never be used.) We're now up to Python 3.5, with 3.6 about to come out soon. Python 2 comes with a script called "2to3" which will take a Python 2 script and update it to Python 3: https://docs.python.org/2/library/2to3.html Make sure you have backups! -- Steve From katuite13 at gmail.com Sat Apr 30 21:36:47 2016 From: katuite13 at gmail.com (Katie Tuite) Date: Sun, 01 May 2016 01:36:47 +0000 Subject: [Tutor] Python Homework Message-ID: I'm trying to do a python homework question and cannot figure out how to start at all. This is the question [image: pasted1]