From alan.gauld at yahoo.co.uk Mon Aug 1 04:05:36 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 1 Aug 2016 09:05:36 +0100 Subject: [Tutor] Book recommendation In-Reply-To: References: Message-ID: On 01/08/16 00:14, D Wyatt wrote: > answers I could understand from you all. While I appreciate the time and > effort you put in helping us out, most of you do not remember what you > didn't used to know, and are often less than helpful because of this. That's a fair point. After 20, 30 or, as in my case, 40 years of programming its hard to remember what you found difficult at the start. Also when addressing an answer you have to make a guess at the level of the questioner and often we don't get much of a clue. (A good counter example is Bob Stepp who was "overly humble" in his questions and got treated as an absolute newbie but then turned out to have quite a lot of experience.) Also many books teach Python to established programmers and relatively few books really aim at the complete beginner. My original book did but even it assumed a good knowledge of PC usage. The author just has to make a guess at the average readers skills and run with that. One area that is especially troublesome is knowledge of math. Programming is rooted in math and professional programmers will have studied math in depth but many amateur beginners may only have junior school math level. But how do you find out? It's a perennial problem when experts try to help novices... -- 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 Aug 1 13:12:22 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 1 Aug 2016 10:12:22 -0700 Subject: [Tutor] Book recommendation In-Reply-To: References: Message-ID: > One area that is especially troublesome is knowledge of > math. Programming is rooted in math and professional > programmers will have studied math in depth but many > amateur beginners may only have junior school math > level. But how do you find out? > > It's a perennial problem when experts try to help novices... [Meta discussion] I think the recommendations from: https://www.recurse.com/manual#sec-environment are reasonable. Basically, we should keep in mind not to be jerks. :P Also, I think it's fair to say that some of us have some backgrounds as teachers, and we remember the admonishments from John Holt's "How Children Fail": https://en.wikipedia.org/wiki/How_Children_Fail From jkornonthecob at yahoo.com Mon Aug 1 11:18:03 2016 From: jkornonthecob at yahoo.com (Justin Korn) Date: Mon, 1 Aug 2016 11:18:03 -0400 Subject: [Tutor] Python Assignment Message-ID: <288BA629-A7CB-4B83-A469-046EFF187A97@yahoo.com> To whom it may concern, I need someone to help me to develop programs for the following assignments. I have been working on these assignments for a week and a half, and I can't make any progress. I also been dealing with a sick relative, so please help me out immediately. I use the version 3.4.1. Here are the following assignments and what I have so far: Our final exam is a real world problem about efficiency in a warehouse. XYZ Corporation sells products online. The company has a large warehouse in which it stores its inventory of products. Orders are picked, packed and shipped from the warehouse. XYZ Corporation has contracted with you to write a program that will minimize the number of steps that the staff in the warehouse (called ODA's) take in picking the products ordered by customers. The information you will need to complete this assignment are in the following files: [orderNumber, partNumber, quantyNumber, aisleNumber, shelfNumber, binNumber] infile = open("warehouse_data.txt", "r") for x in infile for j in range(3, 6): if (j == 1): temp=a[0:3] a[0:3]=a[3:] a[3:]=temp Thanks, Justin From colbychristensen at hotmail.com Mon Aug 1 16:47:32 2016 From: colbychristensen at hotmail.com (Colby Christensen) Date: Mon, 1 Aug 2016 16:47:32 -0400 Subject: [Tutor] data storage question Message-ID: I'm a novice programmer. I have a decent understanding of algorithms but I don't have a lot of computer science/software engineering experience. As a way to help me learn, I've begun a coordinate geometry program similar to the COGO program developed years ago at MIT. Currently, I store the points in a dictionary in the format point_number : [North, East]. I eventually will add a Z component to the points and possibly a description after I get enough of the horizontal geometry worked through. I would like to be able to save the point table so that I can have multiple projects. My main python script is below. It reads in a text file that contains commands to create/calculate the location of the various points. My question is what is a good method to store the point data outside of python? I eventually will also add the capability to define a baseline that consists of multiple points with some attributes to define relative locations along the baseline (stationing).? I use enthought canopy express with python 2.7.11 on windows 10 64 bit.? """ Coordinate geometry program """ import sys from store_point import store_point from clear_points import clear_points from dump_points import dump_points from redefine import redefine from dist import dist from locate_azimuth import locate_azimuth from locate_bearing import locate_bearing from locate_line import locate_line from line_line_int import line_line_int from parallel_line import parallel_line from arc_line_pts import arc_line_pts from divide_line import divide_line try: ? ? infile = open(raw_input("Enter input file name; name.txt:"),'r') except: ? ? print "Invalid filename" ? ? exit() pt_table = {} cmd_table = {"5":store_point, "7":clear_points, "8":dump_points, ? ? ? ? ? ? ? ? ? ? ? "9":redefine, "10":dist, "11":locate_azimuth, "12":locate_bearing, ? ? ? ? ? ? ? ? ? ? ? "15":locate_line, "18":parallel_line, ? ? ? ? ? ? ? ? ? ? ? "19":line_line_int, "22":arc_line_pts, "40":divide_line} count = 0 for line in infile: ? ? #print line ? ? args = line.split() ? ? cmd = args.pop(0) ? ? if cmd in cmd_table: ? ? ? ? ?func = cmd_table[cmd] ? ? ? ? ?func(pt_table, *args) infile.close() Thanks, Colby From pg042672 at stu.provo.edu Mon Aug 1 15:26:19 2016 From: pg042672 at stu.provo.edu (Palmer Gutke) Date: Mon, 1 Aug 2016 13:26:19 -0600 Subject: [Tutor] Variables Message-ID: I'm trying to write a program w/ python that runs once a day and every time it does it adds 20 to a variable. How do I do this so it doesn't reset the variable to the original value every time I run it? Thanks From steve at pearwood.info Mon Aug 1 22:15:47 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 2 Aug 2016 12:15:47 +1000 Subject: [Tutor] Variables In-Reply-To: References: Message-ID: <20160802021545.GC6608@ando.pearwood.info> On Mon, Aug 01, 2016 at 01:26:19PM -0600, Palmer Gutke wrote: > I'm trying to write a program w/ python that runs once a day and every time > it does it adds 20 to a variable. How do I do this so it doesn't reset the > variable to the original value every time I run it? You have to read the variable from a file saved to disk, add 20, then write back to the file. Does that answer your question? Do you need help reading and writing files? -- Steve From steve at pearwood.info Mon Aug 1 22:14:04 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 2 Aug 2016 12:14:04 +1000 Subject: [Tutor] data storage question In-Reply-To: References: Message-ID: <20160802021403.GB6608@ando.pearwood.info> On Mon, Aug 01, 2016 at 04:47:32PM -0400, Colby Christensen wrote: > I'm a novice programmer. I have a decent understanding of algorithms > but I don't have a lot of computer science/software engineering > experience. As a way to help me learn, I've begun a coordinate > geometry program similar to the COGO program developed years ago at > MIT. Currently, I store the points in a dictionary in the format > point_number : [North, East]. I eventually will add a Z component to > the points and possibly a description after I get enough of the > horizontal geometry worked through. I would like to be able to save > the point table so that I can have multiple projects. For external storage, you have lots of options. Two very common or popular suitable standards are JSON or PList. Suppose you have a point table: pt_table = {25: [30.1, 42.5, 2.8, 'The Shire'], 37: [17.2, 67.2, 11.6, 'Mt Doom'], 84: [124.0, 93.8, 65.2, 'Rivendell'], } I can save that table out to a JSON file, then read it back in, like this: py> import json py> with open('/tmp/data.json', 'w') as f: # save to table to disk ... json.dump(pt_table, f) ... py> with open('/tmp/data.json', 'r') as f: # read it back in ... new_table = json.load(f) ... py> print new_table {u'25': [30.1, 42.5, 2.8, u'The Shire'], u'37': [17.2, 67.2, 11.6, u'Mt Doom'], u'84': [124.0, 93.8, 65.2, u'Rivendell']} You'll see that the JSON format has made two changes to the point table: (1) All strings are Unicode strings instead of "byte strings" (sometimes called "ASCII strings"). (2) The keys were numbers (25, 37, 84) but have now been turned into Unicode strings too. We can advise you how to deal with these changes. Nevertheless, JSON is probably the most common standard used today, and you can see how easy the writing and reading of the data is. Here is an alternative: Plists. Like JSON, Plist requires the keys to be strings, but unlike JSON, it won't convert them for you. So you have to use strings in the first place, or write a quick converter: py> pt_table = dict((str(key), value) for key, value in pt_table.items()) py> print pt_table {'25': [30.1, 42.5, 2.8, 'The Shire'], '37': [17.2, 67.2, 11.6, 'Mt Doom'], '84': [124.0, 93.8, 65.2, 'Rivendell']} Notice that now the keys (which were numbers) are now strings. Now we can write to a plist, and read it back: py> plistlib.writePlist(pt_table, '/tmp/data.plist') py> new_table = plistlib.readPlist('/tmp/data.plist') py> new_table == pt_table True Again, if you need to work with numeric keys, there are ways to work around that. If anything is unclear, please feel free to ask questions on the mailing list, and somebody will try to answer them. -- Steve From dyoo at hashcollision.org Tue Aug 2 00:04:48 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 1 Aug 2016 21:04:48 -0700 Subject: [Tutor] Python Assignment In-Reply-To: <288BA629-A7CB-4B83-A469-046EFF187A97@yahoo.com> References: <288BA629-A7CB-4B83-A469-046EFF187A97@yahoo.com> Message-ID: On Mon, Aug 1, 2016 at 8:18 AM, Justin Korn via Tutor wrote: > To whom it may concern, > I need someone to help me to develop programs for the following assignments. You've asked a few questions earlier: https://mail.python.org/pipermail/tutor/2016-July/109403.html https://mail.python.org/pipermail/tutor/2016-July/109406.html That you have to take care of a sick relative is laudable. But mentioning it multiple times is not helpful: it sounds more like an emotional manipulation. It does not look sincere if you mention it every time you're asking for technical help. That being said, a situation like that *can* be a legitimate, major factor behind why you're having difficulty with the problem. And if that's the case, you *need* to talk with your professor or instructor. We're not the right audience to solve the real problem that you're encountering. Most teachers are often pretty good about considering extraordinary circumstances when setting things like deadlines, and they may give some allowance for your situation. Try talking with your instructor. Looking back at your question: it's possible that English isn't your first language, so you may not realize how poorly the questions are stated. This style of stating a problem statement and asking for a solution is not likely to be fruitful. This is because it looks like you are trying to just get a homework solution without regard to why. In most places of learning, this is against an institution's academic honor code. So try to improve the way you're asking questions, and do reply back if you receive a response, especially if you don't understand the response yet. Alan asked you several question in a previous response: https://mail.python.org/pipermail/tutor/2016-July/109405.html He's actually responded to you multiple times, generously giving you his attention. But it seems like you've ignored him altogether. Are there questions there that you do not understand? Good luck to you. From dyoo at hashcollision.org Tue Aug 2 00:21:39 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 1 Aug 2016 21:21:39 -0700 Subject: [Tutor] data storage question In-Reply-To: <20160802021403.GB6608@ando.pearwood.info> References: <20160802021403.GB6608@ando.pearwood.info> Message-ID: I agree with Steven; JSON is probably one of the most popular formats for saving structured data externally, and it's probably the lightweight approach to use in this situation. By the way, it looks like you're already dealing with a certain file format in your program. In fact, it looks like a simple interpreter, if I understand the program's design. Nice! From dyoo at hashcollision.org Tue Aug 2 00:32:46 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 1 Aug 2016 21:32:46 -0700 Subject: [Tutor] data storage question In-Reply-To: References: <20160802021403.GB6608@ando.pearwood.info> Message-ID: One other thing: you might hear another popular approach is to use the "pickle" module. I don't think it'd be appropriate for your situation because it would be overkill for the problem you're describing. JSON is safer: if you have to choose between JSON and pickle, use JSON. --- More curmudgeon-y details: I'm not a fan of pickle because it does way too much for its own good. It's tied to Python, as opposed to being a language-agnostic file format, so no other tools besides Python know how to parse it well. Furthermore, it has eval() deeply buried within it. That is, it is too powerful for most programmers to use safely. There are a few links you can read if you're interested as to why pickle is probably not what you want. https://blog.nelhage.com/2011/03/exploiting-pickle/ https://lincolnloop.com/blog/playing-pickle-security/ http://www.benfrederickson.com/dont-pickle-your-data/ Just wanted to mention this because it used to be the case where 'pickle' would be a proposed solution to the kind of problem you're encountering. With experience, we can say with more certainty that 'pickle' is a sour pick. From jkornonthecob at yahoo.com Tue Aug 2 01:51:54 2016 From: jkornonthecob at yahoo.com (Justin Korn) Date: Tue, 2 Aug 2016 01:51:54 -0400 Subject: [Tutor] Python Assignment Message-ID: <2E04D2D3-5045-4BB1-93AC-6982D63BB942@yahoo.com> To whom it may concern, I need help on this assignment: Create a new class, SMS_store. The class will instantiate SMS_store objects, similar to an inbox or outbox on a cellphone: my_inbox = SMS_store() This store can hold multiple SMS messages (i.e. its internal state will just be a list of messages). Each message will be represented as a tuple: (has_been_viewed, from_number, time_arrived, text_of_SMS) The inbox object should provide these methods: my_inbox.add_new_arrival(from_number, time_arrived, text_of_SMS) # Makes new SMS tuple, inserts it after other messages # in the store. When creating this message, its # has_been_viewed status is set False. my_inbox.message_count() # Returns the number of sms messages in my_inbox my_inbox.get_unread_indexes() # Returns list of indexes of all not-yet-viewed SMS messages my_inbox.get_message(i) # Return (from_number, time_arrived, text_of_sms) for message[i] # Also change its state to "has been viewed". # If there is no message at position i, return None my_inbox.delete(i) # Delete the message at index i my_inbox.clear() # Delete all messages from inbox Write the class, create a message store object, write tests for these methods, and implement the methods. The following attachment is what I have so far: and I get the error Traceback (most recent call last): File "/Applications/Python Assignments/C15E6_JustinKorn.py", line 58, in my_inbox.get_message(i) NameError: name 'i' is not defined Please help me. Thanks, Justin From joel.goldstick at gmail.com Tue Aug 2 04:50:21 2016 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 2 Aug 2016 04:50:21 -0400 Subject: [Tutor] Variables In-Reply-To: <20160802021545.GC6608@ando.pearwood.info> References: <20160802021545.GC6608@ando.pearwood.info> Message-ID: On Mon, Aug 1, 2016 at 10:15 PM, Steven D'Aprano wrote: > On Mon, Aug 01, 2016 at 01:26:19PM -0600, Palmer Gutke wrote: >> I'm trying to write a program w/ python that runs once a day and every time >> it does it adds 20 to a variable. How do I do this so it doesn't reset the >> variable to the original value every time I run it? > > You have to read the variable from a file saved to disk, add 20, then > write back to the file. > > Does that answer your question? Do you need help reading and writing > files? > > > -- > Steve > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor Also, lookup cron. It will start your program at a certain time you select, every day -- Joel Goldstick http://joelgoldstick.com/blog http://cc-baseballstats.info/stats/birthdays From alan.gauld at yahoo.co.uk Tue Aug 2 05:57:41 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 2 Aug 2016 10:57:41 +0100 Subject: [Tutor] Mail delivery failed: returning message to sender Message-ID: <57A06E95.9030709@yahoo.co.uk> Several of my messages via gmane seem to be bouncing so I'm sending this direct to the tutor list. Apologies if it arrives twice! On 02/08/16 06:51, Justin Korn via Tutor wrote: > Create a new class, SMS_store. > This store can hold multiple SMS messages > (has_been_viewed, from_number, time_arrived, text_of_SMS) > The inbox object should provide these methods: > my_inbox.add_new_arrival(from_number, time_arrived, text_of_SMS) > my_inbox.message_count() > my_inbox.get_unread_indexes() > my_inbox.get_message(i) > my_inbox.delete(i) # Delete the message at index i > my_inbox.clear() # Delete all messages from inbox > The following attachment is what I have so far: Unfortunately this is a text based mailing list so your attachment has been removed by the server. We can't see your code. However we do see the error message this time so we can make a guess... > Traceback (most recent call last): > File "/Applications/Python Assignments/C15E6_JustinKorn.py", line 58, in > my_inbox.get_message(i) > NameError: name 'i' is not defined It says 'i' is not defined. I suspect you have used i as the parameter name in your methods as suggested in the assignment. Then you have tried to call the method and also passed an 'i' in when making the call (as shown in the error message). But the i in the method definition is only visible inside the method code. You must define the value you pass in. Something like: my_inbox = SMS_store() i = 1 # define a value for i print( my_inbox.get_message(i) ) # use your local i # now use the method to print all messages for msg_number in range(my_inbox.message_count()): print( my_inbox.get_message(msg_number) ) 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 bgailer at gmail.com Tue Aug 2 10:38:59 2016 From: bgailer at gmail.com (Bob Gailer) Date: Tue, 2 Aug 2016 10:38:59 -0400 Subject: [Tutor] Python Assignment In-Reply-To: <2E04D2D3-5045-4BB1-93AC-6982D63BB942@yahoo.com> References: <2E04D2D3-5045-4BB1-93AC-6982D63BB942@yahoo.com> Message-ID: On Aug 2, 2016 4:42 AM, "Justin Korn via Tutor" wrote: > > To whom it may concern, > > I need help on this assignment: > > > Create a new class, SMS_store. The class will instantiate SMS_store objects, similar to an inbox or outbox on a cellphone: > my_inbox = SMS_store() > This store can hold multiple SMS messages (i.e. its internal state will just be a list of messages). Each message will be represented as a tuple: > (has_been_viewed, from_number, time_arrived, text_of_SMS) > The inbox object should provide these methods: > my_inbox.add_new_arrival(from_number, time_arrived, text_of_SMS) > # Makes new SMS tuple, inserts it after other messages > # in the store. When creating this message, its > # has_been_viewed status is set False. > > my_inbox.message_count() > # Returns the number of sms messages in my_inbox > > my_inbox.get_unread_indexes() > # Returns list of indexes of all not-yet-viewed SMS messages > > my_inbox.get_message(i) > # Return (from_number, time_arrived, text_of_sms) for message[i] > # Also change its state to "has been viewed". > # If there is no message at position i, return None > > my_inbox.delete(i) # Delete the message at index i > my_inbox.clear() # Delete all messages from inbox > Write the class, create a message store object, write tests for these methods, and implement the methods. > > The following attachment is what I have so far: This mailing list is not forward attachments. Instead copy your code and paste it into the email. > > > and I get the error > > Traceback (most recent call last): > File "/Applications/Python Assignments/C15E6_JustinKorn.py", line 58, in > my_inbox.get_message(i) > NameError: name 'i' is not defined > > Please help me. > > Thanks, > Justin > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From chris9361 at yahoo.com Tue Aug 2 10:59:18 2016 From: chris9361 at yahoo.com (Chris Clifton) Date: Tue, 2 Aug 2016 14:59:18 +0000 (UTC) Subject: [Tutor] Problem with code interating thri a list References: <1876265670.9734194.1470149958574.JavaMail.yahoo.ref@mail.yahoo.com> Message-ID: <1876265670.9734194.1470149958574.JavaMail.yahoo@mail.yahoo.com> Hello Everyone, ?? I have been practicing with strings.? Splitting them, joining them, changing case.? All has been going well but came across a exercise in one of the code practice sites that has you changing the case of different characters in a string.? Anything in upper case is converted to lower case and anything in lower case is converted to upper.? The solution I have created seems to work but I have not been able to figure out how to join the string back together.?? String I'm using is "This Is A Test!" to be changed to "tHIS iS a tEST!".? My Logic:? Since a string is immutable, I converted it to a list to separate out the characters and keep them in order.? Idea is to change the case of the characters in the list then run a join to convert it back to a string. Can you point me in the right direction? the print statements in the code are for my debugging and will be removed in the end. Python 3.5.1 on Windows 10.--------------------------------------------------------------------- # Create a function that will take a string and change the upper case characters to lower # and the lower case characters to upper. # Create a function. def convert(text): ??? print(text) ??? text = list(text) # Convert string to a list to separate/split characters and maintain order. ??? print(text) # Check case and convert to opposite case. ??? for item in text: ??????? if item == item.lower(): ??????????? item = item.upper() ??????????? print(item) ??????? else: ??????????? item = item.lower() ??????????? print(item) # Convert list back into string with .join. ??????? result = "".join(text) ??? print() ??? print(result) ??? return result # Call the function print(convert("This Is A Test!")) ----------------------------------------------------------------------------- Thanks,Chris Clifton From Joaquin.Alzola at lebara.com Tue Aug 2 04:55:54 2016 From: Joaquin.Alzola at lebara.com (Joaquin Alzola) Date: Tue, 2 Aug 2016 08:55:54 +0000 Subject: [Tutor] Variables In-Reply-To: References: <20160802021545.GC6608@ando.pearwood.info> Message-ID: >Also, lookup cron. It will start your program at a certain time you select, every day Linux system "crontab -l" to edit it "crontab -e" Any doubts "man crontab" This email is confidential and may be subject to privilege. If you are not the intended recipient, please do not copy or disclose its content but contact the sender immediately upon receipt. From alan.gauld at yahoo.co.uk Tue Aug 2 19:30:47 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 3 Aug 2016 00:30:47 +0100 Subject: [Tutor] Problem with code interating thri a list In-Reply-To: <1876265670.9734194.1470149958574.JavaMail.yahoo@mail.yahoo.com> References: <1876265670.9734194.1470149958574.JavaMail.yahoo.ref@mail.yahoo.com> <1876265670.9734194.1470149958574.JavaMail.yahoo@mail.yahoo.com> Message-ID: On 02/08/16 15:59, Chris Clifton via Tutor wrote: > My Logic: Since a string is immutable, I converted it to a list That is certainly one approach but your solution has some snags. In fact its probably not necessary unless you want to play with big strings. You could just build a new string from the old one. But as strings get bigger building them incrementally gets more expensive. > the print statements in the code are for my debugging and will be removed in the end. That's good :-) I'll remove them for clarity. > def convert(text): > text = list(text) > for item in text: > if item == item.lower(): > item = item.upper() > else: > item = item.lower() > result = "".join(text) > return result First thing is that changing item does not change the item in the list. You need to use enumerate() to get the index and use that to reassign the list entry. like: for index,item in enumerate(text): ..... text[index] = item.lower() Secondly you probably want to do the join() outside the loop. -- 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 Tue Aug 2 19:52:22 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 2 Aug 2016 16:52:22 -0700 Subject: [Tutor] Problem with code interating thri a list In-Reply-To: <1876265670.9734194.1470149958574.JavaMail.yahoo@mail.yahoo.com> References: <1876265670.9734194.1470149958574.JavaMail.yahoo.ref@mail.yahoo.com> <1876265670.9734194.1470149958574.JavaMail.yahoo@mail.yahoo.com> Message-ID: On Tue, Aug 2, 2016 at 7:59 AM, Chris Clifton via Tutor wrote: > My Logic: Since a string is immutable, I converted it to a list to separate out the characters and keep them in order. Idea is to change the case of the characters in the list then run a join to convert it back to a string. Hi Chris, Yes, that's reasonable. One way you can imagine doing this is "accumulating" a result, rather than doing in-place edits. For example, let's say that I have a list of numbers, and would like a function to return their squares. Toy example: it's meant as a finger exercise. Try writing it first. ... Ok, here's one approach. We *could* do it like this: ############################## def squares(nums): copied = nums[:] for index in range(len(copied)): copied[index] = copied[index]**2 return copied ############################## where we copy the list, and then do in-place edits of each element. Note Alan's warning! If we had tried to do: #################################### def squares(nums): copied = nums[:] for index in range(len(copied)): item = copied[index] item = item**2 ## buggy! return copied #################################### this would not have the effect we want. Why not? If it helps to see what's going on, try the Online Python Tutor visualizer. Compare the "buggy" version: http://www.pythontutor.com/visualize.html#code=def%20squares(nums%29%3A%0A%20%20%20%20copied%20%3D%20nums%5B%3A%5D%0A%20%20%20%20for%20index%20in%20range(len(copied%29%29%3A%0A%20%20%20%20%20%20%20%20item%20%3D%20copied%5Bindex%5D%0A%20%20%20%20%20%20%20%20item%20%3D%20item**2%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%23%20buggy!%0A%20%20%20%20return%20copied%0A%20%20%20%20%0Asquares(%5B1,%202,%203%5D%29&cumulative=false&curInstr=0&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=2&rawInputLstJSON=%5B%5D&textReferences=false versus the one that works: http://www.pythontutor.com/visualize.html#code=def%20squares(nums%29%3A%0A%20%20%20%20copied%20%3D%20nums%5B%3A%5D%0A%20%20%20%20for%20index%20in%20range(len(copied%29%29%3A%0A%20%20%20%20%20%20%20%20copied%5Bindex%5D%20%3D%20copied%5Bindex%5D**2%0A%20%20%20%20return%20copied%0A%20%20%20%20%0Asquares(%5B1,%202,%203%5D%29&cumulative=false&curInstr=0&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=2&rawInputLstJSON=%5B%5D&textReferences=false Do you see and understand the difference? Please feel free to ask questions. *** Another way that gets a similar result is to create a fresh new list and append, ignoring indices altogether: ############################## def squares(nums): result = [] for n in nums: result.append(n**2) return result ############################## This is more preferred because we don't normally have to deal with indices. It works because we can depend on the order in which we're walking over the list elements, and we're appending to the end of the list, so the list of the transformed results will match in lockstep with the order of the input. From alan.gauld at yahoo.co.uk Tue Aug 2 19:55:41 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 3 Aug 2016 00:55:41 +0100 Subject: [Tutor] Problem with code interating thri a list In-Reply-To: References: <1876265670.9734194.1470149958574.JavaMail.yahoo.ref@mail.yahoo.com> <1876265670.9734194.1470149958574.JavaMail.yahoo@mail.yahoo.com> Message-ID: On 03/08/16 00:30, Alan Gauld via Tutor wrote: >> if item == item.lower(): I meant to add that the string islower() method is probably more readable: if item.islower() Also that you could use a list comprehension to do this without converting to a list initially: def conveert(text): result_list = [ch.upper() if ch.islower() else ch.lower() for ch in text] return ''.join(result_list) -- 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 Wed Aug 3 01:33:58 2016 From: martin at linux-ip.net (Martin A. Brown) Date: Tue, 2 Aug 2016 22:33:58 -0700 Subject: [Tutor] Variables In-Reply-To: <20160802021545.GC6608@ando.pearwood.info> References: <20160802021545.GC6608@ando.pearwood.info> Message-ID: Hello Palmer, >> I'm trying to write a program w/ python that runs once a day and every time >> it does it adds 20 to a variable. How do I do this so it doesn't reset the >> variable to the original value every time I run it? > >You have to read the variable from a file saved to disk, add 20, >then write back to the file. > >Does that answer your question? Do you need help reading and >writing files? Steven has given you a pointer in the right direction. Given your description, it sounds like you do not know how to make a program/computer remember the (incrementing) number (value) between program runs. So, to my ear, it sounds like each time your program runs, it starts with a value that is 0 (or nonexistent). So, you need to come up with a strategy for persistence. You need to save the final value of your variable at the end of the program, in short, you need to write that to disk (somehow). The most basic way is to write to a simple file, but....there by dragons. Files disappear. Files become corrupt. Files sometimes change permissions. A file that was there a moment ago may not be any longer. So, code that accesses files needs to be ...risk-averse. With the protections of programming languages, you often do not have to deal in memory with the race conditions that plague access to filesystems. People sometimes use databases, but understanding the general race conditions that come with persistent storage will help you whether you are trying to store values in a database or a filesystem. Below is a Python2 (and Python3) program I have written to demonstrate how to read a variable from a file, increment the variable and store that variable again. It may seem a bit long at first, but I'm hoping from the function names that you can see how a simple function like increment() def increment(var, step): return var + step ...can be a bit trickier when you need to save that data between invocations of the program. The program can be run three different ways: # -- put data in nonexistent file, should end up with a '1' # python proggie.py stored-variable.txt # -- put data in existing file, should end up with '2' # python proggie.py stored-variable.txt # -- put data in existing file, should end up with '22' (2 + 20) # python proggie.py stored-variable.txt 20 # -- increment by 20 # -- increment by 20 and sleep 1 second between read/write cycle # first time should get 42, then 62 .... # python proggie.py stored-variable.txt 20 1 # -- sleep Enjoy, and I hope this little program is instructive, -Martin #! /usr/bin/python # # -- read the contents of a file # stuff into a variable # increment the variable # write to a file from __future__ import print_function import os import sys import errno import time import logging logging.basicConfig(stream=sys.stderr, level=logging.INFO) logger = logging.getLogger(__name__) def increment(var, step): return var + step def read_value(fname): '''open a file, read an integer, close file, return integer args: filename rtrn: an integer (integer representation of file contents) s-fx: ValueError if contents are not an integer IOError if cannot read file ''' with open(fname, 'r') as f: var = int(f.read()) return var def read_value_or_return_default(fname, default=0): '''return value from file or a default if file does not exist (ENOENT) args: filename (and optional default value) rtrn: a value s-fx: catches an ENOENT type of IOError and returns default IOError if permissions or other issue ''' try: var = read_value(fname) logger.info('Read %10d (file %s existed)', var, fname) except IOError as e: if e.errno == errno.ENOENT: var = default logger.info('New value %10d (file %s does not exist)', var, fname) else: raise return var def write_value(fname, var): '''open a file, write contents of a var, close file args: filename rtrn: None s-fx: IOError if cannot write file ''' with open(fname, 'w') as f: f.write(str(var)) logger.info('Stored %10d (file %s tempfile)', var, fname) def ris(fname, step): '''read, increment, store in tempfile, atomically replace permanent file squawk to logging when file has been swapped into place ''' var = read_value_or_return_default(fname, default=0) var = increment(var, step) newfname = fname + '.' + str(time.time()) write_value(newfname, var) os.rename(newfname, fname) logger.info('Swapped %10d (file %s)', var, fname) def cli_ris(fname, step=1): ris(fname, step) return os.EX_OK # -- return success to operating system def cli_loop_ris(fname, step=1, sleeptime=1): '''run forever reading, incrementing and saving variable to a file''' while True: ris(fname, step) time.sleep(sleeptime) return os.EX_OK # -- return success to operating system if __name__ == '__main__': proggie, args = sys.argv[0], sys.argv[1:] if len(args) == 1: fname = args.pop() sys.exit(cli_ris(fname)) elif len(args) == 2: fname, step = args step = int(step) sys.exit(cli_ris(fname, step=step)) elif len(args) == 3: fname, step, sleeptime = args step, sleeptime = int(step), int(sleeptime) sys.exit(cli_loop_ris(fname, step=step, sleeptime=sleeptime)) else: sys.exit('Usage: %s [ []]' % (proggie)) # -- end of file -- Martin A. Brown http://linux-ip.net/ From __peter__ at web.de Wed Aug 3 03:09:24 2016 From: __peter__ at web.de (Peter Otten) Date: Wed, 03 Aug 2016 09:09:24 +0200 Subject: [Tutor] Problem with code interating thri a list References: <1876265670.9734194.1470149958574.JavaMail.yahoo.ref@mail.yahoo.com> <1876265670.9734194.1470149958574.JavaMail.yahoo@mail.yahoo.com> Message-ID: Chris Clifton via Tutor wrote: > I have been practicing with strings. Splitting them, joining them, > changing case. All has been going well but came across a exercise in one > of the code practice sites that has you changing the case of different > characters in a string. Anything in upper case is converted to lower case > and anything in lower case is converted to upper. The solution I have > created seems to work but I have not been able to figure out how to join > the string back together. String I'm using is "This Is A Test!" to be > changed to "tHIS iS a tEST!". You'll learn more if you try to understand the approaches shown in Danny's and Alan's posts, but there is also a ready-to-use string method: >>> "This Is A Test!".swapcase() 'tHIS iS a tEST!' I have no idea where you'd need such a method other than to "cheat" in exercises like the one you saw... There is also a method to make arbitrary replacements that is much more useful for solving real-world problems: >>> replacements = str.maketrans({"?": "Ue", "?": "ue"}) >>> "?bel w?tet der G?rtelw?rger!".translate(replacements) 'Uebel wuetet der Guertelwuerger!' >>> import string >>> swap = str.maketrans(string.ascii_uppercase + string.ascii_lowercase, string.ascii_lowercase + string.ascii_uppercase) >>> "This Is A Test!".translate(swap) 'tHIS iS a tEST!' From jkornonthecob at yahoo.com Wed Aug 3 01:34:30 2016 From: jkornonthecob at yahoo.com (Justin Korn) Date: Wed, 3 Aug 2016 01:34:30 -0400 Subject: [Tutor] Python Assignment Message-ID: <1B801004-ACFE-43C5-8950-95A81A318189@yahoo.com> To whom it may concern, I need help creating a program for the following assignment: XYZ Corporation sells products online. The company has a large warehouse in which it stores its inventory of products. Orders are picked, packed and shipped from the warehouse. XYZ Corporation has contracted with you to write a program that will minimize the number of steps that the staff in the warehouse (called ODA's) take in picking the products ordered by customers. The information you will need to complete this assignment are in the following files: Specifications: CTIM285_Summer_2016_FinalExam.pdf Warehouse Map: WarehouseImage.pdf Data for Analysis: warehouse_data_final_exam_Python.txt Data for Analysis is saved in this order on each line of the file: [orderNumber, partNumber, quantyNumber, aisleNumber, shelfNumber, binNumber] This is what I have so far: infile = open("warehouse_data.txt", "r") class Order(): def __init__(self, order_number, line_items): self.order_number = order_number line_items = line_items class LineItem(): def __init__(self, orderNumber, partNumber, quantityNumber, aisleNumber, shelfNumber, binNumber): self.orderNumber = orderNumber self.partNumber = partNumber self.quantityNumber = quantityNumber self.aisleNumber = aisleNumber self.shelfNumber = shelfNumber binNumber = binNumber Thanks, Justin From Joaquin.Alzola at lebara.com Tue Aug 2 03:51:25 2016 From: Joaquin.Alzola at lebara.com (Joaquin Alzola) Date: Tue, 2 Aug 2016 07:51:25 +0000 Subject: [Tutor] Variables In-Reply-To: References: Message-ID: >I'm trying to write a program w/ python that runs once a day and every time it does it adds 20 to a variable. How do I do this so it doesn't reset the variable to the original value every time I run it? You can output the value to a file? Then re-read the file once a day and assign that value to the variable. This email is confidential and may be subject to privilege. If you are not the intended recipient, please do not copy or disclose its content but contact the sender immediately upon receipt. From alan.gauld at yahoo.co.uk Wed Aug 3 05:00:40 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 3 Aug 2016 10:00:40 +0100 Subject: [Tutor] Python Assignment In-Reply-To: <1B801004-ACFE-43C5-8950-95A81A318189@yahoo.com> References: <1B801004-ACFE-43C5-8950-95A81A318189@yahoo.com> Message-ID: On 03/08/16 06:34, Justin Korn via Tutor wrote: > Data for Analysis is saved in this order on each line of the file: > [orderNumber, partNumber, quantyNumber, aisleNumber, shelfNumber, binNumber] > > > This is what I have so far: > > infile = open("warehouse_data.txt", "r") > > class Order(): > def __init__(self, order_number, line_items): > self.order_number = order_number > line_items = line_items You use self for the order_number but not for the line_items? Also, are you really planning on building a collection of line items per order before you create the order? Or might it be better to create the order for the first identified line item and then add() subsequent line items as you find them? Just a thought... > class LineItem(): > def __init__(self, orderNumber, partNumber, quantityNumber, aisleNumber, shelfNumber, binNumber): > self.orderNumber = orderNumber > self.partNumber = partNumber > self.quantityNumber = quantityNumber > self.aisleNumber = aisleNumber > self.shelfNumber = shelfNumber > binNumber = binNumber And similarly you do not use self for bin_number In each case the values without self will be thrown away when the __init__() method exits. Other than that issue it's a fair start in that you now have two classes that can be used to store the data in the file. Your next step is presumably to read the file into objects of these classes. Finally, I'm guessing you'll want to sort the line items into groups based on their location so that the warehouse pickers don't need to visit the same area twice. I'm not clear whether that should be limited per order or to all the line items per batch and the collected items assembled into orders later. I'm assuming that the items are picked by order... but the assignment doesn't seem to specify. -- 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 Wed Aug 3 08:26:18 2016 From: colbychristensen at hotmail.com (Colby Christensen) Date: Wed, 3 Aug 2016 08:26:18 -0400 Subject: [Tutor] data storage question In-Reply-To: <20160802021403.GB6608@ando.pearwood.info> References: , <20160802021403.GB6608@ando.pearwood.info> Message-ID: ---------------------------------------- > Date: Tue, 2 Aug 2016 12:14:04 +1000 > From: steve at pearwood.info > To: tutor at python.org > Subject: Re: [Tutor] data storage question > > On Mon, Aug 01, 2016 at 04:47:32PM -0400, Colby Christensen wrote: > >> I'm a novice programmer. I have a decent understanding of algorithms >> but I don't have a lot of computer science/software engineering >> experience. As a way to help me learn, I've begun a coordinate >> geometry program similar to the COGO program developed years ago at >> MIT. Currently, I store the points in a dictionary in the format >> point_number : [North, East]. I eventually will add a Z component to >> the points and possibly a description after I get enough of the >> horizontal geometry worked through. I would like to be able to save >> the point table so that I can have multiple projects. > > For external storage, you have lots of options. Two very common or > popular suitable standards are JSON or PList. > > Suppose you have a point table: > > pt_table = {25: [30.1, 42.5, 2.8, 'The Shire'], > 37: [17.2, 67.2, 11.6, 'Mt Doom'], > 84: [124.0, 93.8, 65.2, 'Rivendell'], > } > > I can save that table out to a JSON file, then read it back in, like > this: > > py> import json > py> with open('/tmp/data.json', 'w') as f: # save to table to disk > ... json.dump(pt_table, f) > ... > py> with open('/tmp/data.json', 'r') as f: # read it back in > ... new_table = json.load(f) > ... > py> print new_table > {u'25': [30.1, 42.5, 2.8, u'The Shire'], u'37': [17.2, 67.2, 11.6, u'Mt > Doom'], u'84': [124.0, 93.8, 65.2, u'Rivendell']} > > > You'll see that the JSON format has made two changes to the point table: > > (1) All strings are Unicode strings instead of "byte strings" (sometimes > called "ASCII strings"). > > (2) The keys were numbers (25, 37, 84) but have now been turned into > Unicode strings too. Based on both replies I got, JSON is what I will use. I do need the keys in the dictionary to be numerals, specifically they are integers.? I believe after I load a stored pt_table, I can use this script to convert the keys back to integers. pt_table = dict((int(key), value) for key, value in pt_table.items()) Please correct me if there is something wrong with that or if there's something else I should now about converting the keys to ints after reading the stored data. Thanks for your input! > > We can advise you how to deal with these changes. Nevertheless, JSON is > probably the most common standard used today, and you can see how easy > the writing and reading of the data is. > > Here is an alternative: Plists. Like JSON, Plist requires the keys to be > strings, but unlike JSON, it won't convert them for you. So you have to > use strings in the first place, or write a quick converter: > > py> pt_table = dict((str(key), value) for key, value in > pt_table.items()) > py> print pt_table > {'25': [30.1, 42.5, 2.8, 'The Shire'], '37': [17.2, 67.2, 11.6, 'Mt > Doom'], '84': [124.0, 93.8, 65.2, 'Rivendell']} > > > Notice that now the keys (which were numbers) are now strings. Now we > can write to a plist, and read it back: > > py> plistlib.writePlist(pt_table, '/tmp/data.plist') > py> new_table = plistlib.readPlist('/tmp/data.plist') > py> new_table == pt_table > True > > > Again, if you need to work with numeric keys, there are ways to work > around that. > > If anything is unclear, please feel free to ask questions on the mailing > list, and somebody will try to answer them. > > > -- > Steve > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From tripytrev at hotmail.com Wed Aug 3 07:25:46 2016 From: tripytrev at hotmail.com (Trevor H) Date: Wed, 3 Aug 2016 11:25:46 +0000 Subject: [Tutor] Django SQLite data as Pie chart Message-ID: Hi all, I am trying to create a website that could dynamically get data from an SQLite3 database and create it into a website. I know how to install Django, tell it to use an existing database (in setting.py) but I'm not sure about how I would go plotting the data into a pie chart from here on? The values under the tables get populated with a PHP script that gets the information needed to analyse. Example of the tables is as follows: Name: Oses Sqlite3: create table oses (id integer primary key, name text) Hope someone would be able to shine some light on this for me. Thanks TJ Sent from my iPhone From alan.gauld at yahoo.co.uk Wed Aug 3 13:24:06 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 3 Aug 2016 18:24:06 +0100 Subject: [Tutor] Django SQLite data as Pie chart In-Reply-To: References: Message-ID: On 03/08/16 12:25, Trevor H wrote: > I am trying to create a website that could dynamically get data > ... but I'm not sure about how I would go plotting the data > into a pie chart ... There are basically three ways to tackle this. 1) Create the chart as an image on the server and then upload it as a link from the HTML web page. You could include an image map to give a basic form of user interaction with the data. The image can be created using libraries such as Pillow or matplotlib or even the humble turtle. 2) Create the chart as an SVG graphic on the server and upload to the browser as part of the HTML for display. You can associate click events with Javascript functions to provide interaction. 3) Make the raw data available on the server4 and get a Javascript function in the HTML to fetch it as needed and generate the imagery directly in the browsers DOM. (I believe there are JS libraries to assist in this but I've never used them) They are arranged in order of simplicity. They are also arranged in reverse order from the point of flexibility and user interaction. As ever, it's a trade off. -- 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 jf_byrnes at comcast.net Wed Aug 3 15:49:44 2016 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Wed, 3 Aug 2016 14:49:44 -0500 Subject: [Tutor] Regex/Raw String confusion Message-ID: I am reading Automate The Boring Stuff With Python. In the chapter on Regular Expressions he talks about the python escape character being a '\' and regex using alot of backslashes. Then he says, However, by putting an r before the first quote of the string value, you can mark the string as a raw sting, which does not escape characters. He give this example: import re phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') mo = phoneNumRegex.search('My number is 415-555-4242.') print('Phone number found: ' + mo.group()) A couple of pages later he talks about parentheses having special meaning in regex and what to do if they are in your text. In this case, you need to escape the ( and ) characters with a backslash. The \( and \) escape characters in the raw string passed to re.compile() will match actual parenthesis characters. import re phoneNumRegex = re.compile(r'(\(\d\d\d\)) (\d\d\d-\d\d\d\d)') mo = phoneNumRegex.search('My phone number is: (415) 555-4242.') print(mo.group(1)) print() print(mo.group(2)) Both examples work, but one place he says you can't escape raw strings and the other he says you can. What am I missing here? Regards, Jim From jkornonthecob at yahoo.com Wed Aug 3 13:58:25 2016 From: jkornonthecob at yahoo.com (Justin Korn) Date: Wed, 3 Aug 2016 13:58:25 -0400 Subject: [Tutor] Python Assignment Message-ID: <8BA2D96D-C2A9-4406-81DE-0A2375C0B7A6@yahoo.com> To whom it may concern, I need someone to make changes to the following assignment: XYZ Corporation sells products online. The company has a large warehouse in which it stores its inventory of products. Orders are picked, packed and shipped from the warehouse. XYZ Corporation has contracted with you to write a program that will minimize the number of steps that the staff in the warehouse (called ODA's) take in picking the products ordered by customers. The information you will need to complete this assignment are in the following files: Specifications: CTIM285_Summer_2016_FinalExam.pdf Warehouse Map: WarehouseImage.pdf Data for Analysis: warehouse_data_final_exam_Python.txt Data for Analysis is saved in this order on each line of the file: [orderNumber, partNumber, quantyNumber, aisleNumber, shelfNumber, binNumber] This is what I have so far: def load_file(): with open("warehouse_data.txt") as infile: for line in infile: data = process_line(line) class Order(): def __init__(self, order_number): self.order_number = order_number def add_item(): order = [] order.append() def sort_key(): all_keys = [] for item in self.order_number: all_keys.append(item.sort_key()) return min(all_keys) class LineItem(): def __init__(self, orderNumber, partNumber, quantityNumber, aisleNumber, shelfNumber, binNumber): self.orderNumber = orderNumber self.partNumber = partNumber self.quantityNumber = quantityNumber self.aisleNumber = aisleNumber self.shelfNumber = shelfNumber self.binNumber = binNumber def sort_key(): p = (self.aisleNumber, self.shelfNumber, self.binNumber) for i in p: p.sort(i.sort_key()) return(self.aisleNumber, self.shelfNumber * -1, self.binNumber) def __str__(self): return("{} {} {} {} {} {}".format(self.aisleNumber, self.shelfNumber, self.binNumber, self.orderNumber, self.partNumber, self.quantityNumber)) Thanks, Justin From alan.gauld at yahoo.co.uk Wed Aug 3 19:14:00 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 4 Aug 2016 00:14:00 +0100 Subject: [Tutor] Python Assignment In-Reply-To: <8BA2D96D-C2A9-4406-81DE-0A2375C0B7A6@yahoo.com> References: <8BA2D96D-C2A9-4406-81DE-0A2375C0B7A6@yahoo.com> Message-ID: On 03/08/16 18:58, Justin Korn via Tutor wrote: > This is what I have so far: OK, This is starting to look a bit random. You need to slow down and work through what is happening in each method and especially what data is being passed around where. At the moment it makes no sense whatsoever. > def load_file(): > with open("warehouse_data.txt") as infile: > for line in infile: > data = process_line(line) Where is process_line defined? And what happens to data? At the moment its a local variable that disappears when load_file terminates. > class Order(): > def __init__(self, order_number): > self.order_number = order_number > > def add_item(): > order = [] > order.append() What do you think this does? It takes no input values and appends nothing(*) to a list that is deleted at the end of the function. I'm pretty certain that's not what you want. (*) In fact append will error because it needs an input value. > def sort_key(): > all_keys = [] > for item in self.order_number: > all_keys.append(item.sort_key()) > return min(all_keys) You are looping over self.order_number. What kind of data is order_number? What kind of data will item be? Does item have a sort_key() method? Also neither function has a self parameter so will not be usable methods of the class. > class LineItem(): > def __init__(self, orderNumber, partNumber, quantityNumber, aisleNumber, shelfNumber, binNumber): > self.orderNumber = orderNumber > self.partNumber = partNumber > self.quantityNumber = quantityNumber > self.aisleNumber = aisleNumber > self.shelfNumber = shelfNumber > self.binNumber = binNumber > > def sort_key(): > p = (self.aisleNumber, self.shelfNumber, self.binNumber) > for i in p: > p.sort(i.sort_key()) > return(self.aisleNumber, self.shelfNumber * -1, self.binNumber) Look at what the loop is doing. It iterates over three values and tries to sort the tuple p based on a sort_key method of each value. But do those values have a sort_key() method?. And does sorting p achieve anything? I assume you didn't try running this code since it would result in errors. You need to sort out the data types and use them consistently. -- 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 Aug 3 19:21:22 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 4 Aug 2016 00:21:22 +0100 Subject: [Tutor] Regex/Raw String confusion In-Reply-To: References: Message-ID: On 03/08/16 20:49, Jim Byrnes wrote: > Regular Expressions he talks about the python escape character being a > '\' and regex using alot of backslashes. In effect there are two levels of escape character, python and the regex processor. Unfortunately they both use backslash! Python applies its level of escape first then passes the modified string to the regex engine which processes the remaining regex escapes. It is confusing and one reason you should avoid complex regexes if possible. > by putting an r before the first quote of the string value, you can > mark the string as a raw sting, which does not escape characters. This avoids python trying to process the escapes. The raw string is then passed to the regex which will process the backslash escapes that it recognises. > A couple of pages later he talks about parentheses having special > meaning in regex and what to do if they are in your text. > > In this case, you need to escape the ( and ) characters with a > backslash. The \( and \) escape characters in the raw string passed to > re.compile() will match actual parenthesis characters. These are regex escape characters. If you did not have the r in front you would need to double escape them: \\( and \\) So by using the raw string you avoid the initial layer of escaping by the python interpreter and only need to worry about the regex parser - which is more than enough for anyone to worry about! -- 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 jf_byrnes at comcast.net Wed Aug 3 21:54:50 2016 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Wed, 3 Aug 2016 20:54:50 -0500 Subject: [Tutor] Regex/Raw String confusion In-Reply-To: References: Message-ID: On 08/03/2016 06:21 PM, Alan Gauld via Tutor wrote: > On 03/08/16 20:49, Jim Byrnes wrote: > >> Regular Expressions he talks about the python escape character being a >> '\' and regex using alot of backslashes. > > In effect there are two levels of escape character, python and > the regex processor. Unfortunately they both use backslash! > Python applies its level of escape first then passes the > modified string to the regex engine which processes the > remaining regex escapes. It is confusing and one reason > you should avoid complex regexes if possible. > >> by putting an r before the first quote of the string value, you can >> mark the string as a raw sting, which does not escape characters. > > This avoids python trying to process the escapes. > The raw string is then passed to the regex which will > process the backslash escapes that it recognises. > >> A couple of pages later he talks about parentheses having special >> meaning in regex and what to do if they are in your text. >> >> In this case, you need to escape the ( and ) characters with a >> backslash. The \( and \) escape characters in the raw string passed to >> re.compile() will match actual parenthesis characters. > > These are regex escape characters. If you did not have the r in front > you would need to double escape them: > > \\( and \\) > > So by using the raw string you avoid the initial layer of > escaping by the python interpreter and only need to worry > about the regex parser - which is more than enough for anyone > to worry about! > Ok thanks. The book did not mention 2 levels of escaping. With what you told me in mind I reread that section and the book may have hinted at it but I would have never realized it without knowing what you just said. Is the second example a special case? phoneNumRegex = re.compile(r'(\(\d\d\d\)) (\d\d\d-\d\d\d\d)') mo = phoneNumRegex.search('My phone number is: (415) 555-4242.') print(mo.group(1)) print() print(mo.group(2)) I ask because it produces the same results with or without the ' r '. Regards, Jim From dyoo at hashcollision.org Wed Aug 3 22:05:23 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 3 Aug 2016 19:05:23 -0700 Subject: [Tutor] data storage question In-Reply-To: References: <20160802021403.GB6608@ando.pearwood.info> Message-ID: > Based on both replies I got, JSON is what I will use. > > I do need the keys in the dictionary to be numerals, specifically they are integers. > > I believe after I load a stored pt_table, I can use this script to convert the keys back to integers. > > pt_table = dict((int(key), value) for key, value in pt_table.items()) > > Please correct me if there is something wrong with that or if there's something else I should now about converting the keys to ints after reading the stored data. Hi Colby, Yes, this looks ok to me. I think we can also express it as a dictionary comprehension. (https://docs.python.org/3/tutorial/datastructures.html#dictionaries) pt_table = {int(key): value for key, value in pt_table.items()} I think the dictionary comprehension approach is slightly more idiomatic, but what you've got looks ok too. From david at graniteweb.com Thu Aug 4 00:29:36 2016 From: david at graniteweb.com (David Rock) Date: Wed, 3 Aug 2016 23:29:36 -0500 Subject: [Tutor] Regex/Raw String confusion In-Reply-To: References: Message-ID: <3648EED8-8BC4-4676-BA77-B221D93FBD59@graniteweb.com> > On Aug 3, 2016, at 20:54, Jim Byrnes wrote: > > Is the second example a special case? > > phoneNumRegex = re.compile(r'(\(\d\d\d\)) (\d\d\d-\d\d\d\d)') > mo = phoneNumRegex.search('My phone number is: (415) 555-4242.') > print(mo.group(1)) > print() > print(mo.group(2)) > > I ask because it produces the same results with or without the ' r '. No, it?s not a special case. The backslashes in this case are a way to simplify what could otherwise be very unwieldy. There are several of these character groups (called special sequences in the documentation). For example, \s means any whitespace character, \w means any alphanumeric or underscore, \d means any digit, etc. You can look them up in the docs: https://docs.python.org/2/library/re.html ? David Rock david at graniteweb.com From cjackt05 at gmail.com Wed Aug 3 21:41:31 2016 From: cjackt05 at gmail.com (CJ) Date: Wed, 3 Aug 2016 18:41:31 -0700 Subject: [Tutor] Help Message-ID: Hi, I?m coding a game for fun and i keep trying to run it but this keeps showing up: traceback (most recent call last): File "/Volumes/name/box move thing(wed).py", line 13, in player_img = PhotoImage(file="astronaut.png") File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py", line 3394, in __init__ Image.__init__(self, 'photo', name, cnf, master, **kw) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py", line 3350, in __init__ self.tk.call(('image', 'create', imgtype, name,) + options) _tkinter.TclError: couldn't open "astronaut.png": no such file or directory Even though I have a file named ?astronaut.png? I?ve tried a lot of things if I could be helped that would be awesome. Thanks, Anonymous From alan.gauld at yahoo.co.uk Thu Aug 4 04:27:34 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 4 Aug 2016 09:27:34 +0100 Subject: [Tutor] Regex/Raw String confusion In-Reply-To: References: Message-ID: On 04/08/16 02:54, Jim Byrnes wrote: > Is the second example a special case? > > phoneNumRegex = re.compile(r'(\(\d\d\d\)) (\d\d\d-\d\d\d\d)') > > I ask because it produces the same results with or without the ' r '. That's because in this specific case there are no conflicts between the regex escape codes and the Python escape codes. In other words Python does not treat '\(' or '\d' as special characters so it doesn't change the string passed to the regex. (It would be a different story if you had used, say, a '\x' or '\n' or '\b' in the regex.) In general you should proceed with caution and assume that there might be a Python escape sequence lurking in the regex and use raw just in case. -- 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 __peter__ at web.de Thu Aug 4 04:55:09 2016 From: __peter__ at web.de (Peter Otten) Date: Thu, 04 Aug 2016 10:55:09 +0200 Subject: [Tutor] Help References: Message-ID: CJ wrote: > Hi, > I?m coding a game for fun and i keep trying to run it but this keeps > showing up: > traceback (most recent call last): > File "/Volumes/name/box move thing(wed).py", line 13, in > player_img = PhotoImage(file="astronaut.png") > File > "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py", > line 3394, in __init__ > Image.__init__(self, 'photo', name, cnf, master, **kw) > File > "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py", > line 3350, in __init__ > self.tk.call(('image', 'create', imgtype, name,) + options) > _tkinter.TclError: couldn't open "astronaut.png": no such file or > directory > > Even though I have a file named ?astronaut.png? I?ve tried a lot of things > if I could be helped that would be awesome. Print the working directory before the line creating the image: import os os.print(os.getcwd()) > player_img = PhotoImage(file="astronaut.png") Chances are that "astronaut.png" is in another directory. If so you have to provide the path to that directory, e. g. player_img = PhotoImage(file="images/astronaut.png") If the image is in the same directory as the script you can construct the path with import os image_folder = os.path.dirname(__file__) ... player_img = PhotoImage(file=os.path.join(image_folder, "astronaut.png")) From alan.gauld at yahoo.co.uk Thu Aug 4 04:55:49 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 4 Aug 2016 09:55:49 +0100 Subject: [Tutor] SQLite Django In-Reply-To: References: Message-ID: <57A30315.7050108@yahoo.co.uk> Forwarding to list. Please use REplyAll when responding to tutor messages. On 04/08/16 09:19, Trevor H wrote: > Hi Alan, > > Thank you for the reply. I'll try show the graphic as a website. Would > I have to make the data entries as a model in Django? > I'm not a Django expert so don;t know where you would put the code to generate the image. But based on usual MVC practice I'd assume it would be a model somewhere. However the image itself will just be a file on the server and would be stored in the same place as any other images such as logos etc. The key difference is that the image filename will need to be injected into your HTML template somehow and I assume you do that by linking a model variable to a marker in the template. Again I'm no Django expert I've only watched a few YouTube tutorials... > I'm new to this sorry for the newbie question. Newbie questions are what we are here for. Although Django specific issues might be better addressed to the Django list. But we will usually have a pop at them if they are not too Django specific. > I have to link all my data like so to give a plot. Just don't know how. > > SQLi command to join my tables: > To join all tables: > SELECT devices.id AS id, > macs.address AS mac, > oses.name AS os, > browsers.name AS browser > FROM devices > JOIN macs ON devices.mac = macs.id > JOIN oses ON devices.os = oses.id > JOIN browsers ON devices.browser = browsers.id; > Getting the data and generating the plot are two separate issues. You can experiment with the SQL using the SQLIte interpreter till you have a query that delivers what you need. If you don't already have it installed I strongly recommend doing so. Without knowing what you're trying to plot and what your schema looks like I can't really comment on the SQL -- 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 jf_byrnes at comcast.net Thu Aug 4 09:23:46 2016 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Thu, 4 Aug 2016 08:23:46 -0500 Subject: [Tutor] Regex/Raw String confusion In-Reply-To: References: Message-ID: On 08/04/2016 03:27 AM, Alan Gauld via Tutor wrote: > On 04/08/16 02:54, Jim Byrnes wrote: > >> Is the second example a special case? >> >> phoneNumRegex = re.compile(r'(\(\d\d\d\)) (\d\d\d-\d\d\d\d)') >> >> I ask because it produces the same results with or without the ' r '. > > That's because in this specific case there are no conflicts between > the regex escape codes and the Python escape codes. In other > words Python does not treat '\(' or '\d' as special characters > so it doesn't change the string passed to the regex. > (It would be a different story if you had used, say, a > '\x' or '\n' or '\b' in the regex.) > > In general you should proceed with caution and assume that > there might be a Python escape sequence lurking in the regex > and use raw just in case. > Ok, thanks again. I understand what is going on now. Regards, Jim From tmatsumoto at gmx.net Sat Aug 6 12:32:47 2016 From: tmatsumoto at gmx.net (Tutor) Date: Sat, 6 Aug 2016 19:32:47 +0300 Subject: [Tutor] =?utf-8?q?interesting?= Message-ID: <00006ef5cdc9$9baa616f$57774eeb$@gmx.net> Hey friend, Just look at that interesting stuff, I love it! I think you're gonna like it too, take a look here Warmly, Tutor From mittalrishabh at gmail.com Sat Aug 6 23:22:08 2016 From: mittalrishabh at gmail.com (rishabh mittal) Date: Sat, 6 Aug 2016 20:22:08 -0700 Subject: [Tutor] How to use function with default values ? Message-ID: Hi I am new to python and come from C language background. I couldn't able to understand this >>> def f(a, L=[]): ... L.append(a) ... return L ... >>> print(f(1)) [1] >>> print(f(2)) [1, 2] >>> print(f(3)) [1, 2, 3] >>> def f(a, L=10): ... L=10+a ... return L ... >>> print(f(1)) 11 >>> print(f(1)) 11 In the first example if i call function f then it looks like L is treated as a static object which is not reinitialized in the subsequent function calls. But in the second example, it seems to be reinitialized in the subsequent calls. Can anyone explain this or point me to the discussion if it is asked before. Thanks Rishabh Mittal From alan.gauld at yahoo.co.uk Sun Aug 7 04:19:11 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 7 Aug 2016 09:19:11 +0100 Subject: [Tutor] How to use function with default values ? In-Reply-To: References: Message-ID: On 07/08/16 04:22, rishabh mittal wrote: > I am new to python and come from C language background. I couldn't able to > understand this > > >>> def f(a, L=[]): > ... L.append(a) > ... return L > ... > >>>> print(f(1)) > [1] > >>>> print(f(2)) > [1, 2] >>>> def f(a, L=10): > ... L=10+a > ... return L > >>>> print(f(1)) > 11 > >>>> print(f(1)) > 11 > In the first example if i call function f then it looks like L is treated > as a static object which is not reinitialized in the subsequent function > calls. That's more or less correct. The default object is created at definition time and that same object is used for any invocation of the function that does not provide an explicit value. > > But in the second example, it seems to be reinitialized in the subsequent > calls. Can anyone explain this or point me to the discussion if it is > asked before. The issue is immutability. In the first case you create a default object which is a list. Lists are mutable so you can add items to it. In the second case you create a default integer object which is immutable. (And it's important to remember that it is an integer object not an integer placeholder or reference.) So in the first case when you do L.append(a) you add an item to the list But in the second case when you do L = 10+a You create a new integer object that *replaces* the default. The default object is still there ready to be used next time you call the function. It's just the local variable L that has its value changed. And in case you are wondering, it would not have made any difference if you had done L = L+a # or L += a The effect would be the same. The immutable initial value would be replaced by a new integer object. -- 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 cs at zip.com.au Sun Aug 7 20:16:05 2016 From: cs at zip.com.au (cs at zip.com.au) Date: Mon, 8 Aug 2016 10:16:05 +1000 Subject: [Tutor] How to use function with default values ? In-Reply-To: References: Message-ID: <20160808001605.GA26563@cskk.homeip.net> On 07Aug2016 09:19, Alan Gauld wrote: >On 07/08/16 04:22, rishabh mittal wrote: >> I am new to python and come from C language background. I couldn't able to >> understand this >> >>> def f(a, L=[]): >> ... L.append(a) >> ... return L >>>>> print(f(1)) >> [1] >>>>> print(f(2)) >> [1, 2] [...] >> In the first example if i call function f then it looks like L is treated >> as a static object which is not reinitialized in the subsequent function >> calls. > >That's more or less correct. The default object is created at definition >time and that same object is used for any invocation of the function >that does not provide an explicit value. Just a further addition to Alan's explaination: because the default values are defined at the same time that the function is defined, the common idom in Python for default values looks like this: def f(a, L=None): if L is None: L = [] ... Which binds L to a new list every time the function is called (if L is not presupplied). The "None" is not particularly special; like the number 10 it is immutable, so defining it the once at function definition time is not an issue. It is simply an immutable sentinel value representing "not a normal valid value", and the common choice in Python. Cheers, Cameron Simpson From parvcy at gmail.com Tue Aug 9 12:43:26 2016 From: parvcy at gmail.com (Cyrus Parvereshi) Date: Tue, 9 Aug 2016 09:43:26 -0700 Subject: [Tutor] Problem with graphics.py Message-ID: Hi! I'm starting out with programming by self-studying python with a textbook used at my university. I came to a chapter that introduced object oriented programming with graphics tools like GraphWin and Point. However, even though I downloaded the author's graphics.py file from his website and put it in the same folder as the IDLE interpreter, Python command prompt, and every other python program, I still cannot use the module. Every single time I attempt to use a command like "import graphics" or "from graphics import * " it gives an error that there is no module called 'graphics.py. I would like to know how to fix this issue so that I can access the graphics module. Thank you! -Cyrus Parvereshi From steve at pearwood.info Tue Aug 9 13:31:25 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 10 Aug 2016 03:31:25 +1000 Subject: [Tutor] Problem with graphics.py In-Reply-To: References: Message-ID: <20160809173124.GA26300@ando.pearwood.info> On Tue, Aug 09, 2016 at 09:43:26AM -0700, Cyrus Parvereshi wrote: > Hi! I'm starting out with programming by self-studying python with a > textbook used at my university. I came to a chapter that introduced object > oriented programming with graphics tools like GraphWin and Point. However, > even though I downloaded the author's graphics.py file from his website and > put it in the same folder as the IDLE interpreter, Python command prompt, > and every other python program, I still cannot use the module. Every single > time I attempt to use a command like "import graphics" or "from graphics > import * " it gives an error that there is no module called 'graphics.py. What do you mean, "the same folder as the IDLE interpreter"? IDLE is not an interpreter. Please give us some more information so we can help you: - What operating system are you using? Linus? Mac? Windows? - What version of Python are you using? - Where did you put the graphics.py file? *Exactly*. Please don't take a screenshot, just copy and paste (or type) the *EXACT* name of the folder. - From inside IDLE, please run this code and COPY AND PASTE (no screenshots) the output: import sys print(sys.path) > I would like to know how to fix this issue so that I can access the > graphics module. The technical answer is "put the graphics.py file somewhere in the Python path, and make sure it is readable". For an expert, that's all the answer they will need. Don't feel bad if you don't know how to do this -- you're only starting. Answer the questions above, and we'll help with the rest. (Remember to reply to the mailing list, not to me privately.) -- Steve From michael.selik at gmail.com Tue Aug 9 12:55:29 2016 From: michael.selik at gmail.com (Michael Selik) Date: Tue, 09 Aug 2016 16:55:29 +0000 Subject: [Tutor] Problem with graphics.py In-Reply-To: References: Message-ID: On Tue, Aug 9, 2016 at 12:51 PM Cyrus Parvereshi wrote: > Hi! I'm starting out with programming by self-studying python with a > textbook used at my university. I came to a chapter that introduced object > oriented programming with graphics tools like GraphWin and Point. However, > even though I downloaded the author's graphics.py file from his website and > put it in the same folder as the IDLE interpreter, Python command prompt, > and every other python program, I still cannot use the module. Every single > time I attempt to use a command like "import graphics" or "from graphics > import * " it gives an error that there is no module called 'graphics.py. > > I would like to know how to fix this issue so that I can access the > graphics module. > Do you mind running the following commands from the python shell? py> import os py> os.getcwd() '/Users/mike' py> sorted(os.listdir('.')) ['.Trash', 'Applications', 'Desktop', ...] This will show us what location your python interpreter has as the "current working directory" and whether or not the "graphics.py" file is present in that directory. From g.willgoose at telluricresearch.com Wed Aug 10 00:27:42 2016 From: g.willgoose at telluricresearch.com (Garry Willgoose) Date: Wed, 10 Aug 2016 14:27:42 +1000 Subject: [Tutor] command to determine of python 32 or 64 bit? Message-ID: I have a number of binary libraries that are dependent on whether the precompiled python distribution (eg. Enthought, ActiveState, etc) in which they are installed are compiled with 32 or 64 bit. Is there any reliable way to determine at run time whether a python distribution is 32 or 64 bit? If I can determine at runtime then I can set the path for loading of my libraries to something different depending on whether the python is 32 or 64 bit. From alan.gauld at yahoo.co.uk Wed Aug 10 04:40:22 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 10 Aug 2016 09:40:22 +0100 Subject: [Tutor] Problem with graphics.py In-Reply-To: References: Message-ID: On 09/08/16 17:55, Michael Selik wrote: > Do you mind running the following commands from the python shell? > > py> import os > py> os.getcwd() > '/Users/mike' > py> sorted(os.listdir('.')) > ['.Trash', 'Applications', 'Desktop', ...] > > This will show us what location your python interpreter has as the "current > working directory" and whether or not the "graphics.py" file is present in > that directory. That's true but only one of the locations that Python looks in. You also need to use the command Steven suggested: >>> import sys >>> sys.path to see all the places Python will look. -- 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 eryksun at gmail.com Wed Aug 10 06:41:39 2016 From: eryksun at gmail.com (eryk sun) Date: Wed, 10 Aug 2016 10:41:39 +0000 Subject: [Tutor] command to determine of python 32 or 64 bit? In-Reply-To: References: Message-ID: On Wed, Aug 10, 2016 at 4:27 AM, Garry Willgoose wrote: > I have a number of binary libraries that are dependent on whether the precompiled python > distribution (eg. Enthought, ActiveState, etc) in which they are installed are compiled with > 32 or 64 bit. Is there any reliable way to determine at run time whether a python distribution > is 32 or 64 bit? If I can determine at runtime then I can set the path for loading of my libraries > to something different depending on whether the python is 32 or 64 bit. Use platform.architecture()[0]. Currently the value will be either "32bit" or "64bit". From alan.gauld at yahoo.co.uk Wed Aug 10 07:00:39 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 10 Aug 2016 12:00:39 +0100 Subject: [Tutor] command to determine of python 32 or 64 bit? In-Reply-To: References: Message-ID: On 10/08/16 11:41, eryk sun wrote: >> 32 or 64 bit. Is there any reliable way to determine at run time whether a python distribution >> is 32 or 64 bit? > > Use platform.architecture()[0]. Currently the value will be either > "32bit" or "64bit". I assumed that was sys.platform? But on my Linux box I only get the string 'linux' for platform... So is the architecture bit windows only? Or is it a different 'platform'? -- 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 Aug 10 07:02:59 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 10 Aug 2016 12:02:59 +0100 Subject: [Tutor] command to determine of python 32 or 64 bit? In-Reply-To: References: Message-ID: On 10/08/16 11:41, eryk sun wrote: > Use platform.architecture()[0]. Currently the value will be either > "32bit" or "64bit". Its OK, I just discovered there is a platform module! New one on me. That works :-) -- 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 nlwdrff at cfl.rr.com Wed Aug 10 20:16:33 2016 From: nlwdrff at cfl.rr.com (N Woodruff) Date: Wed, 10 Aug 2016 20:16:33 -0400 Subject: [Tutor] install issues - third party modules Message-ID: <003801d1f365$9ead9ec0$dc08dc40$@cfl.rr.com> Hello: I need some help with python installation, please. I have downloaded python 3.5.2, and installed it without issues on windows 7. Now I cannot get Third-party modules to install. I want to use openpyxl. I get the following errors: Can you give me some advice about correcting this and getting pip to install openpyxl Thank you. Norm nlwdrff at gmail.com From alan.gauld at yahoo.co.uk Thu Aug 11 04:19:04 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 11 Aug 2016 09:19:04 +0100 Subject: [Tutor] install issues - third party modules In-Reply-To: <003801d1f365$9ead9ec0$dc08dc40$@cfl.rr.com> References: <003801d1f365$9ead9ec0$dc08dc40$@cfl.rr.com> Message-ID: On 11/08/16 01:16, N Woodruff wrote: > I have downloaded python 3.5.2, and installed it without issues on windows > 7. > > Now I cannot get Third-party modules to install. I want to use openpyxl. How are you running pip? It should be run from a Windows CMD prompt, NOT from the Python >>> prompt. That's the most common mistake. Send the exact command that you are typing. > > I get the following errors: > > > > > > > Unfortunately we can't see them. Can you resend. Please make sure you are using plain text email rather than HTML since that might be the cause of the missing text. -- 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 Thu Aug 11 10:28:44 2016 From: beachkidken at gmail.com (Ken G.) Date: Thu, 11 Aug 2016 10:28:44 -0400 Subject: [Tutor] Where is win32print in Windows 10 Pro Message-ID: <2fe7c8f6-9abf-9fd7-341f-169abb72dd0e@gmail.com> Currently in my Windows 10 Pro, 64-bit operating system, x64-bit based processor, using Python-2.7.12.amd64, I have for the first few lines: ``````````````````````````` import os, sys import win32print ````````````````````````````` and get the following error message: ````````````````````````````````` import win32print ImportError: No module named win32print ```````````````````````````````` I have searched high and low within my Windows computer and have been unable to find 'win32print'. Any idea of where it is located or where I can obtain same. Thanks. From steve at pearwood.info Thu Aug 11 11:34:50 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 12 Aug 2016 01:34:50 +1000 Subject: [Tutor] Where is win32print in Windows 10 Pro In-Reply-To: <2fe7c8f6-9abf-9fd7-341f-169abb72dd0e@gmail.com> References: <2fe7c8f6-9abf-9fd7-341f-169abb72dd0e@gmail.com> Message-ID: <20160811153450.GF26300@ando.pearwood.info> On Thu, Aug 11, 2016 at 10:28:44AM -0400, Ken G. wrote: > import win32print > > ImportError: No module named win32print > > ```````````````````````````````` > > I have searched high and low within my Windows computer and have been > unable to find 'win32print'. Any idea of where it is located or where I > can obtain same. Thanks. Have you searched the Internet? https://duckduckgo.com/html/?q=win32print+python I'm not really familiar with this specific library, but I think it may be part of PyWin32: https://pypi.python.org/pypi/pywin32 which means if you have pip installed, this *may* work: # run this from your operating system shell (command.com, cmd.exe, Powershell?) pip install pywin32 I'm not an expert on Windows, but I hope this helps. -- Steve From beachkidken at gmail.com Thu Aug 11 12:14:50 2016 From: beachkidken at gmail.com (Ken G.) Date: Thu, 11 Aug 2016 12:14:50 -0400 Subject: [Tutor] Where is win32print in Windows 10 Pro [RESOLVED] In-Reply-To: <20160811153450.GF26300@ando.pearwood.info> References: <2fe7c8f6-9abf-9fd7-341f-169abb72dd0e@gmail.com> <20160811153450.GF26300@ando.pearwood.info> Message-ID: <5f89d8c9-3fda-6deb-a3aa-95a764206d89@gmail.com> On 08/11/2016 11:34 AM, Steven D'Aprano wrote: > On Thu, Aug 11, 2016 at 10:28:44AM -0400, Ken G. wrote: > >> import win32print >> >> ImportError: No module named win32print >> >> ```````````````````````````````` >> >> I have searched high and low within my Windows computer and have been >> unable to find 'win32print'. Any idea of where it is located or where I >> can obtain same. Thanks. > Have you searched the Internet? > > https://duckduckgo.com/html/?q=win32print+python > > I'm not really familiar with this specific library, but I think it may > be part of PyWin32: > > https://pypi.python.org/pypi/pywin32 > > > which means if you have pip installed, this *may* work: > > # run this from your operating system shell (command.com, cmd.exe, Powershell?) > pip install pywin32 > > > I'm not an expert on Windows, but I hope this helps. Thanks for the help so far seen here. I already installed pywin32 and no error is encounter in running pywin32 in the python program. Unfortunately, no printing is done yet. Still working on it. Your reference to duckduckgo.com provided a list of useful pywin32 attibutes but no examples was provided. Will keep looking. Thanks. Ken From Joaquin.Alzola at lebara.com Thu Aug 11 04:14:56 2016 From: Joaquin.Alzola at lebara.com (Joaquin Alzola) Date: Thu, 11 Aug 2016 08:14:56 +0000 Subject: [Tutor] install issues - third party modules In-Reply-To: <003801d1f365$9ead9ec0$dc08dc40$@cfl.rr.com> References: <003801d1f365$9ead9ec0$dc08dc40$@cfl.rr.com> Message-ID: > I get the following errors: You need to put the text error not the snapshot. This email is confidential and may be subject to privilege. If you are not the intended recipient, please do not copy or disclose its content but contact the sender immediately upon receipt. From pallabamway at gmail.com Thu Aug 11 12:54:55 2016 From: pallabamway at gmail.com (Pallab Amway) Date: Thu, 11 Aug 2016 22:24:55 +0530 Subject: [Tutor] need help Message-ID: Respected sir Myself pallab kumar seal from India I am using python2.7 in my window 7 but while I am using python to compile my program I am getting following error Programe1 age = 21 if age < 12: print( "You ' re still a child!" ) elif age < 18: print( "You are a teenager!" ) elif age < 30: print( "You ' re pretty young!" ) elif age < 50: print( "Wisening up, are we?" ) else: print( "Aren ' t the years weighing heavy?" ) answer expected an indented block programe 2 x = 41 if x%7 == 0: # --- Here starts a nested block of code --- if x%11 == 0: print( x, "is dividable by both 7 and 11." ) else: print( x, "is dividable by 7, but not by 11." ) # --- Here ends the nested block of code --- elif x%11 == 0: print( x, "is dividable by 11, but not by 7." ) else: print( x, "is dividable by neither 7 nor 11." ) answer expected an indented block yours faithfully pallab kumar seal From alan.gauld at yahoo.co.uk Thu Aug 11 13:19:32 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 11 Aug 2016 18:19:32 +0100 Subject: [Tutor] Where is win32print in Windows 10 Pro [RESOLVED] In-Reply-To: <5f89d8c9-3fda-6deb-a3aa-95a764206d89@gmail.com> References: <2fe7c8f6-9abf-9fd7-341f-169abb72dd0e@gmail.com> <20160811153450.GF26300@ando.pearwood.info> <5f89d8c9-3fda-6deb-a3aa-95a764206d89@gmail.com> Message-ID: On 11/08/16 17:14, Ken G. wrote: > Unfortunately, no printing is done yet. Still working on it. Your > reference to duckduckgo.com provided a list of useful pywin32 attibutes > but no examples was provided. Will keep looking. Thanks. PyWin32 is a very thin layer on top of the Win32/COM API. You probably need to be familiar with printing in Win32 to use PyWin to print, and that's not trivial. If you are already familiar with printing from C/C++ it will be straightforward but otherwise you may be better looking at other options. -- 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 Thu Aug 11 16:07:21 2016 From: beachkidken at gmail.com (Ken G.) Date: Thu, 11 Aug 2016 16:07:21 -0400 Subject: [Tutor] Where is win32print in Windows 10 Pro [RESOLVED] In-Reply-To: References: <2fe7c8f6-9abf-9fd7-341f-169abb72dd0e@gmail.com> <20160811153450.GF26300@ando.pearwood.info> <5f89d8c9-3fda-6deb-a3aa-95a764206d89@gmail.com> Message-ID: On 08/11/2016 01:19 PM, Alan Gauld via Tutor wrote: > On 11/08/16 17:14, Ken G. wrote: >> Unfortunately, no printing is done yet. Still working on it. Your >> reference to duckduckgo.com provided a list of useful pywin32 >> attibutes but no examples was provided. Will keep looking. Thanks. > PyWin32 is a very thin layer on top of the Win32/COM API. You probably > need to be familiar with printing in Win32 to use PyWin to print, and > that's not trivial. If you are already familiar with printing from > C/C++ it will be straightforward but otherwise you may be better > looking at other options. Finally got it printing. Gosh, it is a whole new ball game in a new whole ball park stadium. Loading up on soda pops and popcorns. Yep, you got it right, absolutely NOT trivial. GRRR. Thanks to all for providing guidance of where to go and look. From robertvstepp at gmail.com Thu Aug 11 18:30:01 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Thu, 11 Aug 2016 17:30:01 -0500 Subject: [Tutor] need help In-Reply-To: References: Message-ID: On Aug 11, 2016 12:15 PM, "Pallab Amway" wrote: > > Respected sir > > Myself pallab kumar seal from India I am using python2.7 > in my window 7 but while I am using python to compile my program I am > getting following error > > Programe1 > > age = 21 > > if age < 12: > > print( "You ' re still a child!" ) > > elif age < 18: > > print( "You are a teenager!" ) > > elif age < 30: > > print( "You ' re pretty young!" ) > > elif age < 50: > > print( "Wisening up, are we?" ) > > else: > > print( "Aren ' t the years weighing heavy?" ) > > answer > > > expected an indented block > Do you understand how Python uses consistent indentation to delineate blocks of code? If not, then you need to research this. Also, you say you're using Python 2.7. Python 2.x uses print *statements* => no parentheses, while Python 3.x uses print *functions*. Something else to read up on. Hope this gives you enough hints to work through your current problems! And I hope sending from my phone results in a plain text format! boB P.S.:. Do you have a good book or online tutorial to use? If not, there are plenty of such resources online. From michael.selik at gmail.com Thu Aug 11 13:57:15 2016 From: michael.selik at gmail.com (Michael Selik) Date: Thu, 11 Aug 2016 17:57:15 +0000 Subject: [Tutor] need help In-Reply-To: References: Message-ID: On Thu, Aug 11, 2016 at 1:15 PM Pallab Amway wrote: > expected an indented block > if-statements must have an indented block of code. For example: ``` if age < 12: print('You are a child') ``` From robertvstepp at gmail.com Fri Aug 12 09:52:16 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Fri, 12 Aug 2016 08:52:16 -0500 Subject: [Tutor] Fwd: Re: need help In-Reply-To: References: Message-ID: Pallab, please reply to the Tutor list. ---------- Forwarded message ---------- From: "Pallab Amway" Date: Aug 12, 2016 1:05 AM Subject: Re: [Tutor] need help To: "boB Stepp" Cc: > Respected sir,lots of thanks for your advice,but while i am compiling > those programe with python 2.7 no output is coming only showing the > masage "expected indented block"can you sugest any ebook?and please > sent me a expample with if & loop statement which i can compile on my > python 2.7 .yours faithfuly pallab kumar seal > > On 8/12/16, boB Stepp wrote: > > On Aug 11, 2016 12:15 PM, "Pallab Amway" wrote: > >> > >> Respected sir > >> > >> Myself pallab kumar seal from India I am using > > python2.7 > >> in my window 7 but while I am using python to compile my program I am > >> getting following error > >> > >> Programe1 > >> > >> age = 21 > >> > >> if age < 12: > >> > >> print( "You ' re still a child!" ) > >> > >> elif age < 18: > >> > >> print( "You are a teenager!" ) > >> > >> elif age < 30: > >> > >> print( "You ' re pretty young!" ) > >> > >> elif age < 50: > >> > >> print( "Wisening up, are we?" ) > >> > >> else: > >> > >> print( "Aren ' t the years weighing heavy?" ) > >> > >> answer > >> > >> > >> expected an indented block > >> > > > > Do you understand how Python uses consistent indentation to delineate > > blocks of code? If not, then you need to research this. > > > > Also, you say you're using Python 2.7. Python 2.x uses print *statements* > > => no parentheses, while Python 3.x uses print *functions*. Something else > > to read up on. > > > > Hope this gives you enough hints to work through your current problems! > > > > And I hope sending from my phone results in a plain text format! > > > > boB > > > > P.S.:. Do you have a good book or online tutorial to use? If not, there > > are plenty of such resources online. > > From Joaquin.Alzola at lebara.com Thu Aug 11 10:44:27 2016 From: Joaquin.Alzola at lebara.com (Joaquin Alzola) Date: Thu, 11 Aug 2016 14:44:27 +0000 Subject: [Tutor] Where is win32print in Windows 10 Pro In-Reply-To: <2fe7c8f6-9abf-9fd7-341f-169abb72dd0e@gmail.com> References: <2fe7c8f6-9abf-9fd7-341f-169abb72dd0e@gmail.com> Message-ID: >import win32print >ImportError: No module named win32print That module doesn't exist on your python path 'pywin32' is its canonical name. http://sourceforge.net/projects/pywin32/ For the same question: https://mail.python.org/pipermail/python-list/2015-July/693402.html This email is confidential and may be subject to privilege. If you are not the intended recipient, please do not copy or disclose its content but contact the sender immediately upon receipt. From alan.gauld at yahoo.co.uk Fri Aug 12 12:37:11 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 12 Aug 2016 17:37:11 +0100 Subject: [Tutor] Fwd: Re: need help In-Reply-To: References: Message-ID: > ---------- Forwarded message ---------- > From: "Pallab Amway" >> Respected sir,lots of thanks for your advice,but while i am compiling >> those programe with python 2.7 no output is coming only showing the >> masage "expected indented block" The first thing is to point out that you are getting an output - an error message. Error messages are output. The error tells you that it expects an indented block. Do you understand what that means? Indentation refers to the amount of spacing before the text. specifically there must be more space before the lines after a control statement (like your 'if') than there is on the control line. In most programming languages this is a matter of good style to make the code easier for humans to read. But it is a fundamental principle in python because the compiler uses the spacing to figure out how much code is influenced by the control statement. So an if statement should look like: if : an indented line another indented line end of if block elif can you sugest any ebook?and please I am biased but you can try my tutorial (see .sig below) or there is a full page for beginners on the python.org web site https://www.python.org/about/gettingstarted/ -- 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 itetteh34 at hotmail.com Fri Aug 12 14:28:06 2016 From: itetteh34 at hotmail.com (isaac tetteh) Date: Fri, 12 Aug 2016 13:28:06 -0500 Subject: [Tutor] Fwd: Fwd: Re: need help References: Message-ID: Also use good text editor like sublimeText. It will do the indentation for you. Begin forwarded message: > From: Alan Gauld via Tutor > Date: August 12, 2016 at 11:37:11 AM CDT > To: tutor at python.org > Subject: Re: [Tutor] Fwd: Re: need help > Reply-To: Alan Gauld > > >> ---------- Forwarded message ---------- >> From: "Pallab Amway" >>> Respected sir,lots of thanks for your advice,but while i am compiling >>> those programe with python 2.7 no output is coming only showing the >>> masage "expected indented block" > > The first thing is to point out that you are getting an output - an > error message. Error messages are output. > > The error tells you that it expects an indented block. > Do you understand what that means? Indentation refers > to the amount of spacing before the text. specifically > there must be more space before the lines after a control > statement (like your 'if') than there is on the control > line. > > In most programming languages this is a matter of good > style to make the code easier for humans to read. > But it is a fundamental principle in python because > the compiler uses the spacing to figure out how much > code is influenced by the control statement. > > So an if statement should look like: > > > if : > an indented line > another indented line > end of if block > elif Yet another indented line > only executed if the elif test is true > else: # optional else > More indented lines > only executed when the if and elif parts are false. > > The same applied to other control statements in Python > such as 'for', 'while', 'def', 'try' etc, etc. > > The amount of extra space you apply is up to you > but the recommended size is 4 spaces (as above). > >> can you sugest any ebook?and please > > I am biased but you can try my tutorial (see .sig below) > or there is a full page for beginners on the python.org > web site > > https://www.python.org/about/gettingstarted/ > > > -- > 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 eryksun at gmail.com Fri Aug 12 23:56:17 2016 From: eryksun at gmail.com (eryk sun) Date: Sat, 13 Aug 2016 03:56:17 +0000 Subject: [Tutor] Where is win32print in Windows 10 Pro In-Reply-To: References: <2fe7c8f6-9abf-9fd7-341f-169abb72dd0e@gmail.com> Message-ID: On Thu, Aug 11, 2016 at 2:44 PM, Joaquin Alzola wrote: > >>import win32print >>ImportError: No module named win32print > > That module doesn't exist on your python path > > 'pywin32' is its canonical name. > > http://sourceforge.net/projects/pywin32/ I'm not certain what's meant in the above, but to be clear, PyWin32 installs most of its modules as top-level imports. So `import win32print` is correct. PyWin32 can be pip installed using the "pypiwin32" package: https://pypi.python.org/pypi/pypiwin32 The difference compared to the executable installer is that the wheel package doesn't automatically run the post-install script that copies some DLLs to the System32 directory. Running the post-install script isn't necessary if you just need to call Windows and COM APIs. From beachkidken at gmail.com Sat Aug 13 07:25:58 2016 From: beachkidken at gmail.com (Ken G.) Date: Sat, 13 Aug 2016 07:25:58 -0400 Subject: [Tutor] Where is win32print in Windows 10 Pro In-Reply-To: References: <2fe7c8f6-9abf-9fd7-341f-169abb72dd0e@gmail.com> Message-ID: <75095fd7-04d7-3951-0c83-2c6f92aa20d3@gmail.com> On 08/12/2016 11:56 PM, eryk sun wrote: > On Thu, Aug 11, 2016 at 2:44 PM, Joaquin Alzola > wrote: >>> import win32print >>> ImportError: No module named win32print >> That module doesn't exist on your python path >> >> 'pywin32' is its canonical name. >> >> http://sourceforge.net/projects/pywin32/ > I'm not certain what's meant in the above, but to be clear, PyWin32 > installs most of its modules as top-level imports. So `import > win32print` is correct. > > PyWin32 can be pip installed using the "pypiwin32" package: > > https://pypi.python.org/pypi/pypiwin32 > > The difference compared to the executable installer is that the wheel > package doesn't automatically run the post-install script that copies > some DLLs to the System32 directory. Running the post-install script > isn't necessary if you just need to call Windows and COM APIs. > Thanks for clarifying this more. Ken From oasis.boone at gmail.com Tue Aug 16 16:25:16 2016 From: oasis.boone at gmail.com (Malcolm Boone) Date: Tue, 16 Aug 2016 14:25:16 -0600 Subject: [Tutor] Downloading Slack Files Message-ID: Hello everyone! I'm trying to run a python script that will download all files uploaded to my companies Slack account from the past 30 days. I'm new to Python, so to achieve this, I've just been editing a script that I use to delete all Slack files from the past 30 days. Here is the code I'm using currently with error: import requests import json import urllib import calendar from datetime import datetime, timedelta _token = "REDACTED" _domain = "REDACTED" 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 ("Downloading file" + f["name"] + "...") timestamp = str(calendar.timegm(datetime.now().utctimetuple())) urllib.urlretrieve = "https://" + _domain + ". slack.com/api/files.list" + timestamp requests.post(urllib.urlretrieve, data = { "token": _token, "file": f["id"], "set_active": "true", "_attempts": "1"}) print ("DONE!") So far, when I run this script, all that appears to be happening is it's printing a list of all of the file names. But from what I can tell, it's not actually downloading anything. The internet in our office isn't the greatest and it's printing a new file name every second, but since most of these are video files, I know that it isn't actually downloading anything in this amount of time. I've also tried searching my PC for any of the file names, with nothing turning up. My HD space also goes through no change after running the script. The other issue, is that the script never ends (probably a simple solution, but again I'm pretty new to this). It keeps printing the list of file names over and over until I manually close out of Python. Any help would be greatly appreciated! I'm using a Windows 10 PC running Python 3. From david at graniteweb.com Tue Aug 16 20:21:18 2016 From: david at graniteweb.com (David Rock) Date: Tue, 16 Aug 2016 19:21:18 -0500 Subject: [Tutor] Downloading Slack Files In-Reply-To: References: Message-ID: > On Aug 16, 2016, at 15:25, Malcolm Boone wrote: > > 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 ("Downloading file" + f["name"] + "...") > timestamp = str(calendar.timegm(datetime.now().utctimetuple())) > urllib.urlretrieve = "https://" + _domain + ". > slack.com/api/files.list" + timestamp > requests.post(urllib.urlretrieve, data = { > "token": _token, > "file": f["id"], > "set_active": "true", > "_attempts": "1"}) > print ("DONE!") > > > The other issue, is that the script never ends (probably a simple solution, > but again I'm pretty new to this). It keeps printing the list of file names > over and over until I manually close out of Python. I?m not sure about the downloading part, but the reason it never stops is because this test is never true: > if len(response.json()["files"]) == 0: > break Since you are downloading and not removing anything, there?s always going to be files so you will never break out of the while loop. I think you need to get the list of files first, outside of the loop, then loop over that list to download. ? David Rock david at graniteweb.com From alan.gauld at yahoo.co.uk Tue Aug 16 20:23:26 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 17 Aug 2016 01:23:26 +0100 Subject: [Tutor] Downloading Slack Files In-Reply-To: References: Message-ID: On 16/08/16 21:25, Malcolm Boone wrote: > I'm trying to run a python script that will download all files uploaded to > my companies Slack account from the past 30 days. I've no idea what a slack account is but I'm assuming some kind of web server... I've made a few general observations, I don;t know if they will help much. > import requests > import json You import json but do not appear to use it below. (There are calls to a json attribute of the response, but not to the json module) > import urllib > import calendar > from datetime import datetime, timedelta > > _token = "REDACTED" > _domain = "REDACTED" > > if __name__ == '__main__': > while 1: It would probabl;y be better style to put the code in a function (traditionally 'main()' ) and call the function from the if clause. Also its better style nowadays to use while True rather than while 1 although they do the same thing. > files_list_url = 'https://slack.com/api/files.list' > date = str(calendar.timegm((datetime.now() + timedelta(-30)) > .utctimetuple())) I can't help but feel there is an easier way to do that... But if it works I won't quibble too much. > data = {"token": _token, "ts_to": date} > response = requests.post(files_list_url, data = data) > if len(response.json()["files"]) == 0: > break The break above is the only opportunity to break out of the infinite while loop. Sop long as you get something back its going to keep going. And you don't appear to delete anything so I assume you always get stuff back. > for f in response.json()["files"]: > print ("Downloading file" + f["name"] + "...") > timestamp = str(calendar.timegm(datetime.now().utctimetuple())) > urllib.urlretrieve = "https://" + _domain + ". > slack.com/api/files.list" + timestamp I assume the domain part is what signifies your company's files? Is there really no separator between "files.list" and the timestamp? > requests.post(urllib.urlretrieve, data = { > "token": _token, > "file": f["id"], > "set_active": "true", > "_attempts": "1"}) > The other issue, is that the script never ends (probably a simple solution, > but again I'm pretty new to this). It keeps printing the list of file names > over and over until I manually close out of Python. You don't appear to do anything in the for loop that will change the response above so I don't think the break will ever be called. That probably explains your infinite loop. You probably need to sanity check the downloaded file (when you get one) and then explicitly delete the server copy, or mark it as read or whatever stops the server telling you about 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 ken.mayer at gmail.com Wed Aug 17 18:15:03 2016 From: ken.mayer at gmail.com (Ken Mayer) Date: Wed, 17 Aug 2016 15:15:03 -0700 Subject: [Tutor] simple troubleshooting question Message-ID: Dear Tutor: I'm new to Python. I'm trying to do 3 things that are giving me invalid syntax or other problems: 1) import numpy as np ImportError: No module named 'numpy' 2) pip install - U pip SyntaxError: invalid syntax' 3) pip install -U quantiacsToolbox Also, is there any way I can copy entire code and paste it in the Python 3.5 (32-bit) type DOS screen that I have? Thank you. Ken From alan.gauld at yahoo.co.uk Wed Aug 17 19:57:39 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 18 Aug 2016 00:57:39 +0100 Subject: [Tutor] simple troubleshooting question In-Reply-To: References: Message-ID: On 17/08/16 23:15, Ken Mayer wrote: > I'm new to Python. I'm trying to do 3 things that are giving me invalid > syntax or other problems: > > 1) import numpy as np > > ImportError: No module named 'numpy' Numpy is not part of standard Python. You need to install it seperately or, my preference, download a Python distribution such as Anaconda that comes with it pre-installed. > 2) pip install - U pip > > SyntaxError: invalid syntax' You are running pip from inside python, it is actually an external command that should be run from the OS command prompt (aka DOS or CMD prompt) > Also, is there any way I can copy entire code and paste it in the Python > 3.5 (32-bit) type DOS screen that I have? That's an interpreter intended for experimentation only. There are other more advanced Python interpreters that can accept large amounts of pasted code(*) but it is usually better to create a new file and save the code into the file then run the file as a script. [ (*)If you get Anaconda it comes with IPython which is an example of such an interpreter, it has a notepad concept where code can be pasted and executed. ] So for example if you created a file called myscript.py and pasted in the code: import sys name = input("Whats your name? ") for i in range(3): print("Hello ", name) sys.exit() You would run it using C:\WINDOWS> python path\to\myscript.py Or, if you use the standard Python IDE - IDLE - you can use the File->New menu to create a new python file then paste your code, save it and run it all using the menus. 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 kalpeshnaik42 at gmail.com Fri Aug 19 10:36:37 2016 From: kalpeshnaik42 at gmail.com (Kalpesh Naik) Date: Fri, 19 Aug 2016 20:06:37 +0530 Subject: [Tutor] Invalid syntax error in my program Message-ID: <57b71985.0566620a.83c2b.f24f@mx.google.com> Sir/Mam i am doing python language program of simple calculator but there was some errors in my program Please solve it and also guide me #SIMPLE CALCULATOR #1-Addition #2-Subtraction #3-Division #4-Multiplication #5-Modules while True: n=int(input("Enter your choice:")) a=int(input("Enter 1st value:")) print("1st value is:",a) b=int(input("Enter 2nd value:")) print("2nd value is:",b) if n==1: c=a+b print("Addition is : ",c) elif n==2: d=a-b print("Subtraction is : ",d) elif n==3: x=a/b print("Division is : ",x) elif n==4: y=a*b print("Multiplication is : ",y) elif n==5: z=a%b print("modules is : ",z) else: print("!!!Enter wrong choice!!!") From ruby.student at gmail.com Fri Aug 19 11:30:40 2016 From: ruby.student at gmail.com (Ruby Student) Date: Fri, 19 Aug 2016 15:30:40 +0000 Subject: [Tutor] Problems install pymqi Message-ID: Hello Team, I am having a bad day (actually second day) trying to get *pymqi *installed. Any help is greatly appreciated. Yesterday I installed Python on my desktop. I am trying to use the Python WebSphere MQ API and learn Python at the same time. *OS*: Windows 7 Enterprise x64 Edition, Build 7601: SP1 *Python*: Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:40:30) [MSC v.1500 64 bit (AMD64)] on win32 *C++*: Microsoft Visual C++ Compiler for Python 2.7 *Python*: Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:40:30) [MSC v.1500 64 bit (AMD64)] on win32 I also have a full blown IBM WebSphere MQ environment, meaning that I have all the header files, specially the *cmqc.h* C:\Python27>*dspmqver* Name: *WebSphere MQ* Version: 8.0.0.4 Level: p800-004-151017 I tried installing *pymqi* using two different methods and I got errors both times. *METHOD 1*: Using *easy_install* C:\Python27>*easy_install pymqi* Searching for pymqi Reading https://pypi.python.org/simple/pymqi/ Best match: pymqi 1.5.4 Downloading https://pypi.python.org/packages/a6/c6/518923b9ea2bea36e30bcbe0f23c2ce00202a44e1d0d6b6f1d94c68e7dc0/pymqi-.5.4.tar.gz#md5=2289f37b30fd40f 08f8edb2fe3872f31 Processing pymqi-1.5.4.tar.gz Writing c:\users\myuserid\appdata\local\temp\1\easy_install-wzpfj1\pymqi-1.5.4\setup.cfg Running pymqi-1.5.4\setup.py -q bdist_egg --dist-dir c:\users\reyesv~1\appdata\local\temp\1\easy_install-wzpfj1\pymqi-1.5.4\egg-dist-tmp-upo7kw Building PyMQI client 64bits pymqe.c pymqi/pymqe.c(240) : error C2275: 'MQCSP' : illegal use of this type as an expression C:\IBM\WebSphere MQ\tools\c\include\cmqc.h(4072) : see declaration of 'MQCSP' pymqi/pymqe.c(240) : error C2146: syntax error : missing ';' before identifier 'csp' pymqi/pymqe.c(240) : error C2065: 'csp' : undeclared identifier pymqi/pymqe.c(240) : error C2059: syntax error : '{' pymqi/pymqe.c(247) : error C2065: 'csp' : undeclared identifier pymqi/pymqe.c(247) : error C2224: left of '.AuthenticationType' must have struct/union type pymqi/pymqe.c(248) : error C2065: 'csp' : undeclared identifier pymqi/pymqe.c(248) : error C2224: left of '.CSPUserIdPtr' must have struct/union type pymqi/pymqe.c(249) : error C2065: 'csp' : undeclared identifier pymqi/pymqe.c(249) : error C2224: left of '.CSPUserIdLength' must have struct/union type pymqi/pymqe.c(250) : error C2065: 'csp' : undeclared identifier pymqi/pymqe.c(250) : error C2224: left of '.CSPPasswordPtr' must have struct/union type pymqi/pymqe.c(251) : error C2065: 'csp' : undeclared identifier pymqi/pymqe.c(251) : error C2224: left of '.CSPPasswordLength' must have struct/union type pymqi/pymqe.c(256) : error C2065: 'csp' : undeclared identifier pymqi/pymqe.c(256) : warning C4133: '=' : incompatible types - from 'int *' to 'PMQCSP' error: Setup script exited with error: command 'C:\\Users\\myuserid\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\cl.exe' failed with exit status 2 C:\Python27> *METHOD 2*: Using *pip* C:\Python27>*pip install pymqi* Collecting pymqi Using cached pymqi-1.5.4.tar.gz Requirement already satisfied (use --upgrade to upgrade): testfixtures in c:\python27\lib\site-packages (from pymqi) Installing collected packages: pymqi Running setup.py install for pymqi ... error Complete output from command c:\python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\myuserid\\appdata\\local\\temp\\1\\pip -build-cgd7j6\\pymqi\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --rec ord c:\users\reyesv~1\appdata\local\temp\1\pip-5ganmv-record\install-record.txt --single-version-externally-managed --compile: Building PyMQI client 64bits running install running build running build_py creating build creating build\lib.win-amd64-2.7 creating build\lib.win-amd64-2.7\pymqi copying pymqi\__init__.py -> build\lib.win-amd64-2.7\pymqi copying pymqi\CMQC.py -> build\lib.win-amd64-2.7\pymqi copying pymqi\CMQCFC.py -> build\lib.win-amd64-2.7\pymqi copying pymqi\CMQXC.py -> build\lib.win-amd64-2.7\pymqi copying pymqi\CMQZC.py -> build\lib.win-amd64-2.7\pymqi running build_ext building 'pymqi.pymqe' extension creating build\temp.win-amd64-2.7 creating build\temp.win-amd64-2.7\Release creating build\temp.win-amd64-2.7\Release\pymqi C:\Users\myuserid\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DND EBUG -DPYQMI_SERVERBUILD=0 "-Ic:\Program Files (x86)\IBM\WebSphere MQ\tools\c\include" -Ic:\python27\include -Ic:\python27\PC /Tcpymqi/pymqe.c /Fobuild\temp.win-amd64-2.7\Release\pymqi/pymqe.obj pymqe.c pymqi/pymqe.c(240) : error C2275: 'MQCSP' : illegal use of this type as an expression C:\IBM\WebSphere MQ\tools\c\include\cmqc.h(4072) : see declaration of 'MQCSP' pymqi/pymqe.c(240) : error C2146: syntax error : missing ';' before identifier 'csp' pymqi/pymqe.c(240) : error C2065: 'csp' : undeclared identifier pymqi/pymqe.c(240) : error C2059: syntax error : '{' pymqi/pymqe.c(247) : error C2065: 'csp' : undeclared identifier pymqi/pymqe.c(247) : error C2224: left of '.AuthenticationType' must have struct/union type pymqi/pymqe.c(248) : error C2065: 'csp' : undeclared identifier pymqi/pymqe.c(248) : error C2224: left of '.CSPUserIdPtr' must have struct/union type pymqi/pymqe.c(249) : error C2065: 'csp' : undeclared identifier pymqi/pymqe.c(249) : error C2224: left of '.CSPUserIdLength' must have struct/union type pymqi/pymqe.c(250) : error C2065: 'csp' : undeclared identifier pymqi/pymqe.c(250) : error C2224: left of '.CSPPasswordPtr' must have struct/union type pymqi/pymqe.c(251) : error C2065: 'csp' : undeclared identifier pymqi/pymqe.c(251) : error C2224: left of '.CSPPasswordLength' must have struct/union type pymqi/pymqe.c(256) : error C2065: 'csp' : undeclared identifier pymqi/pymqe.c(256) : warning C4133: '=' : incompatible types - from 'int *' to 'PMQCSP' error: command 'C:\\Users\\reyesviloria362048\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\cl.exe' failed with exit status 2 ---------------------------------------- Command "c:\python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\reyesv~1\\appdata\\local\\temp\\1\\pip-build-cgd7j6\\pymqi\\se tup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record c:\users\reyesv~1\ap pdata\local\temp\1\pip-5ganmv-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in c:\users\reyesv~1\a ppdata\local\temp\1\pip-build-cgd7j6\pymqi\ From simon at taliuk.co.uk Thu Aug 18 07:41:40 2016 From: simon at taliuk.co.uk (Simon Le-Talbot) Date: Thu, 18 Aug 2016 11:41:40 +0000 Subject: [Tutor] Random time code Message-ID: Hi , I have recently purchased a Raspberry pi3 and I am wanting to turn a light on and then have it turn off at a random time between 3 and 8 seconds. Each time I turn the light on I want it to turn off at a different time ( just like the race start lights in formula 1). Code you possible help me with the python code required to do this? Regards Simon. Sent from my iPhone Sent from my iPhone From alan.gauld at yahoo.co.uk Fri Aug 19 13:23:08 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 19 Aug 2016 18:23:08 +0100 Subject: [Tutor] Invalid syntax error in my program In-Reply-To: <57b71985.0566620a.83c2b.f24f@mx.google.com> References: <57b71985.0566620a.83c2b.f24f@mx.google.com> Message-ID: On 19/08/16 15:36, Kalpesh Naik wrote: > #SIMPLE CALCULATOR > while True: > n=int(input("Enter your choice:")) > a=int(input("Enter 1st value:")) > print("1st value is:",a) > b=int(input("Enter 2nd value:")) > print("2nd value is:",b) > if n==1: > c=a+b > print("Addition is : ",c) > elif n==2: > d=a-b The elif line should be aligned with the if line like this: if : XXXXX XXXXX elif : YYYYY YYYYY elif : ZZZZZ ZZZZZ else: AAAAA The indentation is what python uses to figure out where the blocks (X,Y and Z) end. Aligned as you have it Python tries to interpret the elif as if it were part of the if block. > elif n==5: > z=a%b > print("modules is : ",z) I think you mean modulo not modules. Modules, especially in Python, means something very different. 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 Fri Aug 19 13:28:18 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 19 Aug 2016 18:28:18 +0100 Subject: [Tutor] Random time code In-Reply-To: References: Message-ID: On 18/08/16 12:41, Simon Le-Talbot wrote: > Hi , I have recently purchased a Raspberry pi3 and > I am wanting to turn a light on and then have it > turn off at a random time between 3 and 8 seconds. The time module will give you the current time in seconds. It also provides the sleep() function which lets your program pause(sleep) for a number of seconds. sleep(...) sleep(seconds) Delay execution for a given number of seconds. The argument may be a floating point number for subsecond precision. (END) For randomness look at the random module which includes several different random number generation functions. One of them, randrange() probably suits your needs best. randrange(start, stop=None, step=1, _int=) method of random.Random instance Choose a random item from range(start, stop[, step]). This fixes the problem with randint() which includes the endpoint; in Python this is usually not what you want. (END) If you need more help in assembling the parts let us know. But I didn't want to spoil your fun in figuring it out. :-) -- 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 Aug 19 13:34:22 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 19 Aug 2016 18:34:22 +0100 Subject: [Tutor] Problems install pymqi In-Reply-To: References: Message-ID: On 19/08/16 16:30, Ruby Student wrote: > Hello Team, > > I am having a bad day (actually second day) trying to get *pymqi *installed. > Any help is greatly appreciated. > Yesterday I installed Python on my desktop. I am trying to use the Python > WebSphere MQ API and learn Python at the same time. That's quite a bit off topic for this group (Python language and core library) but you may just get lucky and find somebody who has done it. However you are probably more likely to get help on a dedicated pymqi forum or on the main python mailing list/group. There seems to be some kind of forum here: https://github.com/dsuch/pymqi/issues This looks pretty much like yours.... https://github.com/dsuch/pymqi/issues/35 -- 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 wumeid at hotmail.com Sat Aug 20 18:37:15 2016 From: wumeid at hotmail.com (Michelle Meiduo Wu) Date: Sat, 20 Aug 2016 22:37:15 +0000 Subject: [Tutor] About Using timeout Mark in Pytest Message-ID: Hi there, I'd like to use @pytest. mark.timeout in pytest test in Windows. But if one of test cases is timeout, then the following test cases will stop. Is there anybody know how to continue to run the following test cases if a test case is timeout? Thank you in advance. Michelle From rohitm at gmail.com Sun Aug 21 03:19:25 2016 From: rohitm at gmail.com (Rohit Mediratta) Date: Sun, 21 Aug 2016 00:19:25 -0700 Subject: [Tutor] About Using timeout Mark in Pytest In-Reply-To: References: Message-ID: I'm guessing the decorator is using method='thread', which is the default and aborts the process when timeout occurs. Can you see if your env supports method='signal' and if this resolves the issue? @pytest.mark.timeout(method='signal') Reference guide for supported options is here: https://pypi.python.org/pypi/pytest-timeout -Rohit > On Aug 20, 2016, at 3:37 PM, Michelle Meiduo Wu wrote: > > Hi there, > > > I'd like to use @pytest. mark.timeout in pytest test in Windows. But if one of test cases is timeout, then the following test cases will stop. > > > Is there anybody know how to continue to run the following test cases if a test case is timeout? > > > Thank you in advance. > > > Michelle > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From michealemeagi at gmail.com Wed Aug 24 06:26:07 2016 From: michealemeagi at gmail.com (Micheal Emeagi) Date: Wed, 24 Aug 2016 11:26:07 +0100 Subject: [Tutor] I Need Help Message-ID: Hello Tutor, I am a newbie programmer trying to implement an exponential smoothing forcast using two list. Yt list has the Y values and Ft list has the forcast values. Ft is the forcast list whose length should be one element greater than the Yt list. I want the elements of ft to increment by one while I use it to generate the subsequent element. But for some reasons I don't understand, it keeps changing the second element in Ft. Could please help me figure what is going wrong with the while iteration. See below the code. Michael yt = [1,2,3,4,5,6] ft = [yt[0],yt[0]] alpha = 0.5 while len(ft) != len(yt) + 1: ft.append(ft[1] + alpha * (yt[1] - ft[1])) print(ft) ft[1] += 1 yt[1] += 1 print (ft) From alan.gauld at yahoo.co.uk Wed Aug 24 13:28:00 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 24 Aug 2016 18:28:00 +0100 Subject: [Tutor] I Need Help In-Reply-To: References: Message-ID: On 24/08/16 11:26, Micheal Emeagi wrote: > forcast values. Ft is the forcast list whose length should be one element > greater than the Yt list. I want the elements of ft to increment by one > while I use it to generate the subsequent element. But for some reasons I > don't understand, it keeps changing the second element in Ft. You have hard coded an index of 1, so it will always append a calculation based on that list item.. > Could please help me figure what is going wrong with the while iteration. I don;t understand your algorithm so don;t know what you are tryingt to do, but the easiest way to deal with this kind of issue is usually to manually step through the code listing each variable on each iteration. Sometimes on paper or you could just use print statements. Like this: > yt = [1,2,3,4,5,6] > ft = [yt[0],yt[0]] This sets the first two values to 1, is that what you wanted? > alpha = 0.5 > while len(ft) != len(yt) + 1: > ft.append(ft[1] + alpha * (yt[1] - ft[1])) yt = [1,2,3,4,5,6] ft = [1,1] -> [1,1,(1+0.5(2-1)] -> [1,1,1.5] > ft[1] += 1 > yt[1] += 1 yt = [1,3,3,4,5,6] ft = [1,2,1.5] len(ft) != len(yt+1 -> True Notice that this is where you always change the same index value. I'm guessing you maybe need an index variable that you increment round about here. But I'm not sure since I don't really understand your algorithm. Continuing... Next iteration: > ft.append(ft[1] + alpha * (yt[1] - ft[1])) yt = [1,3,3,4,5,6] ft = [1,2,1.5,] -> [1,2,1.5,(2+0.5(3-2)) -> [1,2,1.5,2.5] > ft[1] += 1 > yt[1] += 1 yt = [1,4,3,4,5,6] ft = [1,3,1.5,2.5] len(ft) != len(yt)+1 -> True Next iteration: > ft.append(ft[1] + alpha * (yt[1] - ft[1])) yt = [1,4,3,4,5,6] ft = [1,3,1.5,2.5] -> [1,3,1.5,2.5,(3+0.5(4-3)) -> [1,3,1.5,2.5,3.5] > ft[1] += 1 > yt[1] += 1 yt = [1,5,3,4,5,6] ft = [1,4,1.5,2.5,3.5] len(ft) != len(yt)+1 -> True etc... I'm assuming that's not what you were looking for but since I don't know what you expected I can't say any more, other than that, if it is, there are easier ways to do it! I'm guessing you might want something like: yt = [1,2,3,4,5,6] ft = [yt[0]] alpha = 0.5 for idx,n in enumerate(yt): ft.append(ft[idx] + alpha*(n-ft[idx])) Which gives an ft of: [1, 1.0, 1.5, 2.25, 3.125, 4.0625, 5.03125] But that's just a wild guess at what you might be trying to do. But maybe it will give you some ideas. -- 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 Joaquin.Alzola at lebara.com Wed Aug 24 12:53:05 2016 From: Joaquin.Alzola at lebara.com (Joaquin Alzola) Date: Wed, 24 Aug 2016 16:53:05 +0000 Subject: [Tutor] I Need Help In-Reply-To: References: Message-ID: >I want the elements of ft to increment by one while I use it to generate the subsequent element. But for some reasons I don't understand, it keeps changing the second element in Ft. >yt = [1,2,3,4,5,6] >ft = [yt[0],yt[0]] >alpha = 0.5 >while len(ft) != len(yt) + 1: > ft.append(ft[1] + alpha * (yt[1] - ft[1])) > print(ft) > ft[1] += 1 > yt[1] += 1 >print (ft) Right now your output is: [1, 1, 1.5] [1, 2, 1.5, 2.5] [1, 3, 1.5, 2.5, 3.5] [1, 4, 1.5, 2.5, 3.5, 4.5] [1, 5, 1.5, 2.5, 3.5, 4.5, 5.5] [1, 6, 1.5, 2.5, 3.5, 4.5, 5.5] What do you want it to be? This email is confidential and may be subject to privilege. If you are not the intended recipient, please do not copy or disclose its content but contact the sender immediately upon receipt. From michealemeagi at gmail.com Wed Aug 24 14:12:01 2016 From: michealemeagi at gmail.com (Micheal Emeagi) Date: Wed, 24 Aug 2016 19:12:01 +0100 Subject: [Tutor] I Need Help In-Reply-To: References: Message-ID: This is what it is suppose to be [1, 1, 1.5] [1, 1, 1.5, 2.25] [1, 1, 1.5, 2.25, 3.125] [1, 1, 1.5, 2.25, 3.125, 4.06] [1, 1, 1.5, 2.25, 3.125, 4.06, 5.03] The model below is what I want to implement.I chose alpha to be 0.5. The model below chose 0.3. What is Exponential Smoothing? - A type of weighted moving averaging model - Part of many forecasting packages; ideal for developing forecasts of lots of smaller items - Needs only three numbers: Ft-1 = Forecast for the period before current time period t At-1 = Actual demand for the period before current time period t *a* = Weight between 0 and 1 - Formula - As a gets closer to 1, the more weight put on the most recent demand number Exponential Smoothing Forecaset with a = .3 On Wed, Aug 24, 2016 at 5:53 PM, Joaquin Alzola wrote: > >I want the elements of ft to increment by one while I use it to generate > the subsequent element. But for some reasons I don't understand, it keeps > changing the second element in Ft. > > >yt = [1,2,3,4,5,6] > > >ft = [yt[0],yt[0]] > >alpha = 0.5 > >while len(ft) != len(yt) + 1: > > > ft.append(ft[1] + alpha * (yt[1] - ft[1])) > > > print(ft) > > ft[1] += 1 > > yt[1] += 1 > >print (ft) > > Right now your output is: > [1, 1, 1.5] > [1, 2, 1.5, 2.5] > [1, 3, 1.5, 2.5, 3.5] > [1, 4, 1.5, 2.5, 3.5, 4.5] > [1, 5, 1.5, 2.5, 3.5, 4.5, 5.5] > [1, 6, 1.5, 2.5, 3.5, 4.5, 5.5] > > What do you want it to be? > This email is confidential and may be subject to privilege. If you are not > the intended recipient, please do not copy or disclose its content but > contact the sender immediately upon receipt. > From alan.gauld at yahoo.co.uk Wed Aug 24 20:41:59 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 25 Aug 2016 01:41:59 +0100 Subject: [Tutor] I Need Help In-Reply-To: References: Message-ID: On 24/08/16 19:12, Micheal Emeagi wrote: > This is what it is suppose to be > [1, 1, 1.5, 2.25, 3.125, 4.06, 5.03] Oh good, it looks like my wild guess was right. :-) enjoy, -- 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 Wed Aug 24 20:57:43 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 25 Aug 2016 10:57:43 +1000 Subject: [Tutor] I Need Help In-Reply-To: References: Message-ID: <20160825005742.GD26300@ando.pearwood.info> On Wed, Aug 24, 2016 at 11:26:07AM +0100, Micheal Emeagi wrote: > yt = [1,2,3,4,5,6] > ft = [yt[0],yt[0]] > alpha = 0.5 > while len(ft) != len(yt) + 1: > ft.append(ft[1] + alpha * (yt[1] - ft[1])) > print(ft) > ft[1] += 1 > yt[1] += 1 > > print (ft) I think that your intention is to handle each element of yt, exactly once each. It is nearly always easiest to use a for loop rather than a while loop for these sorts of tasks. So your code then becomes: yt = [1, 2, 3, 4, 5, 6] ft = [yt[0], yt[0]] alpha = 0.5 for y in yt: # ft[-1] always refers to the LAST element of ft forecast_value = ft[-1] + alpha*(y - ft[-1]) ft.append(forecast_value) print(ft) When I run this code, I get: [1, 1, 1.0] [1, 1, 1.0, 1.5] [1, 1, 1.0, 1.5, 2.25] [1, 1, 1.0, 1.5, 2.25, 3.125] [1, 1, 1.0, 1.5, 2.25, 3.125, 4.0625] [1, 1, 1.0, 1.5, 2.25, 3.125, 4.0625, 5.03125] Notice that ft has length TWO more than yt, rather than one. That's because you initialise it with two copies of yt[0]. Are you sure that's what you want? -- Steve From akleider at sonic.net Thu Aug 25 21:12:12 2016 From: akleider at sonic.net (Alex Kleider) Date: Thu, 25 Aug 2016 18:12:12 -0700 Subject: [Tutor] project directory structure Message-ID: <3c207ca5d6f32bfcab10f7992389942c@sonic.net> I'm still struggling with what is the best way to set up a project directory. All the sources I've read seem to agree that one should have a top level project directory under which one might expect to find the following: COPYING.txt # or LICENSE.txt README.rst setup.py and if the project consists of only one .py file, it also goes here but if there is to be more than one module, the code should be in a subdirectory of the same name as the top level one so we now have something like the following: MyProject COPYING.txt # or LICENSE.txt MyProject data/ src/ module1.py module2.py tests/ test1.py test1.py README.rst setup.py Assuming the latter scenario, where should one run virtualenv -p python3 venv? ... at the top level or within the second level? During development I would expect to have MyProject/MyProject as my working directory most of the time and hence think venv should be there but perhaps it should be the level above so that it encompasses setup.py. The main reason I want to get this right is because all my .py files begin with a shebang line of the form #!../venv/bin/python3 which uses a relative path so the choice I make will determine if I use the above or #!../../venv/bin/python3 Any advice would be appreciated. Alex From jf_byrnes at comcast.net Thu Aug 25 21:34:43 2016 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Thu, 25 Aug 2016 20:34:43 -0500 Subject: [Tutor] tkinter/sqlite3? Message-ID: I am working with Python 3.4.3 on Ubuntu 14.04. I am learning tkinter so I decided to rewrite a program I had written in pythoncard in tkinter. I found that a sqlite3 SELECT statement that works in pythoncard throws an error in tkinter and am wondering why? # Fill the accounts listbox from the passwords database def fill_accounts_lb(category): conn = sqlite3Connect() cur = conn.cursor() #cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY Account COLLATE NOCASE''', category) (1) cur.execute('''SELECT Account FROM pwds WHERE Category='%s' ORDER BY Account COLLATE NOCASE''' % category) result = [row[0] for row in cur.fetchall()] clearListbox() for account in result: lb_accounts.insert(END, account) conn.close() (1) Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python3.4/tkinter/__init__.py", line 1536, in __call__ return self.func(*args) File "tk_pwds.py", line 22, in rbCall fill_accounts_lb('WebSites') File "tk_pwds.py", line 56, in fill_accounts_lb cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY Account COLLATE NOCASE''', category) sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 8 supplied. I cut the working statement from pythoncard and pasted it into tkinter and am curious why it works in the pythoncard version and not the tkinter version. I'm not sure where it is coming up with the 8 bindings it said are supplied? Thanks, Jim From ben+python at benfinney.id.au Fri Aug 26 00:27:47 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 26 Aug 2016 14:27:47 +1000 Subject: [Tutor] project directory structure References: <3c207ca5d6f32bfcab10f7992389942c@sonic.net> Message-ID: <85a8g0w3wc.fsf@benfinney.id.au> Alex Kleider writes: > I'm still struggling with what is the best way to set up a project > directory. One thing to learn is that there's no one right way that is universally applicable. In particular, you are asking about *social* conventions here. These are prone to change and negotiation and exceptions. > Assuming the latter scenario, where should one run > virtualenv -p python3 venv? > ... at the top level or within the second level? I recommend keeping the virtualenv entirely *outside* the code base. Make a directory elsewhere to hold your virtualenvs, like a directory to hold your caches. Removing and re-populating the virtualenv should be independent from removing and re-populating the working tree. Hence they should be entirely separate directories. > The main reason I want to get this right is because all my .py files > begin with a shebang line of the form > #!../venv/bin/python3 That's exactly the wrong thing to do. Your shebang line should *not* assume a custom location of the Python interpreter. It's the responsibility of the operating system or virtualenv to provide the Python interpreter command in a standard place. Instead, use: #! /usr/bin/env python3 or: #! /usr/bin/python3 and leave it to the operating system and the virtualenv to provide the Python interpreter correctly. -- \ ?You've got to think about big things while you're doing small | `\ things, so that all the small things go in the right | _o__) direction.? ?Alvin Toffler | Ben Finney From akleider at sonic.net Fri Aug 26 02:26:34 2016 From: akleider at sonic.net (Alex Kleider) Date: Thu, 25 Aug 2016 23:26:34 -0700 Subject: [Tutor] project directory structure In-Reply-To: <85a8g0w3wc.fsf@benfinney.id.au> References: <3c207ca5d6f32bfcab10f7992389942c@sonic.net> <85a8g0w3wc.fsf@benfinney.id.au> Message-ID: <72bddf5e702cfccb52e2776edd9c8f12@sonic.net> On 2016-08-25 21:27, Ben Finney wrote: > That's exactly the wrong thing to do. Your shebang line should *not* > assume a custom location of the Python interpreter. > > It's the responsibility of the operating system or virtualenv to > provide > the Python interpreter command in a standard place. > > Instead, use: > > #! /usr/bin/env python3 > > or: > > #! /usr/bin/python3 > > and leave it to the operating system and the virtualenv to provide the > Python interpreter correctly. Thanks, Ben, for your input. Am I to assume that if I have activated a virtualenv, then the following shebang #!/usr/bin/env python will use the python specified in the venv/bin/? From __peter__ at web.de Fri Aug 26 03:03:14 2016 From: __peter__ at web.de (Peter Otten) Date: Fri, 26 Aug 2016 09:03:14 +0200 Subject: [Tutor] tkinter/sqlite3? References: Message-ID: Jim Byrnes wrote: > I am working with Python 3.4.3 on Ubuntu 14.04. > > I am learning tkinter so I decided to rewrite a program I had written in > pythoncard in tkinter. I found that a sqlite3 SELECT statement that > works in pythoncard throws an error in tkinter and am wondering why? > > # Fill the accounts listbox from the passwords database > def fill_accounts_lb(category): > conn = sqlite3Connect() > cur = conn.cursor() > #cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY > Account COLLATE NOCASE''', category) (1) > cur.execute('''SELECT Account FROM pwds WHERE Category='%s' ORDER BY > Account COLLATE NOCASE''' > % category) > result = [row[0] for row in cur.fetchall()] > clearListbox() > for account in result: > lb_accounts.insert(END, account) > conn.close() > > (1) > Exception in Tkinter callback > Traceback (most recent call last): > File "/usr/lib/python3.4/tkinter/__init__.py", line 1536, in __call__ > return self.func(*args) > File "tk_pwds.py", line 22, in rbCall > fill_accounts_lb('WebSites') > File "tk_pwds.py", line 56, in fill_accounts_lb > cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY > Account COLLATE NOCASE''', category) > sqlite3.ProgrammingError: Incorrect number of bindings supplied. The > current statement uses 1, and there are 8 supplied. > > I cut the working statement from pythoncard and pasted it into tkinter > and am curious why it works in the pythoncard version and not the > tkinter version. I'm not sure where it is coming up with the 8 bindings > it said are supplied? category is probably a string with eight characters. As cursor.execute() expects a sequence as its second argument it misinterprets this string as 8 distinct arguments. If the string were of length one your code would (accidentally) work; this might have been the case in your other script. The correct fix is to put even a single value into a list or tuple: cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY Account COLLATE NOCASE''', [category]) If you choose the tuple remember that a one-tuple requires a trailing comma: cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY Account COLLATE NOCASE''', (category,)) From alan.gauld at yahoo.co.uk Fri Aug 26 05:22:35 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 26 Aug 2016 10:22:35 +0100 Subject: [Tutor] tkinter/sqlite3? In-Reply-To: References: Message-ID: On 26/08/16 02:34, Jim Byrnes wrote: > Exception in Tkinter callback > Traceback (most recent call last): ... > File "tk_pwds.py", line 56, in fill_accounts_lb > cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY > Account COLLATE NOCASE''', category) > sqlite3.ProgrammingError: Incorrect number of bindings supplied. The > current statement uses 1, and there are 8 supplied. > > I cut the working statement from pythoncard and pasted it into tkinter > and am curious why it works in the pythoncard version and not the > tkinter version. Peter has given the solution, but just to be clear this has nothing whatsoever to do with Tkinter v Pythoncard it is entirely a Sqlite issue. (As is evidenced in the error message.) Did you use an older version of Sqlite when you wrote the Pythoncard code perhaps? You probably also used an older version of Python? The real mystery is how it worked in the Pythoncard version, unless, as Peter suggests, you just got lucky and always passed a single valued item? Finally, the string formatting solution is never a good idea for database queries since it is (a) open to injection attack and (b) liable to generate an incorrect SQL query which is hard to debug. (ie the query gets executed but returns different data to what you expected/wanted) -- 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 jf_byrnes at comcast.net Fri Aug 26 15:45:37 2016 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Fri, 26 Aug 2016 14:45:37 -0500 Subject: [Tutor] tkinter/sqlite3? In-Reply-To: References: Message-ID: On 08/26/2016 02:03 AM, Peter Otten wrote: > Jim Byrnes wrote: > >> I am working with Python 3.4.3 on Ubuntu 14.04. >> >> I am learning tkinter so I decided to rewrite a program I had written in >> pythoncard in tkinter. I found that a sqlite3 SELECT statement that >> works in pythoncard throws an error in tkinter and am wondering why? >> >> # Fill the accounts listbox from the passwords database >> def fill_accounts_lb(category): >> conn = sqlite3Connect() >> cur = conn.cursor() >> #cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY >> Account COLLATE NOCASE''', category) (1) >> cur.execute('''SELECT Account FROM pwds WHERE Category='%s' ORDER BY >> Account COLLATE NOCASE''' >> % category) >> result = [row[0] for row in cur.fetchall()] >> clearListbox() >> for account in result: >> lb_accounts.insert(END, account) >> conn.close() >> >> (1) >> Exception in Tkinter callback >> Traceback (most recent call last): >> File "/usr/lib/python3.4/tkinter/__init__.py", line 1536, in __call__ >> return self.func(*args) >> File "tk_pwds.py", line 22, in rbCall >> fill_accounts_lb('WebSites') >> File "tk_pwds.py", line 56, in fill_accounts_lb >> cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY >> Account COLLATE NOCASE''', category) >> sqlite3.ProgrammingError: Incorrect number of bindings supplied. The >> current statement uses 1, and there are 8 supplied. >> >> I cut the working statement from pythoncard and pasted it into tkinter >> and am curious why it works in the pythoncard version and not the >> tkinter version. I'm not sure where it is coming up with the 8 bindings >> it said are supplied? > > category is probably a string with eight characters. As cursor.execute() > expects a sequence as its second argument it misinterprets this string as 8 > distinct arguments. If the string were of length one your code would > (accidentally) work; this might have been the case in your other script. > The correct fix is to put even a single value into a list or tuple: See my reply to Alan as to my guess why the pythoncard script worked. > cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY > Account COLLATE NOCASE''', [category]) > > If you choose the tuple remember that a one-tuple requires a trailing comma: > > cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY > Account COLLATE NOCASE''', (category,)) > Thanks for showing me the correct way to write that statement. Regards, Jim From jf_byrnes at comcast.net Fri Aug 26 15:56:43 2016 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Fri, 26 Aug 2016 14:56:43 -0500 Subject: [Tutor] tkinter/sqlite3? In-Reply-To: References: Message-ID: On 08/26/2016 04:22 AM, Alan Gauld via Tutor wrote: > On 26/08/16 02:34, Jim Byrnes wrote: > >> Exception in Tkinter callback >> Traceback (most recent call last): > ... >> File "tk_pwds.py", line 56, in fill_accounts_lb >> cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY >> Account COLLATE NOCASE''', category) >> sqlite3.ProgrammingError: Incorrect number of bindings supplied. The >> current statement uses 1, and there are 8 supplied. >> >> I cut the working statement from pythoncard and pasted it into tkinter >> and am curious why it works in the pythoncard version and not the >> tkinter version. > > Peter has given the solution, but just to be clear this has > nothing whatsoever to do with Tkinter v Pythoncard it is > entirely a Sqlite issue. (As is evidenced in the error message.) > Did you use an older version of Sqlite when you wrote the > Pythoncard code perhaps? You probably also used an older > version of Python? > The real mystery is how it worked in the Pythoncard version, > unless, as Peter suggests, you just got lucky and always > passed a single valued item? The pythoncard version has been in use for a while so I used a desktop launcher to started it. It wasn't until I tried to run it from a terminal to see if there were any error messages, that I realized it was using python 2.7.6 and I was working with python 3.4.3. I am guessing that the different version must have caused the problem. > Finally, the string formatting solution is never a good > idea for database queries since it is (a) open to injection > attack and (b) liable to generate an incorrect SQL query > which is hard to debug. (ie the query gets executed but > returns different data to what you expected/wanted) > The DB is local to my machine so I don't think I have had a problem in the past, but now that you and Peter have shown me the correct way, I will be doing it in the future. Regards, Jim From awais.mamoon at live.com Fri Aug 26 11:54:53 2016 From: awais.mamoon at live.com (Awais Mamoon) Date: Fri, 26 Aug 2016 15:54:53 -0000 Subject: [Tutor] syntax error help Message-ID: Hi my code should be working however keeps coming up with invalid syntax but I know there isn?t one. Please help me its been 2 hours Here is my code: alphabet = 'abcdefghijklmnaopqrstuvwxyz' #gets the message from the user so it can Encrypt or Decrypt def getMessage(): print('Enter your message:') return input() #gets the key from the use so it can Encrypt or Decrypt the chosen message def getKey(): while True: print("please enter your keyword") Keyword = input() valid_Keyword = True for letter in Keyword: if (letter not in alphabet) and (letter != " "): valid_Keyword = False if valid_Keyword == False: print("you need to enter a valid keyword") if valid_Keyword == True: return Keyword def EncryptionOrDecryption(plaintext_message, Keyword): NewLetter = ("") Ciphertext = ("") PositionKeyword = 0 print('Do you wish to encrypt or decrypt') option = input() if option == "e" or "encrypt": for i in plaintext_message: if i == "": Ciphertext = Ciphertext + "" else: NewLetter = (alphabet.index(i)+1) + alphabet.index(Keyword[PositionKeyword] PositionKeyword = PositionKeyword + 1 if PositionKeyword == len(Keyword): PositionKeyword = 0 if NewLetter > 25: NewLetter = NewLetter - 26 Ciphertext = Ciphertext + alphabet[NewLetter] return Ciphertext elif option == "d" or "decrypt": for i in plaintext_message: if i == "": Ciphertext = Ciphertext + "" else: NewLetter = (alphabet.index(i)-1) + alphabet.index(Keyword[PositionKeyword]) PositionKeyword = Keyword + 1 if PositionKeyword == len(Keyword): PositionKeyword = 0 if NewLetter > 25: NewLetter = NewLetter - 26 Ciphertext = Ciphertext + alphabet[NewLetter] return Ciphertext #this makes the code abit more efficient plaintext_message = getMessage() Keyword = getKey() Ciphertext = EncryptionOrDecryption(plaintext_message, Keyword) #displays the Encyrpted/Decrypted message to the user print('Your translated text is:') print(Ciphertext) From david at graniteweb.com Fri Aug 26 18:24:53 2016 From: david at graniteweb.com (David Rock) Date: Fri, 26 Aug 2016 17:24:53 -0500 Subject: [Tutor] syntax error help In-Reply-To: References: Message-ID: <9DDB5B7A-5B89-4697-AC0C-7121968A0011@graniteweb.com> > On Mar 30, 2016, at 13:05, Awais Mamoon wrote: > > Hi my code should be working however keeps coming up with invalid syntax but > I know there isn?t one. Please help me its been 2 hours > When you run your code, what is the actual error you get (copy and paste the entire thing, please)? Where does it say the syntax error is? ? David Rock david at graniteweb.com From alan.gauld at yahoo.co.uk Fri Aug 26 19:18:02 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 27 Aug 2016 00:18:02 +0100 Subject: [Tutor] syntax error help In-Reply-To: References: Message-ID: On 30/03/16 19:05, Awais Mamoon wrote: > Hi my code should be working however keeps coming up with invalid syntax but > I know there isn?t one. You are wrong. There is. I suspect the error message tells you where it is. In future please include the full error message with your code. Look closely at this function: > def EncryptionOrDecryption(plaintext_message, Keyword): > > NewLetter = ("") > Ciphertext = ("") > PositionKeyword = 0 > print('Do you wish to encrypt or decrypt') > option = input() > > if option == "e" or "encrypt": > for i in plaintext_message: > if i == "": > Ciphertext = Ciphertext + "" > else: > NewLetter = (alphabet.index(i)+1) + > alphabet.index(Keyword[PositionKeyword] > PositionKeyword = PositionKeyword + 1 > if PositionKeyword == len(Keyword): > PositionKeyword = 0 > if NewLetter > 25: > NewLetter = NewLetter - 26 > Ciphertext = Ciphertext + alphabet[NewLetter] > return Ciphertext > > elif option == "d" or "decrypt": > for i in plaintext_message: > if i == "": > Ciphertext = Ciphertext + "" > else: > NewLetter = (alphabet.index(i)-1) + > alphabet.index(Keyword[PositionKeyword]) > PositionKeyword = Keyword + 1 > if PositionKeyword == len(Keyword): > PositionKeyword = 0 > if NewLetter > 25: > NewLetter = NewLetter - 26 > Ciphertext = Ciphertext + alphabet[NewLetter] > return Ciphertext -- 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 Sat Aug 27 00:58:18 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 27 Aug 2016 14:58:18 +1000 Subject: [Tutor] project directory structure References: <3c207ca5d6f32bfcab10f7992389942c@sonic.net> <85a8g0w3wc.fsf@benfinney.id.au> <72bddf5e702cfccb52e2776edd9c8f12@sonic.net> Message-ID: <8560qmx0yd.fsf@benfinney.id.au> Alex Kleider writes: > Am I to assume that if I have activated a virtualenv, then the > following shebang > #!/usr/bin/env python > will use the python specified in the venv/bin/? Yes, the purpose of that shebang is to tell the OS that *whichever* ?python? command is found first, is the one to use. That way it's not hard-coded, but is up to your environment (including the virtualenv) to determine at run-time which Python interperter to use. If it does not, start a new thread and we'll try to figure out what's going wrong. -- \ ?A computer once beat me at chess, but it was no match for me | `\ at kick boxing.? ?Emo Philips | _o__) | Ben Finney From jademudan at gmail.com Sat Aug 27 02:26:38 2016 From: jademudan at gmail.com (Jade Beckmann) Date: Sat, 27 Aug 2016 18:26:38 +1200 Subject: [Tutor] Running Python code without python installed Message-ID: Hi there, I'm creating a program using python that uses a GUI and I want to be able to give the file to others for them to use the program on their computer. I'm just wondering how someone who doesn't have the python software installed on their PC or mac would be able to run the program? Thanks, Jade From ben+python at benfinney.id.au Sat Aug 27 04:27:35 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 27 Aug 2016 18:27:35 +1000 Subject: [Tutor] Running Python code without python installed References: Message-ID: <85wpj2vcp4.fsf@benfinney.id.au> Jade Beckmann writes: > I'm just wondering how someone who doesn't have the python software > installed on their PC or mac would be able to run the program? The program will need the Python interpreter and standard library installed, along with any third-party libraries on which your program depends. That's a fact of how Python works. The general problem is termed ?distribution? of your Python code. See the Python Wiki for discussion of tools to help with distribution . -- \ ?Anything that we scientists can do to weaken the hold of | `\ religion should be done and may in the end be our greatest | _o__) contribution to civilization.? ?Steven Weinberg | Ben Finney From alan.gauld at yahoo.co.uk Sat Aug 27 04:34:12 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 27 Aug 2016 09:34:12 +0100 Subject: [Tutor] Running Python code without python installed In-Reply-To: References: Message-ID: On 27/08/16 07:26, Jade Beckmann wrote: > I'm just wondering how someone who doesn't have the python software > installed on their PC or mac would be able to run the program? They can't. You need the interpreter to be able to run Python code. The good news is that Macs come with Python installed so provided your code runs on that version of Python you are good to go. You need to install your code plus any extra modules (eg the GUI framework etc) On Windows its more complex and you either have to 1)provide a link for the user to download Python separately. (This is what Java users do, leaving it to the user to install Java on the computer.) or 2) Bundle the interpreter with your code so it all gets installed at once, you might create a simple installer program to do that for the user. or 3) use an exe builder tool that wraps the interpreter and your code into a single executable file. The downside of this is that if the user has several of your programs they effectively end up with multiple versions of Python installed, one per exe. But disk space is cheap these days... These approaches get easier for the user and harder for the programmer as you go down the list. Your choice... But the bottom line is that one way or another you need to get a Python interpreter on your users computer to run your code. The final option is to change your program so that it is a web app and deploy it on a server. Then you just need to distribute the URL. -- 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 wolfrage8765 at gmail.com Sat Aug 27 08:48:54 2016 From: wolfrage8765 at gmail.com (wolfrage8765 at gmail.com) Date: Sat, 27 Aug 2016 08:48:54 -0400 Subject: [Tutor] Running Python code without python installed In-Reply-To: References: Message-ID: There are actually some options here. But all of them will require some form of a installer. The only gotcha is you need an installer for each platform you plan on distributing too. So for Windows I currently use: INNO Setup Installer ( http://www.jrsoftware.org/isinfo.php ) and package the Python installer for windows with-in it; then install Python and after that is complete I install my python program; once everything is installed you can create a launcher. Inno comes with a nice little IDE to help you create the installer. It also runs well in Wine in case you are on Windows. For Linux: I use a self extracting shell installer script ( http://stephanepeter.com/makeself/ ) that runs the appropriate installation commands for Linux to get a Python interpret installed and then switch it over to Python to finish the install. But I also test for Python and 99% of the time my installer has reported that Python in some form was already installed on Linux. For OSX I have not yet tried to get my code working there; but I am fairly certain that Python is installed on most OSX installs by default it just becomes a matter of upgrading it to a more modern version. For Android and IOS I use Kivy and buildozer to create the necessary packages. Also the web app option is another good possibility; as mentioned by Alan; since HTML5 has done so much to improve the state of web applications. On Sat, Aug 27, 2016 at 2:26 AM, Jade Beckmann wrote: > Hi there, > > I'm creating a program using python that uses a GUI and I want to be able > to give the file to others for them to use the program on their computer. > I'm just wondering how someone who doesn't have the python software > installed on their PC or mac would be able to run the program? > > Thanks, > > Jade > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From akleider at sonic.net Sat Aug 27 12:06:14 2016 From: akleider at sonic.net (Alex Kleider) Date: Sat, 27 Aug 2016 09:06:14 -0700 Subject: [Tutor] project directory structure In-Reply-To: <8560qmx0yd.fsf@benfinney.id.au> References: <3c207ca5d6f32bfcab10f7992389942c@sonic.net> <85a8g0w3wc.fsf@benfinney.id.au> <72bddf5e702cfccb52e2776edd9c8f12@sonic.net> <8560qmx0yd.fsf@benfinney.id.au> Message-ID: <3fbfc95ec5779fea01aa2e244122413d@sonic.net> On 2016-08-26 21:58, Ben Finney wrote: > Alex Kleider writes: > >> Am I to assume that if I have activated a virtualenv, then the >> following shebang >> #!/usr/bin/env python >> will use the python specified in the venv/bin/? > > Yes, the purpose of that shebang is to tell the OS that *whichever* > ?python? command is found first, is the one to use. Thanks for clarifying. It was only after poking around and experimenting that I discovered that what the virtualenv activate command actually does is place its bin directory at the beginning of the PYTHONPATH environment variable- something I've no where seen explicitly documented. cheers, Alex From cs at zip.com.au Sat Aug 27 18:23:49 2016 From: cs at zip.com.au (cs at zip.com.au) Date: Sun, 28 Aug 2016 08:23:49 +1000 Subject: [Tutor] project directory structure In-Reply-To: <3fbfc95ec5779fea01aa2e244122413d@sonic.net> References: <3fbfc95ec5779fea01aa2e244122413d@sonic.net> Message-ID: <20160827222349.GA12232@cskk.homeip.net> On 27Aug2016 09:06, Alex Kleider wrote: >On 2016-08-26 21:58, Ben Finney wrote: >>Alex Kleider writes: >>>Am I to assume that if I have activated a virtualenv, then the >>>following shebang >>>#!/usr/bin/env python >>>will use the python specified in the venv/bin/? >> >>Yes, the purpose of that shebang is to tell the OS that *whichever* >>?python? command is found first, is the one to use. > >Thanks for clarifying. >It was only after poking around and experimenting that I discovered >that what the virtualenv activate command actually does is place its >bin directory at the beginning of the PYTHONPATH environment variable- >something I've no where seen explicitly documented. Shouldn't that be $PATH? It does this so that running "python" will find the virtulenv "python" command ahead of others, which is its design requirement. The venv "python" then does essentially the same thing internally with sys.path to achieve the same effect for python module imports. Cheers, Cameron Simpson From akleider at sonic.net Sun Aug 28 11:30:56 2016 From: akleider at sonic.net (Alex Kleider) Date: Sun, 28 Aug 2016 08:30:56 -0700 Subject: [Tutor] project directory structure In-Reply-To: <20160827222349.GA12232@cskk.homeip.net> References: <3fbfc95ec5779fea01aa2e244122413d@sonic.net> <20160827222349.GA12232@cskk.homeip.net> Message-ID: On 2016-08-27 15:23, cs at zip.com.au wrote: > On 27Aug2016 09:06, Alex Kleider wrote: >> On 2016-08-26 21:58, Ben Finney wrote: >>> Alex Kleider writes: >>>> Am I to assume that if I have activated a virtualenv, then the >>>> following shebang >>>> #!/usr/bin/env python >>>> will use the python specified in the venv/bin/? >>> >>> Yes, the purpose of that shebang is to tell the OS that *whichever* >>> ?python? command is found first, is the one to use. >> >> Thanks for clarifying. >> It was only after poking around and experimenting that I discovered >> that what the virtualenv activate command actually does is place its >> bin directory at the beginning of the PYTHONPATH environment variable- >> something I've no where seen explicitly documented. > > Shouldn't that be $PATH? Yes indeed- typing too quickly short circuiting the brain! Good that it's been pointed out. > It does this so that running "python" will > find the virtulenv "python" command ahead of others, which is its > design requirement. The venv "python" then does essentially the same > thing internally with sys.path to achieve the same effect for python > module imports. > > Cheers, > Cameron Simpson From zemmoura.khalil at gmail.com Sun Aug 28 05:10:51 2016 From: zemmoura.khalil at gmail.com (khalil zakaria Zemmoura) Date: Sun, 28 Aug 2016 10:10:51 +0100 Subject: [Tutor] Downloading Slack Files In-Reply-To: References: Message-ID: I noticed that you didn't store what requests downloaded in a new file you created. The usual pattern to use is to download a file and writing it to the HD drive. You have to create a file with "With open(file_name.extention, "wb") as f: " and write to that file. Here is the code that I suggest With open(filename, 'wb') as fd: for chunk in r.iter_content(chunk_size): fd.write(chunk) I apologize if the display of the email is messy since I am using Gmail on my phone. Le 17 ao?t 2016 00:56, "Malcolm Boone" a ?crit : > Hello everyone! > > I'm trying to run a python script that will download all files uploaded to > my companies Slack account from the past 30 days. I'm new to Python, so to > achieve this, I've just been editing a script that I use to delete all > Slack files from the past 30 days. > > Here is the code I'm using currently with error: > > import requests > import json > import urllib > import calendar > from datetime import datetime, timedelta > > _token = "REDACTED" > _domain = "REDACTED" > > 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 ("Downloading file" + f["name"] + "...") > timestamp = str(calendar.timegm(datetime. > now().utctimetuple())) > urllib.urlretrieve = "https://" + _domain + ". > slack.com/api/files.list" + timestamp > requests.post(urllib.urlretrieve, data = { > "token": _token, > "file": f["id"], > "set_active": "true", > "_attempts": "1"}) > print ("DONE!") > > So far, when I run this script, all that appears to be happening is it's > printing a list of all of the file names. But from what I can tell, it's > not actually downloading anything. The internet in our office isn't the > greatest and it's printing a new file name every second, but since most of > these are video files, I know that it isn't actually downloading anything > in this amount of time. I've also tried searching my PC for any of the file > names, with nothing turning up. My HD space also goes through no change > after running the script. > > The other issue, is that the script never ends (probably a simple solution, > but again I'm pretty new to this). It keeps printing the list of file names > over and over until I manually close out of Python. > > Any help would be greatly appreciated! > > I'm using a Windows 10 PC running Python 3. > _______________________________________________ > 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 Sun Aug 28 05:13:12 2016 From: zemmoura.khalil at gmail.com (khalil zakaria Zemmoura) Date: Sun, 28 Aug 2016 10:13:12 +0100 Subject: [Tutor] Downloading Slack Files In-Reply-To: References: Message-ID: Just replace r.iter_content(...) By response.iter_content(...) From shahankhan0 at gmail.com Sun Aug 28 10:46:02 2016 From: shahankhan0 at gmail.com (shahan khan) Date: Sun, 28 Aug 2016 19:46:02 +0500 Subject: [Tutor] Problem Message-ID: Hello I'm teching myself Python using MIT opencourse ware. I'm a beginner and have some what knowledge of c and c++. I'm using Python version Here is the problem: McDiophantine: Selling McNuggets In mathematics, a Diophantine equation (named for Diophantus of Alexandria, a third century Greek mathematician) is a polynomial equation where the variables can only take on integer values. Although you may not realize it, you have seen Diophantine equations before: one of the most famous Diophantine equations is: xn + yn= zn. For n=2, there are infinitely many solutions (values for x, y and z) called the Pythagorean triples, e.g. 32 + 42 = 52. For larger values of n, Fermat?s famous ?last theorem? states that there do not exist any positive integer solutions for x, y and z that satisfy this equation. For centuries, mathematicians have studied different Diophantine equations; besides Fermat?s last theorem, some famous ones include Pell?s equation, and the Erdos-Strauss conjecture. For more information on this intriguing branch of mathematics, you may find the Wikipedia article of interest. We are not certain that McDonald?s knows about Diophantine equations (actually we doubt that they do), but they use them! McDonald?s sells Chicken McNuggets in packages of 6, 9 or 20 McNuggets. Thus, it is possible, for example, to buy exactly 15 McNuggets (with one package of 6 and a second package of 9), but it is not possible to buy exactly 16 nuggets, since no non-negative integer combination of 6?s, 9?s and 20?s adds up to 16. To determine if it is possible to buy exactly n McNuggets, one has to solve a Diophantine equation: find non-negative integer values of a, b, and c, such that 6a + 9b + 20c = n. Problem 1. Show that it is possible to buy exactly 50, 51, 52, 53, 54, and 55 McNuggets, by finding solutions to the Diophantine equation. You can solve this in your head, using paper and pencil, or writing a program. However you chose to solve this problem, list the combinations of 6, 9 and 20 packs of McNuggets you need to buy in order to get each of the exact amounts. Given that it is possible to buy sets of 50, 51, 52, 53, 54 or 55 McNuggets by combinations of 6, 9 and 20 packs, show that it is possible to buy 56, 57,?, 65 McNuggets. In other words, show how, given solutions for 50-55, one can derive solutions for 56-65. Theorem: If it is possible to buy x, x+1,?, x+5 sets of McNuggets, for some x, then it is possible to buy any number of McNuggets >= x, given that McNuggets come in 6, 9 and 20 packs. Here is my code: for a in range(1,10): for b in range(1,5): for c in range(1,5): mc=(6*a)+(9*b)+(20*c) if mc==50: print a,b,c else: print a,b,c a=+1 b=b+1 c=c+1 and this is the output: 1 1 1 1 2 2 1 3 3 1 4 4 1 2 1 1 3 2 1 4 3 1 5 4 1 3 1 1 4 2 1 5 3 1 6 4 1 4 1 1 5 2 1 6 3 1 7 4 2 1 1 1 2 2 1 3 3 1 4 4 1 2 1 1 3 2 1 4 3 1 5 4 1 3 1 1 4 2 1 5 3 1 6 4 1 4 1 1 5 2 1 6 3 1 7 4 3 1 1 1 2 2 1 3 3 1 4 4 1 2 1 1 3 2 1 4 3 1 5 4 1 3 1 1 4 2 1 5 3 1 6 4 1 4 1 1 5 2 1 6 3 1 7 4 4 1 1 1 2 2 1 3 3 1 4 4 1 2 1 1 3 2 1 4 3 1 5 4 1 3 1 1 4 2 1 5 3 1 6 4 1 4 1 1 5 2 1 6 3 1 7 4 5 1 1 1 2 2 1 3 3 1 4 4 1 2 1 1 3 2 1 4 3 1 5 4 1 3 1 1 4 2 1 5 3 1 6 4 1 4 1 1 5 2 1 6 3 1 7 4 6 1 1 1 2 2 1 3 3 1 4 4 1 2 1 1 3 2 1 4 3 1 5 4 1 3 1 1 4 2 1 5 3 1 6 4 1 4 1 1 5 2 1 6 3 1 7 4 7 1 1 1 2 2 1 3 3 1 4 4 1 2 1 1 3 2 1 4 3 1 5 4 1 3 1 1 4 2 1 5 3 1 6 4 1 4 1 1 5 2 1 6 3 1 7 4 8 1 1 1 2 2 1 3 3 1 4 4 1 2 1 1 3 2 1 4 3 1 5 4 1 3 1 1 4 2 1 5 3 1 6 4 1 4 1 1 5 2 1 6 3 1 7 4 9 1 1 1 2 2 1 3 3 1 4 4 1 2 1 1 3 2 1 4 3 1 5 4 1 3 1 1 4 2 1 5 3 1 6 4 1 4 1 1 5 2 1 6 3 1 7 4. Can someone please tell me whats wrong with my code?. I'm using for loops to give possible valutes to a,b and c and then using the equation (6*a)+(9*b)+(20*c) to determine possible values for a,b and c for satisfying the equation. From joel.goldstick at gmail.com Sun Aug 28 18:20:48 2016 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 28 Aug 2016 18:20:48 -0400 Subject: [Tutor] Problem In-Reply-To: References: Message-ID: On Sun, Aug 28, 2016 at 10:46 AM, shahan khan wrote: > Hello > I'm teching myself Python using MIT opencourse ware. I'm a beginner and > have some what knowledge of c and c++. I'm using Python version > > Here is the problem: > McDiophantine: Selling McNuggets > In mathematics, a Diophantine equation (named for Diophantus of Alexandria, > a third century Greek mathematician) is a polynomial equation where the > variables can only take on integer values. Although you may not realize it, > you have seen Diophantine equations before: one of the most famous > Diophantine equations is: > xn + yn= zn. > For n=2, there are infinitely many solutions (values for x, y and z) called > the Pythagorean triples, e.g. 32 + 42 = 52. For larger values of n, > Fermat?s famous ?last theorem? states that there do not exist any positive > integer solutions for x, y and z that satisfy this equation. For centuries, > mathematicians have studied different Diophantine equations; besides > Fermat?s last theorem, some famous ones include Pell?s equation, and the > Erdos-Strauss conjecture. For more information on this intriguing branch of > mathematics, you may find the Wikipedia article of interest. > We are not certain that McDonald?s knows about Diophantine equations > (actually we doubt that they do), but they use them! McDonald?s sells > Chicken McNuggets in packages of 6, 9 or 20 McNuggets. Thus, it is > possible, for example, to buy exactly 15 McNuggets (with one package of 6 > and a second package of 9), but it is not possible to buy exactly 16 > nuggets, since no non-negative integer combination of 6?s, 9?s and 20?s > adds up to 16. To determine if it is possible to buy exactly n McNuggets, > one has to solve a Diophantine equation: find non-negative integer values > of a, b, and c, such that > 6a + 9b + 20c = n. > Problem 1. > Show that it is possible to buy exactly 50, 51, 52, 53, 54, and 55 > McNuggets, by finding solutions to the Diophantine equation. You can solve > this in your head, using paper and pencil, or writing a program. However > you chose to solve this problem, list the combinations of 6, 9 and 20 packs > of McNuggets you need to buy in order to get each of the exact amounts. > Given that it is possible to buy sets of 50, 51, 52, 53, 54 or 55 McNuggets > by combinations of 6, 9 and 20 packs, show that it is possible to buy 56, > 57,?, 65 McNuggets. In other words, show how, given solutions for 50-55, > one can derive solutions for 56-65. > Theorem: If it is possible to buy x, x+1,?, x+5 sets of McNuggets, for some > x, then it is possible to buy any number of McNuggets >= x, given that > McNuggets come in 6, 9 and 20 packs. > > Here is my code: > for a in range(1,10): > for b in range(1,5): > for c in range(1,5): > mc=(6*a)+(9*b)+(20*c) > if mc==50: > print a,b,c > else: > print a,b,c > a=+1 > b=b+1 > c=c+1 Welcome to the list. You need to format your code correctly for anyone to help you. From alan.gauld at yahoo.co.uk Sun Aug 28 19:17:20 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 29 Aug 2016 00:17:20 +0100 Subject: [Tutor] Problem In-Reply-To: References: Message-ID: On 28/08/16 15:46, shahan khan wrote: > Theorem: If it is possible to buy x, x+1,?, x+5 sets of McNuggets, for some > x, then it is possible to buy any number of McNuggets >= x, given that > McNuggets come in 6, 9 and 20 packs. > > Here is my code: > for a in range(1,10): > for b in range(1,5): > for c in range(1,5): > mc=(6*a)+(9*b)+(20*c) > if mc==50: > print a,b,c > else: > print a,b,c > a=+1 > b=b+1 > c=c+1 Its hard to be sure what you are tying to do here because the formattng is messed up. Please post in plain text. For example it could be: for a in range(1,10): for b in range(1,5): for c in range(1,5): mc=(6*a)+(9*b)+(20*c) if mc==50: print a,b,c else: print a,b,c a=+1 b=b+1 c=c+1 But its not clear why you are adding 1 to a,b and c? And I'm not sure why the inner loops are both up to 4. I don't really understand what you are trying to do or how you think this code will do it, so I can't offer you more help. Sorry. Alan g From dyoo at hashcollision.org Sun Aug 28 20:18:11 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Sun, 28 Aug 2016 17:18:11 -0700 Subject: [Tutor] Problem In-Reply-To: References: Message-ID: On Sun, Aug 28, 2016 at 7:46 AM, shahan khan wrote: > Hello > I'm teching myself Python using MIT opencourse ware. I'm a beginner and > have some what knowledge of c and c++. I'm using Python version > Here is my code: [code cut] Before showing code, try to express what you're trying to do in English first. That is, your explanation near the bottom: > I'm using for loops to give possible valutes to a,b and c and then using the equation (6*a)+(9*b)+(20*c) to determine possible values for a,b and c for satisfying the equation. ... this should actually be presented because it's the most important part! The problem with code is that code just executes. Any expectations we have about what that code does is a matter of human interpretation. Anyway, from looking at your original code (modulo indentation), I *think* the treatment as a search problem, looking for the values of the parameters a, b, c is reasonable, with the way you're doing nested for loops, > for a in range(1,10): > for b in range(1,5): > for c in range(1,5): However, I am not entirely convinced that the search bounds are actually sound. Here's why: I don't know why the numbers 1, 10, 5, and 5 were chosen in the loop: they seem arbitrary, and you need to say where those numbers came from. I suspect there's a problem with them anyway. One concrete reason why I don't think it works: change the problem slightly. Say that we're trying to find a solution for the parameters where the Diophantine equation evaluates to 6. Basically, the really simple edge case. What change would you make to your code for this simpler case? I'd assume that the simplest thing to do would be to change the target value in the test expression, from: if mc==50: ... to if mc == 6: ... Now, before we even try your program, we *know* there's a trivial solution for a, b, and c such that the equation sums to six! a = 1 b = 0 c = 0 However, looking back at program structure, we can see, even without looking at the rest of the code, that it can't possibly consider such parameters, because it's assuming that all three variables have to be positive. So that's something that we know needs to be fixed in some way. My take on the problem: this sounds very much like a question begging for a dynamic programming approach, rather than a nested loop approach. The reason I say this is because of the part of the problem statement: ############################################################### Theorem: If it is possible to buy x, x+1,?, x+5 sets of McNuggets, for some x, then it is possible to buy any number of McNuggets >= x, given that McNuggets come in 6, 9 and 20 packs. ############################################################### would be the beginning of a mathematical induction proof, which is the scent of a dynamic programming problem. I'd sketch this as follows: let's call M(n) a boolean function on the natural numbers that's true if we can buy n McNuggets by *any* combination of 6, 9, and 20 packs. We know that: * M(6) is true * M(9) is true * M(20) is true Why? Because we can take a single 6-pack, or a single 9-pack, or a single 20-pack, and each of these is a way to buy 6, 9, or 20 McNuggets. >From that core collection of knowledge, that inductive base, we can start investigating what else we can discover by building upon that knowledge inductively. Example: we know that since M(6) is true, that M(12) is true, because we can include another 6-pack to the one that built up M(6). Furthermore, we know that M(15) is true, because M(6) is true, and we can include another 9-pack to the one that built up M(6). What about M(50)? Well, not quite sure. However, I do know this: if M(50) is true, then *at least one* of the following has to be true: a. M(44) is true b. M(41) is true c. M(30) is true How in the world would we know this? Because if we were able to make 50 McNuggets out of a collection of 6, 9, or 20 packs, then we have to have picked one of those packs. And the remainder, outside of that pack, is where we get 44, 41, or 30. We don't have absolute knowledge here: it's *conditional* because we don't yet know if M(44), M(41), or M(30) is true. But it's a start. I don't want to say too much more about this. The reason is because if I state the idea just a little bit more formally, it suddenly looks a heck of a lot like a direct problem solution. But I hope that gives you some ideas. See: https://mail.python.org/pipermail/tutor/2016-July/109391.html for some links to dynamic programming material. From shahankhan0 at gmail.com Sun Aug 28 18:21:25 2016 From: shahankhan0 at gmail.com (Shahan Khan) Date: Mon, 29 Aug 2016 03:21:25 +0500 Subject: [Tutor] Problem In-Reply-To: <1472419859.1183.27.camel@gmail.com> References: <1472419859.1183.27.camel@gmail.com> Message-ID: <95A6E2CB-7FBA-4CA4-8DAB-7D604DDCA5F4@gmail.com> Thankyou so much for taking the time it really means alot. I'll change the code and try again. I have just one question what purpose does " {} " serve here? Sent from my iPhone > On 29-Aug-2016, at 2:30 AM, zakaria wrote: > > if you print the values of a, b ,c that satisfy and don't satisfy the > condiction cm == 50 at the same time, you can't know what works and > what did not work. > > here is the code that i wrote and worked well > > for a in range(1, 11): # i replaced 10 by 11 to include the 10 > for b in range(1, 6): # same as before put 6 to include 5 > for c in range(1, 6): > mc = (6*a) + (9*b) + (20*a) > if mc == 50: > print(a, b, c) > > notice that i am using python 3.5, range is a generator like xrange in > python 2 > > and the result is 2 for a and b and 1 for c > I wish this coold help you > > for what you said, here is the hard coded solution: > > for a in range(1, 11): > for b in range(1, 6): > for c in range(1, 6): > mc = 6*a + 9*b + 20*c > if mc == 50: > print('for 50 McNuggets, "a"= {}, "b"={}, "c"={}'.format(a, b, > c)) > if mc == 51: > print('for 51 McNuggets, "a"= {}, "b"={}, "c"={}'.format(a, b, > c)) > if mc == 52: > print('for 52 McNuggets, "a"= {}, "b"={}, "c"={}'.format(a, b, > c)) > if mc == 53: > print('for 53 McNuggets, "a"= {}, "b"={}, "c"={}'.format(a, b, > c)) > if mc == 54: > print('for 54 McNuggets, "a"= {}, "b"={}, "c"={}'.format(a, b, > c)) > if mc == 55: > print('for 55 McNuggets, "a"= {}, "b"={}, "c"={}'.format(a, b, > c)) > and the result was > > for 55 McNuggets, "a"= 1, "b"=1, "c"=2 > for 53 McNuggets, "a"= 1, "b"=3, "c"=1 > for 50 McNuggets, "a"= 2, "b"=2, "c"=1 > for 53 McNuggets, "a"= 4, "b"=1, "c"=1 > > > Or you can write a more elegant one: > > for a in range(1, 11): > for b in range(1, 6): > for c in range(1, 6): > mc = 6*a + 9*b + 20*c > if mc in range(50, 56): > print('for {} McNuggets, "a"= {}, "b"={}, "c"={}'.format(mc, > a, b, c)) > > i used range(50, 56) to include the value 56 > > know , i wanted to know the purpose of this code: >> a=+1 >> b=b+1 >> c=c+1 From shahankhan0 at gmail.com Sun Aug 28 18:53:45 2016 From: shahankhan0 at gmail.com (shahan khan) Date: Mon, 29 Aug 2016 03:53:45 +0500 Subject: [Tutor] Problem In-Reply-To: <95A6E2CB-7FBA-4CA4-8DAB-7D604DDCA5F4@gmail.com> References: <1472419859.1183.27.camel@gmail.com> <95A6E2CB-7FBA-4CA4-8DAB-7D604DDCA5F4@gmail.com> Message-ID: I changed the code a bit and this is the result: for a in range(1,11): for b in range(1,6): for c in range(1,6): mc=(6*a)+(9*b)+(20*c) if mc==50: print 'For 50 McNuggets:''a=',a,'b=',b,'c=',c if mc==51: print 'Fpr 51 McNuggets:''a=',a,'b=',b,'c=',c if mc==52: print 'For 52 McNuggets:''a=',a,'b=',b,'c=',c if mc==53: print 'For 53 McNuggets:''a=',a,'b=',b,'c=',c if mc==54: print 'For 54 McNuggets:''a=',a,'b=',b,'c=',c if mc==55: print 'For 55 McNuggets:''a=',a,'b=',b,'c=',c Result: For 55 McNuggets:a= 1 b= 1 c= 2 For 53 McNuggets:a= 1 b= 3 c= 1 For 50 McNuggets:a= 2 b= 2 c= 1 For 53 McNuggets:a= 4 b= 1 c= 1 Two questions: 1) why is it printing backwards? 2) why is it skipping 51,52 and 54? On Mon, Aug 29, 2016 at 3:21 AM, Shahan Khan wrote: > Thankyou so much for taking the time it really means alot. I'll change the > code and try again. I have just one question what purpose does " {} " serve > here? > > Sent from my iPhone > > > On 29-Aug-2016, at 2:30 AM, zakaria wrote: > > > > if you print the values of a, b ,c that satisfy and don't satisfy the > > condiction cm == 50 at the same time, you can't know what works and > > what did not work. > > > > here is the code that i wrote and worked well > > > > for a in range(1, 11): # i replaced 10 by 11 to include the 10 > > for b in range(1, 6): # same as before put 6 to include 5 > > for c in range(1, 6): > > mc = (6*a) + (9*b) + (20*a) > > if mc == 50: > > print(a, b, c) > > > > notice that i am using python 3.5, range is a generator like xrange in > > python 2 > > > > and the result is 2 for a and b and 1 for c > > I wish this coold help you > > > > for what you said, here is the hard coded solution: > > > > for a in range(1, 11): > > for b in range(1, 6): > > for c in range(1, 6): > > mc = 6*a + 9*b + 20*c > > if mc == 50: > > print('for 50 McNuggets, "a"= {}, "b"={}, "c"={}'.format(a, b, > > c)) > > if mc == 51: > > print('for 51 McNuggets, "a"= {}, "b"={}, "c"={}'.format(a, b, > > c)) > > if mc == 52: > > print('for 52 McNuggets, "a"= {}, "b"={}, "c"={}'.format(a, b, > > c)) > > if mc == 53: > > print('for 53 McNuggets, "a"= {}, "b"={}, "c"={}'.format(a, b, > > c)) > > if mc == 54: > > print('for 54 McNuggets, "a"= {}, "b"={}, "c"={}'.format(a, b, > > c)) > > if mc == 55: > > print('for 55 McNuggets, "a"= {}, "b"={}, "c"={}'.format(a, b, > > c)) > > and the result was > > > > for 55 McNuggets, "a"= 1, "b"=1, "c"=2 > > for 53 McNuggets, "a"= 1, "b"=3, "c"=1 > > for 50 McNuggets, "a"= 2, "b"=2, "c"=1 > > for 53 McNuggets, "a"= 4, "b"=1, "c"=1 > > > > > > Or you can write a more elegant one: > > > > for a in range(1, 11): > > for b in range(1, 6): > > for c in range(1, 6): > > mc = 6*a + 9*b + 20*c > > if mc in range(50, 56): > > print('for {} McNuggets, "a"= {}, "b"={}, "c"={}'.format(mc, > > a, b, c)) > > > > i used range(50, 56) to include the value 56 > > > > know , i wanted to know the purpose of this code: > >> a=+1 > >> b=b+1 > >> c=c+1 > From shahankhan0 at gmail.com Sun Aug 28 18:55:43 2016 From: shahankhan0 at gmail.com (shahan khan) Date: Mon, 29 Aug 2016 03:55:43 +0500 Subject: [Tutor] Problem In-Reply-To: References: Message-ID: Yes i format my code but i can't figure out this new problem On Mon, Aug 29, 2016 at 3:20 AM, Joel Goldstick wrote: > On Sun, Aug 28, 2016 at 10:46 AM, shahan khan > wrote: > > Hello > > I'm teching myself Python using MIT opencourse ware. I'm a beginner and > > have some what knowledge of c and c++. I'm using Python version > > > > Here is the problem: > > McDiophantine: Selling McNuggets > > In mathematics, a Diophantine equation (named for Diophantus of > Alexandria, > > a third century Greek mathematician) is a polynomial equation where the > > variables can only take on integer values. Although you may not realize > it, > > you have seen Diophantine equations before: one of the most famous > > Diophantine equations is: > > xn + yn= zn. > > For n=2, there are infinitely many solutions (values for x, y and z) > called > > the Pythagorean triples, e.g. 32 + 42 = 52. For larger values of n, > > Fermat?s famous ?last theorem? states that there do not exist any > positive > > integer solutions for x, y and z that satisfy this equation. For > centuries, > > mathematicians have studied different Diophantine equations; besides > > Fermat?s last theorem, some famous ones include Pell?s equation, and the > > Erdos-Strauss conjecture. For more information on this intriguing branch > of > > mathematics, you may find the Wikipedia article of interest. > > We are not certain that McDonald?s knows about Diophantine equations > > (actually we doubt that they do), but they use them! McDonald?s sells > > Chicken McNuggets in packages of 6, 9 or 20 McNuggets. Thus, it is > > possible, for example, to buy exactly 15 McNuggets (with one package of 6 > > and a second package of 9), but it is not possible to buy exactly 16 > > nuggets, since no non-negative integer combination of 6?s, 9?s and 20?s > > adds up to 16. To determine if it is possible to buy exactly n McNuggets, > > one has to solve a Diophantine equation: find non-negative integer values > > of a, b, and c, such that > > 6a + 9b + 20c = n. > > Problem 1. > > Show that it is possible to buy exactly 50, 51, 52, 53, 54, and 55 > > McNuggets, by finding solutions to the Diophantine equation. You can > solve > > this in your head, using paper and pencil, or writing a program. However > > you chose to solve this problem, list the combinations of 6, 9 and 20 > packs > > of McNuggets you need to buy in order to get each of the exact amounts. > > Given that it is possible to buy sets of 50, 51, 52, 53, 54 or 55 > McNuggets > > by combinations of 6, 9 and 20 packs, show that it is possible to buy 56, > > 57,?, 65 McNuggets. In other words, show how, given solutions for 50-55, > > one can derive solutions for 56-65. > > Theorem: If it is possible to buy x, x+1,?, x+5 sets of McNuggets, for > some > > x, then it is possible to buy any number of McNuggets >= x, given that > > McNuggets come in 6, 9 and 20 packs. > > > > Here is my code: > > for a in range(1,10): > > for b in range(1,5): > > for c in range(1,5): > > mc=(6*a)+(9*b)+(20*c) > > if mc==50: > > print a,b,c > > else: > > print a,b,c > > a=+1 > > b=b+1 > > c=c+1 > > Welcome to the list. > > You need to format your code correctly for anyone to help you. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From shahankhan0 at gmail.com Sun Aug 28 22:59:45 2016 From: shahankhan0 at gmail.com (Shahan Khan) Date: Mon, 29 Aug 2016 07:59:45 +0500 Subject: [Tutor] Problem In-Reply-To: References: Message-ID: <72A5F975-B048-4955-ACE0-0CFEDB9E09FF@gmail.com> I understand your argument. You're saying M(50),M(51)and M(52) is basically a set of 6 9 and 20 packs and we should approach it by using lower values starting from 0 for one or two variables to simply the solution on paper. I think I have some idea now as to how to approach this problem. Sent from my iPhone > On 29-Aug-2016, at 5:18 AM, Danny Yoo wrote: > >> On Sun, Aug 28, 2016 at 7:46 AM, shahan khan wrote: >> Hello >> I'm teching myself Python using MIT opencourse ware. I'm a beginner and >> have some what knowledge of c and c++. I'm using Python version > > > >> Here is my code: > [code cut] > > Before showing code, try to express what you're trying to do in > English first. That is, your explanation near the bottom: > >> I'm using for loops to give possible valutes to a,b and c and then using the equation (6*a)+(9*b)+(20*c) to determine possible values for a,b and c for > satisfying the equation. > > ... this should actually be presented because it's the most important > part! The problem with code is that code just executes. Any > expectations we have about what that code does is a matter of human > interpretation. > > > > Anyway, from looking at your original code (modulo indentation), I > *think* the treatment as a search problem, looking for the values of > the parameters a, b, c is reasonable, with the way you're doing nested > for loops, > >> for a in range(1,10): >> for b in range(1,5): >> for c in range(1,5): > > However, I am not entirely convinced that the search bounds are > actually sound. Here's why: I don't know why the numbers 1, 10, 5, > and 5 were chosen in the loop: they seem arbitrary, and you need to > say where those numbers came from. I suspect there's a problem with > them anyway. > > > One concrete reason why I don't think it works: change the problem > slightly. Say that we're trying to find a solution for the parameters > where the Diophantine equation evaluates to 6. Basically, the really > simple edge case. > > What change would you make to your code for this simpler case? I'd > assume that the simplest thing to do would be to change the target > value in the test expression, from: > > if mc==50: ... > > to > > if mc == 6: ... > > > Now, before we even try your program, we *know* there's a trivial > solution for a, b, and c such that the equation sums to six! > > a = 1 > b = 0 > c = 0 > > However, looking back at program structure, we can see, even without > looking at the rest of the code, that it can't possibly consider such > parameters, because it's assuming that all three variables have to be > positive. > > So that's something that we know needs to be fixed in some way. > > > > My take on the problem: this sounds very much like a question begging > for a dynamic programming approach, rather than a nested loop > approach. The reason I say this is because of the part of the problem > statement: > > ############################################################### > Theorem: If it is possible to buy x, x+1,?, x+5 sets of McNuggets, for some > x, then it is possible to buy any number of McNuggets >= x, given that > McNuggets come in 6, 9 and 20 packs. > ############################################################### > > would be the beginning of a mathematical induction proof, which is the > scent of a dynamic programming problem. > > > I'd sketch this as follows: let's call M(n) a boolean function on the > natural numbers that's true if we can buy n McNuggets by *any* > combination of 6, 9, and 20 packs. > > We know that: > > * M(6) is true > * M(9) is true > * M(20) is true > > Why? Because we can take a single 6-pack, or a single 9-pack, or a > single 20-pack, and each of these is a way to buy 6, 9, or 20 > McNuggets. > > From that core collection of knowledge, that inductive base, we can > start investigating what else we can discover by building upon that > knowledge inductively. > > > Example: we know that since M(6) is true, that M(12) is true, because > we can include another 6-pack to the one that built up M(6). > Furthermore, we know that M(15) is true, because M(6) is true, and we > can include another 9-pack to the one that built up M(6). > > > What about M(50)? Well, not quite sure. However, I do know this: if > M(50) is true, then *at least one* of the following has to be true: > > a. M(44) is true > b. M(41) is true > c. M(30) is true > > How in the world would we know this? > > Because if we were able to make 50 McNuggets out of a collection of 6, > 9, or 20 packs, then we have to have picked one of those packs. And > the remainder, outside of that pack, is where we get 44, 41, or 30. > > We don't have absolute knowledge here: it's *conditional* because we > don't yet know if M(44), M(41), or M(30) is true. But it's a start. > > I don't want to say too much more about this. The reason is because > if I state the idea just a little bit more formally, it suddenly looks > a heck of a lot like a direct problem solution. But I hope that gives > you some ideas. > > See: https://mail.python.org/pipermail/tutor/2016-July/109391.html for > some links to dynamic programming material. From zemmoura.khalil at gmail.com Sun Aug 28 16:34:15 2016 From: zemmoura.khalil at gmail.com (khalil zakaria Zemmoura) Date: Sun, 28 Aug 2016 21:34:15 +0100 Subject: [Tutor] Problem In-Reply-To: References: Message-ID: Can you please rewrite the python code using proper indentation, since, as you know, indentation matters in Python Le 28 ao?t 2016 18:40, "shahan khan" a ?crit : Hello I'm teching myself Python using MIT opencourse ware. I'm a beginner and have some what knowledge of c and c++. I'm using Python version Here is the problem: McDiophantine: Selling McNuggets In mathematics, a Diophantine equation (named for Diophantus of Alexandria, a third century Greek mathematician) is a polynomial equation where the variables can only take on integer values. Although you may not realize it, you have seen Diophantine equations before: one of the most famous Diophantine equations is: xn + yn= zn. For n=2, there are infinitely many solutions (values for x, y and z) called the Pythagorean triples, e.g. 32 + 42 = 52. For larger values of n, Fermat?s famous ?last theorem? states that there do not exist any positive integer solutions for x, y and z that satisfy this equation. For centuries, mathematicians have studied different Diophantine equations; besides Fermat?s last theorem, some famous ones include Pell?s equation, and the Erdos-Strauss conjecture. For more information on this intriguing branch of mathematics, you may find the Wikipedia article of interest. We are not certain that McDonald?s knows about Diophantine equations (actually we doubt that they do), but they use them! McDonald?s sells Chicken McNuggets in packages of 6, 9 or 20 McNuggets. Thus, it is possible, for example, to buy exactly 15 McNuggets (with one package of 6 and a second package of 9), but it is not possible to buy exactly 16 nuggets, since no non-negative integer combination of 6?s, 9?s and 20?s adds up to 16. To determine if it is possible to buy exactly n McNuggets, one has to solve a Diophantine equation: find non-negative integer values of a, b, and c, such that 6a + 9b + 20c = n. Problem 1. Show that it is possible to buy exactly 50, 51, 52, 53, 54, and 55 McNuggets, by finding solutions to the Diophantine equation. You can solve this in your head, using paper and pencil, or writing a program. However you chose to solve this problem, list the combinations of 6, 9 and 20 packs of McNuggets you need to buy in order to get each of the exact amounts. Given that it is possible to buy sets of 50, 51, 52, 53, 54 or 55 McNuggets by combinations of 6, 9 and 20 packs, show that it is possible to buy 56, 57,?, 65 McNuggets. In other words, show how, given solutions for 50-55, one can derive solutions for 56-65. Theorem: If it is possible to buy x, x+1,?, x+5 sets of McNuggets, for some x, then it is possible to buy any number of McNuggets >= x, given that McNuggets come in 6, 9 and 20 packs. Here is my code: for a in range(1,10): for b in range(1,5): for c in range(1,5): mc=(6*a)+(9*b)+(20*c) if mc==50: print a,b,c else: print a,b,c a=+1 b=b+1 c=c+1 and this is the output: 1 1 1 1 2 2 1 3 3 1 4 4 1 2 1 1 3 2 1 4 3 1 5 4 1 3 1 1 4 2 1 5 3 1 6 4 1 4 1 1 5 2 1 6 3 1 7 4 2 1 1 1 2 2 1 3 3 1 4 4 1 2 1 1 3 2 1 4 3 1 5 4 1 3 1 1 4 2 1 5 3 1 6 4 1 4 1 1 5 2 1 6 3 1 7 4 3 1 1 1 2 2 1 3 3 1 4 4 1 2 1 1 3 2 1 4 3 1 5 4 1 3 1 1 4 2 1 5 3 1 6 4 1 4 1 1 5 2 1 6 3 1 7 4 4 1 1 1 2 2 1 3 3 1 4 4 1 2 1 1 3 2 1 4 3 1 5 4 1 3 1 1 4 2 1 5 3 1 6 4 1 4 1 1 5 2 1 6 3 1 7 4 5 1 1 1 2 2 1 3 3 1 4 4 1 2 1 1 3 2 1 4 3 1 5 4 1 3 1 1 4 2 1 5 3 1 6 4 1 4 1 1 5 2 1 6 3 1 7 4 6 1 1 1 2 2 1 3 3 1 4 4 1 2 1 1 3 2 1 4 3 1 5 4 1 3 1 1 4 2 1 5 3 1 6 4 1 4 1 1 5 2 1 6 3 1 7 4 7 1 1 1 2 2 1 3 3 1 4 4 1 2 1 1 3 2 1 4 3 1 5 4 1 3 1 1 4 2 1 5 3 1 6 4 1 4 1 1 5 2 1 6 3 1 7 4 8 1 1 1 2 2 1 3 3 1 4 4 1 2 1 1 3 2 1 4 3 1 5 4 1 3 1 1 4 2 1 5 3 1 6 4 1 4 1 1 5 2 1 6 3 1 7 4 9 1 1 1 2 2 1 3 3 1 4 4 1 2 1 1 3 2 1 4 3 1 5 4 1 3 1 1 4 2 1 5 3 1 6 4 1 4 1 1 5 2 1 6 3 1 7 4. Can someone please tell me whats wrong with my code?. I'm using for loops to give possible valutes to a,b and c and then using the equation (6*a)+(9*b)+(20*c) to determine possible values for a,b and c for satisfying the equation. _______________________________________________ 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 Sun Aug 28 17:30:59 2016 From: zemmoura.khalil at gmail.com (zakaria) Date: Sun, 28 Aug 2016 22:30:59 +0100 Subject: [Tutor] Problem In-Reply-To: References: Message-ID: <1472419859.1183.27.camel@gmail.com> if you print the values of a, b ,c that satisfy and don't satisfy the condiction cm == 50 at the same time, you can't know what works and what did not work. here is the code that i wrote and worked well for a in range(1, 11): ? ? ? ? # i replaced 10 by 11 to include the 10? ? ? for b in range(1, 6): ? ? ?# same as before put 6 to include 5 ? ? ? ? for c in range(1, 6): ? ? ? ? ? ? mc = (6*a) + (9*b) + (20*a) ? ? ? ? ? ? if mc == 50: ? ? ? ? ? ? ? ? print(a, b, c) notice that i am using python 3.5, range is a generator like xrange in python 2 and the result is 2 for a and b and 1 for c I wish this coold help you for what you said, here is the hard coded solution: for a in range(1, 11): ? ?for b in range(1, 6): ? ? ?for c in range(1, 6): ? ? ? ?mc = 6*a + 9*b + 20*c ? ? ? ?if mc == 50: ? ? ? ? ?print('for 50 McNuggets, "a"= {}, "b"={}, "c"={}'.format(a, b, c)) ? ? ? ?if mc == 51: ? ? ? ? ?print('for 51 McNuggets, "a"= {}, "b"={}, "c"={}'.format(a, b, c)) ? ? ? ?if mc == 52: ? ? ? ? ?print('for 52 McNuggets, "a"= {}, "b"={}, "c"={}'.format(a, b, c)) ? ? ? ?if mc == 53: ? ? ? ? ?print('for 53 McNuggets, "a"= {}, "b"={}, "c"={}'.format(a, b, c)) ? ? ? ?if mc == 54: ? ? ? ? ?print('for 54 McNuggets, "a"= {}, "b"={}, "c"={}'.format(a, b, c)) ? ? ? ?if mc == 55: ? ? ? ? ?print('for 55 McNuggets, "a"= {}, "b"={}, "c"={}'.format(a, b, c)) and the result was? for 55 McNuggets, "a"= 1, "b"=1, "c"=2 for 53 McNuggets, "a"= 1, "b"=3, "c"=1 for 50 McNuggets, "a"= 2, "b"=2, "c"=1 for 53 McNuggets, "a"= 4, "b"=1, "c"=1 Or you can write a more elegant one: for a in range(1, 11): ? ?for b in range(1, 6): ? ? ?for c in range(1, 6): ? ? ? ?mc = 6*a + 9*b + 20*c ? ? ? ?if mc in range(50, 56): ? ? ? ? ?print('for {} McNuggets, "a"= {}, "b"={}, "c"={}'.format(mc, a, b, c)) i used range(50, 56) to include the value 56 know , i wanted to know the purpose of this code: > a=+1 > b=b+1 > c=c+1 From zemmoura.khalil at gmail.com Sun Aug 28 19:47:01 2016 From: zemmoura.khalil at gmail.com (zakaria) Date: Mon, 29 Aug 2016 00:47:01 +0100 Subject: [Tutor] Problem In-Reply-To: <912DCD60-6E4D-4EF5-A6FE-0F48509015F3@gmail.com> References: <1472419859.1183.27.camel@gmail.com> <912DCD60-6E4D-4EF5-A6FE-0F48509015F3@gmail.com> Message-ID: <1472428021.1183.52.camel@gmail.com> The " {} " is the place holder of the values of a, b and c argument passed to format. this example maybe can help to understand print('I like the python {}'.format('mailing-list')) will output >>> ?I like the python mailing-list The format methode will substitute the {} with the argument it takes. if you want to insert more than one string in the string 'I like python' you have to use multiple {} example: print('Il like the {} {}'.format('Python', 'mailing-list')) will output >> I like the python mailing-list you can google it under the term of "string formating python" and learn more if you want ? > 1) why is it printing backwards? it is giving that order of result because of the values that takes a, b, c in across the different iteration. the outer loop over the fisrt iteration gives set a to 1 the middel loop over the fisrt iteration gives set b to 1 the inner loop over the fisrt iteration gives set c to 1 and that dont give any result so the inner loop continue to run until it sets c to 4 witch gives the result of 55. this output is conditioned by the algorythm used > 2) why is it skipping 51,52 and 54? Are you shure those values are possible. Can you give me the values of a, b and c you calculated by hand for those different results? regards From alan.gauld at yahoo.co.uk Mon Aug 29 06:04:11 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 29 Aug 2016 11:04:11 +0100 Subject: [Tutor] Problem In-Reply-To: References: <1472419859.1183.27.camel@gmail.com> <95A6E2CB-7FBA-4CA4-8DAB-7D604DDCA5F4@gmail.com> Message-ID: On 28/08/16 23:53, shahan khan wrote: > I changed the code a bit and this is the result: > for a in range(1,11): > for b in range(1,6): > for c in range(1,6): > mc=(6*a)+(9*b)+(20*c) > if mc==50: > print 'For 50 McNuggets:''a=',a,'b=',b,'c=',c > if mc==51: > print 'Fpr 51 McNuggets:''a=',a,'b=',b,'c=',c > if mc==52: > print 'For 52 McNuggets:''a=',a,'b=',b,'c=',c > if mc==53: > print 'For 53 McNuggets:''a=',a,'b=',b,'c=',c > if mc==54: > print 'For 54 McNuggets:''a=',a,'b=',b,'c=',c > if mc==55: > print 'For 55 McNuggets:''a=',a,'b=',b,'c=',c > Result: > For 55 McNuggets:a= 1 b= 1 c= 2 > For 53 McNuggets:a= 1 b= 3 c= 1 > For 50 McNuggets:a= 2 b= 2 c= 1 > For 53 McNuggets:a= 4 b= 1 c= 1 > > Two questions: > 1) why is it printing backwards? It is printing in the order it finds them based on your loop values. So the first two have a=1, the 3rd has a=2 and the last a=4 But please post in plain text not HTML since otherwise your code format gets messed up. Alan G From dvnsarma at gmail.com Mon Aug 29 07:09:44 2016 From: dvnsarma at gmail.com (=?UTF-8?B?RC5WLk4uU2FybWEg4LCh4LC/LuCwteCwvy7gsI7gsKjgsY0u4LC24LCw4LGN4LCu?=) Date: Mon, 29 Aug 2016 16:39:44 +0530 Subject: [Tutor] Problem In-Reply-To: References: <1472419859.1183.27.camel@gmail.com> <95A6E2CB-7FBA-4CA4-8DAB-7D604DDCA5F4@gmail.com> Message-ID: The following code should do. for a in range(1,10): for b in range(1,5): for c in range(1,5): for mc in range(50, 55): if mc ==(6*a)+(9*b)+(20*c): print "mc= ",mc,"a= ",a,"b= ",b,"c=",c regards, Sarma. On Mon, Aug 29, 2016 at 3:34 PM, Alan Gauld via Tutor wrote: > On 28/08/16 23:53, shahan khan wrote: >> >> I changed the code a bit and this is the result: >> for a in range(1,11): >> for b in range(1,6): >> for c in range(1,6): >> mc=(6*a)+(9*b)+(20*c) >> if mc==50: >> print 'For 50 McNuggets:''a=',a,'b=',b,'c=',c >> if mc==51: >> print 'Fpr 51 McNuggets:''a=',a,'b=',b,'c=',c >> if mc==52: >> print 'For 52 McNuggets:''a=',a,'b=',b,'c=',c >> if mc==53: >> print 'For 53 McNuggets:''a=',a,'b=',b,'c=',c >> if mc==54: >> print 'For 54 McNuggets:''a=',a,'b=',b,'c=',c >> if mc==55: >> print 'For 55 McNuggets:''a=',a,'b=',b,'c=',c >> Result: >> For 55 McNuggets:a= 1 b= 1 c= 2 >> For 53 McNuggets:a= 1 b= 3 c= 1 >> For 50 McNuggets:a= 2 b= 2 c= 1 >> For 53 McNuggets:a= 4 b= 1 c= 1 >> >> Two questions: >> 1) why is it printing backwards? > > > It is printing in the order it finds them based on your loop values. > So the first two have a=1, the 3rd has a=2 and the last a=4 > > But please post in plain text not HTML since otherwise your code > format gets messed up. > > Alan G > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From monikajg at netzero.net Mon Aug 29 15:03:31 2016 From: monikajg at netzero.net (monikajg at netzero.net) Date: Mon, 29 Aug 2016 19:03:31 GMT Subject: [Tutor] __init__ Message-ID: <20160829.120331.26589.0@webmail08.dca.untd.com> Hi: If __init__ is not defined in a class, will it be called when creating an instance? What in a case if this class inherits from parent with __init__ and without __init__? Thank you Monika ____________________________________________________________ www.theictm.org (Sponsored by Content.Ad) 1 Fruit That "Destroys" Diabetes http://thirdpartyoffers.netzero.net/TGL3241/57c4872872749728513dst03duc From monikajg at netzero.net Mon Aug 29 17:18:17 2016 From: monikajg at netzero.net (monikajg at netzero.net) Date: Mon, 29 Aug 2016 21:18:17 GMT Subject: [Tutor] super Message-ID: <20160829.141817.12489.0@webmail09.dca.untd.com> Hi: Why in super(Child,self).setVal(value) there is Child and self in super? Why the repetition? Or should it say Parent instead of Child? In my understanding it should say Parent2 instead of Child since it refers to which parent to take the medthod from. In case of multiple inheritance it should state the class from which super will take the setVal method. Please explain what Im missing here. Thank you Monika class Paren2t(): def setVal(self, value): self.value = value class Child(Parent1, Parent2): def setVal(self, value) super(Child,self).setVal(value) ____________________________________________________________ legitfeed.com (Sponsored by Content.Ad) 10 Disturbing Things Your Nails Reveal About Your Health http://thirdpartyoffers.netzero.net/TGL3241/57c4a6dd3b01026dd4006st03duc From alan.gauld at yahoo.co.uk Mon Aug 29 18:10:30 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 29 Aug 2016 23:10:30 +0100 Subject: [Tutor] __init__ In-Reply-To: <20160829.120331.26589.0@webmail08.dca.untd.com> References: <20160829.120331.26589.0@webmail08.dca.untd.com> Message-ID: On 29/08/16 20:03, monikajg at netzero.net wrote: > If __init__ is not defined in a class, will it be called when creating an instance? > What in a case if this class inherits from parent with __init__ and without __init__? The easiest way to find out is try it and see what happens! Just put appropriate print statements in the method. Alan G From joel.goldstick at gmail.com Mon Aug 29 18:11:46 2016 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 29 Aug 2016 18:11:46 -0400 Subject: [Tutor] __init__ In-Reply-To: <20160829.120331.26589.0@webmail08.dca.untd.com> References: <20160829.120331.26589.0@webmail08.dca.untd.com> Message-ID: On Mon, Aug 29, 2016 at 3:03 PM, monikajg at netzero.net wrote: > > > Hi: > If __init__ is not defined in a class, will it be called when creating an instance? > What in a case if this class inherits from parent with __init__ and without __init__? > Thank you > Monika > ____________________________________________________________ > www.theictm.org (Sponsored by Content.Ad) > 1 Fruit That "Destroys" Diabetes > http://thirdpartyoffers.netzero.net/TGL3241/57c4872872749728513dst03duc > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor The class will be instantiated.. but no attributes will be set -- Joel Goldstick http://joelgoldstick.com/blog http://cc-baseballstats.info/stats/birthdays From steve at pearwood.info Mon Aug 29 20:30:14 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 30 Aug 2016 10:30:14 +1000 Subject: [Tutor] super In-Reply-To: <20160829.141817.12489.0@webmail09.dca.untd.com> References: <20160829.141817.12489.0@webmail09.dca.untd.com> Message-ID: <20160830003012.GB26300@ando.pearwood.info> On Mon, Aug 29, 2016 at 09:18:17PM +0000, monikajg at netzero.net wrote: > Hi: > Why in super(Child,self).setVal(value) there is Child and self in super? Why the repetition? Or should it say Parent instead of Child? > In my understanding it should say Parent2 instead of Child since it refers to which parent to take the medthod from. In case of multiple inheritance it should state the class from which super will take the setVal method. > Please explain what Im missing here. A lot :-) No, super() doesn't specify which parent to take the message from, because in multiple inheritence you normally need to take it from ALL parents: class Child(Parent1, Parent2): def setVal(self, value): Parent1.setVal(self, value) Parent2.setVal(self, value) If you're writing that, then super() is a better solution. def Child(Parent1, Parent2): def setVal(self, value): # This will automatically call both Parents super(Child, self).setVal(val) It is better because in complex class hierarchies that form a diamond shape, calling each parent by hand may cause one of the methods to be called twice. super() will avoid that. What if the method is only defined once? Let's say that Parent1 defines setVal, but Parent2 doesn't. Or worse, you're not sure whether they both have a setVal method -- at least one does, for sure, but maybe both of them do, and you're not sure which. super() to the rescue. If you always use super(), it will ensure that the method is called from each parent that has it, but not from parents that don't. (So long as at least one parent has the method.) It might help to see what Raymond Hettinger has said about super: https://rhettinger.wordpress.com/2011/05/26/super-considered-super/ Or if you prefer a video: https://www.youtube.com/watch?v=EiOglTERPEo And remember, in Python 3 (but not Python 2) you can just call super() with no arguments, and the interpreter will work out what you mean. -- Steve From steve at pearwood.info Mon Aug 29 20:42:59 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 30 Aug 2016 10:42:59 +1000 Subject: [Tutor] __init__ In-Reply-To: <20160829.120331.26589.0@webmail08.dca.untd.com> References: <20160829.120331.26589.0@webmail08.dca.untd.com> Message-ID: <20160830004259.GC26300@ando.pearwood.info> On Mon, Aug 29, 2016 at 07:03:31PM +0000, monikajg at netzero.net wrote: > > > Hi: > If __init__ is not defined in a class, will it be called when creating an instance? Yes, because the default __init__ does nothing. So if you don't need an __init__, just don't bother to write it! Try experimenting with code like this at the interactive interpreter: # Wrong, don't do this: class MyObject(): def __init__(self): # Do nothing! pass def method(self): print("called method") # Better: class MyObject(): def method(self): print("called method") obj = MyObject() > What in a case if this class inherits from parent with __init__ and without __init__? If you use super(), Python will work out what to do. So long as all the existing __init__ methods take the same arguments, use super(). If they take different arguments, you can't use super() and have to do it by hand. I see you are doing a lot of multiple inheritence (MI). I don't want to discourage you, but MI is considered an advanced subject. (Most programming languages don't even support it!) You should make sure you understand single inheritence and super() very well before tackling MI, otherwise you're likely to get confused. In any case, feel free to ask questions or ask for clarifications, and we'll answer as best we can. -- Steve From mattnewkid at gmail.com Mon Aug 29 22:22:56 2016 From: mattnewkid at gmail.com (Matthew Lehmberg) Date: Mon, 29 Aug 2016 21:22:56 -0500 Subject: [Tutor] Error help Message-ID: I've been getting this error over and over and was wondering if someone could help me fix it. [image: Inline image 1] From monikajg at netzero.net Mon Aug 29 18:52:31 2016 From: monikajg at netzero.net (monikajg at netzero.net) Date: Mon, 29 Aug 2016 22:52:31 GMT Subject: [Tutor] __init__ Message-ID: <20160829.155231.2309.0@webmail01.dca.untd.com> I cannot really try it. If I have a class without __init__ and the class does not inherit from a class that has init there is really no place for me to put print statement. IN Java if you do not have a constructor specified java calls a default constructor behind the scenes setting up memory. Does python call default __init__ if one is not defined? In two python classes that I took both teachers gave a different answers. ---------- Original Message ---------- From: Alan Gauld via Tutor To: tutor at python.org Subject: Re: [Tutor] __init__ Date: Mon, 29 Aug 2016 23:10:30 +0100 On 29/08/16 20:03, monikajg at netzero.net wrote: > If __init__ is not defined in a class, will it be called when creating an instance? > What in a case if this class inherits from parent with __init__ and without __init__? The easiest way to find out is try it and see what happens! Just put appropriate print statements in the method. Alan G _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ____________________________________________________________ oldcatlady.com (Sponsored by Content.Ad) 40 Years Later: How Do 'The Brady Bunch' Look Now? http://thirdpartyoffers.netzero.net/TGL3241/57c4bcd6864d53cd60b7ast01duc From alan.gauld at yahoo.co.uk Tue Aug 30 04:36:41 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 30 Aug 2016 09:36:41 +0100 Subject: [Tutor] Error help In-Reply-To: References: Message-ID: On 30/08/16 03:22, Matthew Lehmberg wrote: > I've been getting this error over and over and was wondering if someone > could help me fix it. [image: Inline image 1] This is a text mailing list so attachments dont get through. Plese repost with your error message cut n paste into the message. Alan G From alan.gauld at yahoo.co.uk Tue Aug 30 05:09:55 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 30 Aug 2016 10:09:55 +0100 Subject: [Tutor] __init__ In-Reply-To: <20160829.155231.2309.0@webmail01.dca.untd.com> References: <20160829.155231.2309.0@webmail01.dca.untd.com> Message-ID: On 29/08/16 23:52, monikajg at netzero.net wrote: > I cannot really try it. > If I have a class without __init__ and the class does not > inherit from a class that has init there is really no place > for me to put print statement. Fair enough but in that case there is no __init__ to call. The top level class object has an empty __init__() which does nothing, so it will be called by __new__() > IN Java if you do not have a constructor specified java > calls a default constructor behind the scenes setting up memory. Remember that init() is an initialiser, not a constructor. The constructor is the rarely seen __new__() method. It is new() that sets up the memory then calls init(). So init is only used to initialise the object after it has been constructed. > Does python call default __init__ if one is not defined? There is always one defined in object but it does nothing. There is also a default new() in object which is what sets up the memory etc and then calls init() Alan G From eryksun at gmail.com Tue Aug 30 07:50:25 2016 From: eryksun at gmail.com (eryk sun) Date: Tue, 30 Aug 2016 11:50:25 +0000 Subject: [Tutor] __init__ In-Reply-To: References: <20160829.155231.2309.0@webmail01.dca.untd.com> Message-ID: On Tue, Aug 30, 2016 at 9:09 AM, Alan Gauld via Tutor wrote: > new() that sets up the memory then calls init(). So init is > only used to initialise the object after it has been > constructed. __new__ and __init__ are called by the metaclass __call__ method. __init_ is called if __new__ returns an instance of the class. From monikajg at netzero.net Tue Aug 30 12:59:43 2016 From: monikajg at netzero.net (monikajg at netzero.net) Date: Tue, 30 Aug 2016 16:59:43 GMT Subject: [Tutor] __init__ Message-ID: <20160830.095943.32457.1@webmail12.dca.untd.com> Thank you all for your answers. The below seems contradicting to me: " in that case there is no __init__ to call. The top level class object has an empty __init__() which does nothing, so it will be called by __new__()" "It is new() that sets up the memory then calls init(). So init is only used to initialise the object after it has been constructed." "There is always one defined in object but it does nothing. There is also a default new() in object which is what sets up the memory etc and then calls init()" so a class has a default, empty __init__ and __new__. __new__ sets up memory and calls __init__. In class that has no parent: __init is called by __new__ but really does not do anything since it is empty. Assume you have a child class with no init, but it has empty, default __init__ provided by pathon and the same for its parent class. When instantiating child class, child class's __new__ calls its ___init__ in child class and then calls __init__ in parent class? Why does it not just use the default, provided by python __init__ since it found it? ---------- Original Message ---------- From: Alan Gauld via Tutor To: tutor at python.org Subject: Re: [Tutor] __init__ Date: Tue, 30 Aug 2016 10:09:55 +0100 On 29/08/16 23:52, monikajg at netzero.net wrote: > I cannot really try it. > If I have a class without __init__ and the class does not > inherit from a class that has init there is really no place > for me to put print statement. Fair enough but in that case there is no __init__ to call. The top level class object has an empty __init__() which does nothing, so it will be called by __new__() > IN Java if you do not have a constructor specified java > calls a default constructor behind the scenes setting up memory. Remember that init() is an initialiser, not a constructor. The constructor is the rarely seen __new__() method. It is new() that sets up the memory then calls init(). So init is only used to initialise the object after it has been constructed. > Does python call default __init__ if one is not defined? There is always one defined in object but it does nothing. There is also a default new() in object which is what sets up the memory etc and then calls init() Alan G _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ____________________________________________________________ Affordable Wireless Plans Set up is easy. Get online in minutes. Starting at only $14.95 per month! www.netzero.net?refcd=nzmem0216 From stefan.sette at skynet.be Tue Aug 30 05:25:44 2016 From: stefan.sette at skynet.be (fa306795@skynet.be) Date: Tue, 30 Aug 2016 11:25:44 +0200 (CEST) Subject: [Tutor] ImportError: cannot import name Message-ID: <937085769.231735.1472549144825.open-xchange@webmail.nmp.proximus.be> Hello, I use python 3.5.1 and try to import sompy and get the following error: File "C:\Anaconda3\lib\site-packages\sompy-1.0-py3.5.egg\sompy\__init__.py", line 30, in from sompy import SOMFactory ImportError: cannot import name 'SOMFactory' What could cause such an error? Thanks in advance for any suggestions. Stefan From alan.gauld at yahoo.co.uk Tue Aug 30 16:21:06 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 30 Aug 2016 21:21:06 +0100 Subject: [Tutor] __init__ In-Reply-To: References: <20160829.155231.2309.0@webmail01.dca.untd.com> Message-ID: On 30/08/16 12:50, eryksun wrote: > On Tue, Aug 30, 2016 at 9:09 AM, Alan Gauld via Tutor wrote: >> new() that sets up the memory then calls init(). So init is >> only used to initialise the object after it has been >> constructed. > > __new__ and __init__ are called by the metaclass __call__ method. > __init_ is called if __new__ returns an instance of the class. Quite so, but I didn't want to bend brains too much by mentioning metaclasses! They are confusing enough for experienced programmers let alone the typical tutor subscriber! Alan G From alan.gauld at yahoo.co.uk Tue Aug 30 16:23:55 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 30 Aug 2016 21:23:55 +0100 Subject: [Tutor] ImportError: cannot import name In-Reply-To: <937085769.231735.1472549144825.open-xchange@webmail.nmp.proximus.be> References: <937085769.231735.1472549144825.open-xchange@webmail.nmp.proximus.be> Message-ID: On 30/08/16 10:25, fa306795 at skynet.be wrote: > Hello, > I use python 3.5.1 and try to import sompy and get the following error: > > File "C:\Anaconda3\lib\site-packages\sompy-1.0-py3.5.egg\sompy\__init__.py", > line 30, in from sompy import SOMFactory > > ImportError: cannot import name 'SOMFactory' > > What could cause such an error? Thanks in advance for any suggestions. The most likely cause is that the module sompy does not contain the name SOMFactory (check the spelling...). Try >>> import sompy >>> dir(sompy) To check the available names Alan G From alan.gauld at yahoo.co.uk Tue Aug 30 16:37:44 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 30 Aug 2016 21:37:44 +0100 Subject: [Tutor] __init__ In-Reply-To: <20160830.095943.32457.1@webmail12.dca.untd.com> References: <20160830.095943.32457.1@webmail12.dca.untd.com> Message-ID: On 30/08/16 17:59, monikajg at netzero.net wrote: > Assume you have a child class with no init, but it has empty, > default __init__ provided by pathon It inherits the empty init from object. > and the same for its parent class. When instantiating child class, > child class's __new__ calls its ___init__ in child class and then > calls __init__ in parent class? Usually there is only one new in object. When new finishes constructing the empty object init() gets called. There is no magic it is just a standard method call that starts at the lowest level child and works its way up the tree until it finds an init. If all else fails it reaches the top level object.init() If any subclass has defined an init it will be called first and unless it calls super() it will be the last. > Why does it not just use the default, provided by python > __init__ since it found it? It uses the first init it finds. The last place it looks is in object which has an empty init method. Python itself does not provide a default init, it is the empty one in object that fulfills that function (since every class ultimately inherits object). I suspect that's how Java does it too since every Java class descends from Object. But I've not examined Java that closely. As eryksun has intimated there is actually another layer of magic involved in Python via the metaclass mechanism which allows us to change the mechanism by which classes are constructed. but that is way deeper than most programmers ever need to go! Remember the old adage -Keep it Simple! Alan G From monikajg at netzero.net Tue Aug 30 17:08:13 2016 From: monikajg at netzero.net (monikajg at netzero.net) Date: Tue, 30 Aug 2016 21:08:13 GMT Subject: [Tutor] __init__ Message-ID: <20160830.140813.17125.0@webmail12.dca.untd.com> OK so somebodys remark that there is a default __init__ provided was not correct. What about old style classes? When we have a class that has no parent. and it does not inherit from object since it is old class - and this class has no __init__, does __new__ call __init__? ---------- Original Message ---------- From: Alan Gauld via Tutor To: tutor at python.org Subject: Re: [Tutor] __init__ Date: Tue, 30 Aug 2016 21:37:44 +0100 On 30/08/16 17:59, monikajg at netzero.net wrote: > Assume you have a child class with no init, but it has empty, > default __init__ provided by pathon It inherits the empty init from object. > and the same for its parent class. When instantiating child class, > child class's __new__ calls its ___init__ in child class and then > calls __init__ in parent class? Usually there is only one new in object. When new finishes constructing the empty object init() gets called. There is no magic it is just a standard method call that starts at the lowest level child and works its way up the tree until it finds an init. If all else fails it reaches the top level object.init() If any subclass has defined an init it will be called first and unless it calls super() it will be the last. > Why does it not just use the default, provided by python > __init__ since it found it? It uses the first init it finds. The last place it looks is in object which has an empty init method. Python itself does not provide a default init, it is the empty one in object that fulfills that function (since every class ultimately inherits object). I suspect that's how Java does it too since every Java class descends from Object. But I've not examined Java that closely. As eryksun has intimated there is actually another layer of magic involved in Python via the metaclass mechanism which allows us to change the mechanism by which classes are constructed. but that is way deeper than most programmers ever need to go! Remember the old adage -Keep it Simple! Alan G _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ____________________________________________________________ Health News 24 (Sponsored by Content.Ad) Don't Use Botox, Use This Instead: Granny Reveals $39 Method http://thirdpartyoffers.netzero.net/TGL3241/57c5f6096912f7609373fst03duc From alan.gauld at yahoo.co.uk Tue Aug 30 19:25:42 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 31 Aug 2016 00:25:42 +0100 Subject: [Tutor] __init__ In-Reply-To: <20160830.140813.17125.0@webmail12.dca.untd.com> References: <20160830.140813.17125.0@webmail12.dca.untd.com> Message-ID: <04d26c33-996f-9739-1fc1-3846d0d51e21@yahoo.co.uk> On 30/08/16 22:08, monikajg at netzero.net wrote: > OK so somebodys remark that there is a default __init__ provided was not correct. It depends on how you interpret default. In so far as object is the default superclass (in v3) and it provides an init then there is a default, but its not part of the language per se but of the standard object model. > What about old style classes? That's a very good question and I don't know the answer. Hopefully someone else does! Alan G From steve at pearwood.info Tue Aug 30 20:25:17 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 31 Aug 2016 10:25:17 +1000 Subject: [Tutor] ImportError: cannot import name In-Reply-To: <937085769.231735.1472549144825.open-xchange@webmail.nmp.proximus.be> References: <937085769.231735.1472549144825.open-xchange@webmail.nmp.proximus.be> Message-ID: <20160831002517.GK26300@ando.pearwood.info> On Tue, Aug 30, 2016 at 11:25:44AM +0200, fa306795 at skynet.be wrote: > Hello, > I use python 3.5.1 and try to import sompy and get the following error: > > File "C:\Anaconda3\lib\site-packages\sompy-1.0-py3.5.egg\sompy\__init__.py", > line 30, in from sompy import SOMFactory > > ImportError: cannot import name 'SOMFactory' > > What could cause such an error? Thanks in advance for any suggestions. Lots of things. (1) Check the spelling. Python is case-sensitive, so SOMFactory is not the same as SomFactory or SOMfactory or somfactory. (2) Do you have your own file called "sompy.py" somewhere? If so, that will block access to the real one. (3) Are you sure that sompy supports Python 3.5? (4) Are you sure that SOMFactory actually exists? I don't see it in any of the five notebooks here: https://github.com/sevamoo/SOMPY although maybe I've missed something. It might help if you can copy and paste the FULL traceback showing exactly what line of code failed and the precise sequence of calls. Please COPY and PASTE (don't retype from memory, or summarise, and especially don't take a screenshot) the entire traceback, starting with the line Traceback (most recent call last): all the way to the end. Then we will have a better idea of what is going on. -- Steve From steve at pearwood.info Tue Aug 30 20:44:11 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 31 Aug 2016 10:44:11 +1000 Subject: [Tutor] ImportError: cannot import name In-Reply-To: <20160831002517.GK26300@ando.pearwood.info> References: <937085769.231735.1472549144825.open-xchange@webmail.nmp.proximus.be> <20160831002517.GK26300@ando.pearwood.info> Message-ID: <20160831004411.GL26300@ando.pearwood.info> On Wed, Aug 31, 2016 at 10:25:17AM +1000, Steven D'Aprano wrote: > (4) Are you sure that SOMFactory actually exists? I don't see it in any > of the five notebooks here: > > https://github.com/sevamoo/SOMPY > > although maybe I've missed something. I may have... there's a sixth notepad here: http://nbviewer.jupyter.org/gist/sevamoo/ec0eb28229304f4575085397138ba5b1 and it refers to SOMFactory. -- Steve From monikajg at netzero.net Wed Aug 31 00:05:26 2016 From: monikajg at netzero.net (monikajg at netzero.net) Date: Wed, 31 Aug 2016 04:05:26 GMT Subject: [Tutor] __init__ Message-ID: <20160830.210526.15943.1@webmail11.dca.untd.com> Somebody in this line of emails mentioned that python provides default __init__ if it its not stated in the class by the programmer. And that it is called by __new__ Then later on you corrected that. ---------- Original Message ---------- From: Alan Gauld via Tutor To: "monikajg at netzero.net" Cc: tutor at python.org Subject: Re: [Tutor] __init__ Date: Wed, 31 Aug 2016 00:25:42 +0100 On 30/08/16 22:08, monikajg at netzero.net wrote: > OK so somebodys remark that there is a default __init__ provided was not correct. It depends on how you interpret default. In so far as object is the default superclass (in v3) and it provides an init then there is a default, but its not part of the language per se but of the standard object model. > What about old style classes? That's a very good question and I don't know the answer. Hopefully someone else does! Alan G _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ____________________________________________________________ The ICTM (Sponsored by Content.Ad) Diabetes Breakthrough That Will Bankrupt Diabetes Industry http://thirdpartyoffers.netzero.net/TGL3241/57c657c7d3a4157c77d5cst01duc From monikajg at netzero.net Wed Aug 31 00:12:24 2016 From: monikajg at netzero.net (monikajg at netzero.net) Date: Wed, 31 Aug 2016 04:12:24 GMT Subject: [Tutor] generator object Message-ID: <20160830.211224.15943.2@webmail11.dca.untd.com> So generator function returns generator object according to Aaron Maxwell. But does this mean that each time yields "returns" it is a generator object? So if there are 5 yield "returns" there are 5 generator objects? Or is there always only one generator object returned by the generator functions? Can somebody please explain? Thank you Monika ---------- Original Message ---------- From: Alan Gauld via Tutor To: "monikajg at netzero.net" Cc: tutor at python.org Subject: Re: [Tutor] __init__ Date: Wed, 31 Aug 2016 00:25:42 +0100 On 30/08/16 22:08, monikajg at netzero.net wrote: > OK so somebodys remark that there is a default __init__ provided was not correct. It depends on how you interpret default. In so far as object is the default superclass (in v3) and it provides an init then there is a default, but its not part of the language per se but of the standard object model. > What about old style classes? That's a very good question and I don't know the answer. Hopefully someone else does! Alan G _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ____________________________________________________________ Health News 24 (Sponsored by Content.Ad) Granny Reveals Her Method: Don't Use Botox, Do This Instead http://thirdpartyoffers.netzero.net/TGL3241/57c65972bb39559723662st04duc From alan.gauld at yahoo.co.uk Wed Aug 31 03:56:21 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 31 Aug 2016 08:56:21 +0100 Subject: [Tutor] generator object In-Reply-To: <20160830.211224.15943.2@webmail11.dca.untd.com> References: <20160830.211224.15943.2@webmail11.dca.untd.com> Message-ID: On 31/08/16 05:12, monikajg at netzero.net wrote: > > So generator function returns generator object according to Aaron Maxwell. I don't believe that's correct. A generator function can return any kind of object including basic types like numbers, bool etc.In addition, a generator function yields values which can also be of any type. It might be valid to say that a generator function *is* a generator object, but I'll leave that distinction to the language lawyers to debate. Alan G From __peter__ at web.de Wed Aug 31 04:46:12 2016 From: __peter__ at web.de (Peter Otten) Date: Wed, 31 Aug 2016 10:46:12 +0200 Subject: [Tutor] ImportError: cannot import name References: <937085769.231735.1472549144825.open-xchange@webmail.nmp.proximus.be> Message-ID: fa306795 at skynet.be wrote: > Hello, > I use python 3.5.1 and try to import sompy and get the following error: > > File > "C:\Anaconda3\lib\site-packages\sompy-1.0-py3.5.egg\sompy\__init__.py", > line 30, in from sompy import SOMFactory > > ImportError: cannot import name 'SOMFactory' > > What could cause such an error? Thanks in advance for any suggestions. The library in question seems to be https://github.com/sevamoo/SOMPY Given a package structure sompy/ __init__.py sompy.py ... the line from sompy import SOMFactory is a relative import in Python 2 and fetches the name SOMFactory from the sompy.sompy submodule, but an absolute import in Python 3 which tries to access the (inexistent) sompy.SOMFactory from the file sompy/__init__.py. Thus it looks like SOMPY requires Python 2. From __peter__ at web.de Wed Aug 31 05:09:14 2016 From: __peter__ at web.de (Peter Otten) Date: Wed, 31 Aug 2016 11:09:14 +0200 Subject: [Tutor] generator object References: <20160830.211224.15943.2@webmail11.dca.untd.com> Message-ID: monikajg at netzero.net wrote: > So generator function returns generator object according to Aaron Maxwell. It's always nice to give a link or a quote. > But does this mean that each time yields "returns" it is a generator > object? So if there are 5 yield "returns" there are 5 generator objects? > Or is there always only one generator object returned by the generator > functions? Can somebody please explain? Thank you Monika ---------- By "generator function" he probably means something like >>> def f(): ... yield "foo" ... yield "bar" ... According to Python that's a function: >>> f Let's invoke it to see what it returns: >>> f() >>> f() >>> f() So these are indeed "generator objects", they are distinct (you get a new one on every invocation of f()) as you can verify by looking at their IDs (the hexadecimal numbers in the representation). However, the number of yield-s does not come into play yet. If there are any in the function body, it's not a "normal function", it's a "generator function". The yield-s show their effect when you iterate over the generator >>> for item in f(): print(item) ... foo bar or apply next(): >>> g = f() >>> next(g) 'foo' >>> next(g) 'bar' >>> next(g) Traceback (most recent call last): File "", line 1, in StopIteration The number of values you can get from a generator is not determined by the number of yield-s as one yield-expression may be executed more than once. The following example can run "forever": >>> def step(start, delta): ... value = start ... while True: ... yield value ... value += delta ... >>> two = step(0, 2) >>> three = step(42, 3) >>> >>> next(two) 0 >>> next(two) 2 >>> next(two) 4 >>> next(three) 42 >>> next(three) 45 >>> for a, b in zip(two, three): ... print(a, b) ... if a > 10: break ... 6 48 8 51 10 54 12 57 From steve at pearwood.info Wed Aug 31 07:24:57 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 31 Aug 2016 21:24:57 +1000 Subject: [Tutor] generator object In-Reply-To: <20160830.211224.15943.2@webmail11.dca.untd.com> References: <20160830.211224.15943.2@webmail11.dca.untd.com> Message-ID: <20160831112457.GO26300@ando.pearwood.info> On Wed, Aug 31, 2016 at 04:12:24AM +0000, monikajg at netzero.net wrote: > > So generator function returns generator object according to Aaron > Maxwell. But does this mean that each time yields "returns" it is a > generator object? So if there are 5 yield "returns" there are 5 > generator objects? Or is there always only one generator object > returned by the generator functions? > Can somebody please explain? The terminology can be confusing, because there are multiple very similar terms which are related. But fortunately, we can ask Python itself for help! Let's start by using the inspect module to take a look at an ordinary function: py> import inspect py> def func(): ... return 19 ... py> inspect.isfunction(func) True py> inspect.isgenerator(func) False py> inspect.isgeneratorfunction(func) False So that's pretty straight-forward: a regular function is just a function. What happens if we make something which people often call "a generator"? Let's make a function and use yield instead of return: py> def gen(): ... yield 19 ... py> inspect.isfunction(gen) True py> inspect.isgenerator(gen) False py> inspect.isgeneratorfunction(gen) True So there you have it: a function with "yield" inside is still a function, but it is also a "generator function". Even though people often call it "a generator", it isn't technically a generator. It's a generator function. If we call the generator function, what do we get? py> it = gen() py> inspect.isfunction(it) False py> inspect.isgenerator(it) True py> inspect.isgeneratorfunction(it) False So there we have it, all official: calling a generator FUNCTION returns a generator. But in practice, people will use the term "generator" for both generator functions like "gen", and the actual generators like "it". Normally the distinction isn't important, or it is obvious. When it isn't obvious, you can avoid ambiguity by referring to "gen" as the generator function, and "it" as the generator object. -- Steve From steve at pearwood.info Wed Aug 31 08:39:33 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 31 Aug 2016 22:39:33 +1000 Subject: [Tutor] __init__ In-Reply-To: <20160830.210526.15943.1@webmail11.dca.untd.com> References: <20160830.210526.15943.1@webmail11.dca.untd.com> Message-ID: <20160831123933.GS26300@ando.pearwood.info> On Wed, Aug 31, 2016 at 04:05:26AM +0000, monikajg at netzero.net wrote: > Somebody in this line of emails mentioned that python provides default > __init__ if it its not stated in the class by the programmer. And that > it is called by __new__ That may have been me, except I didn't mention __new__. > Then later on you corrected that. Instantiation of classes is slightly different in Python 2 and 3. In Python 3, there is only one mechanism. When you have a class, and you create an instance: instance = MyClass(args) the following happens: instance = MyClass.__new__(args) instance.__init__(args) That is a simplified description, the actual details are a bit more complicated, but if you think of it like the above, you will be okay except for the most unusual situations. Does this mean that all classes must define __new__ and __init__? No! If you don't define them, your class will inherit them from the root of the class hierarchy, "object". object has those methods built-in: py> object.__new__ py> object.__init__ and if you don't override one or both, you get the superclass method and its default behaviour. object.__new__ actually creates the instance, and object.__init__ takes no arguments and does nothing. In Python 3, writing: class MyClass(object): or just class MyClass: has the same effect. Both cases inherit from object. Things are a bit more complicated in Python 2. If you inherit from object, or from some other type that inherits from object (such as int, float, list, dict etc) then it behaves just like Python 3. But if you don't inherit from object, if you write: class MyClass: with no parent classes listed, you get the legacy Python 1 behaviour, so-called "old-style" or "classic" classes. You probably don't want to use classic classes. All sorts of things don't work with them, such as super, property, classmethod, staticmethod, and __slots__. Avoid classic classes unless you know what you are doing. In a classic class, there is no __new__ method. Only __init__ is called. If you don't write an __init__ method, Python performs a default initialisation, but there's no method involved. The interpreter has the behaviour hard-coded, unless you override it. So for both Python 3 "new-style" classes, and Python 2 "old-style" classes, writing __init__ in optional. If you don't write it, you get the default behaviour. -- Steve From steve at pearwood.info Wed Aug 31 11:23:58 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 1 Sep 2016 01:23:58 +1000 Subject: [Tutor] __init__ In-Reply-To: <20160830.140813.17125.0@webmail12.dca.untd.com> References: <20160830.140813.17125.0@webmail12.dca.untd.com> Message-ID: <20160831152358.GT26300@ando.pearwood.info> On Tue, Aug 30, 2016 at 09:08:13PM +0000, monikajg at netzero.net wrote: > OK so somebodys remark that there is a default __init__ provided was not correct. It is correct. The default __init__ is provided by object, the root of the class hierarchy. > What about old style classes? When we have a class that has no parent. > and it does not inherit from object since it is old class - and this > class has no __init__, does __new__ call __init__? For old-style classes, __new__ doesn't exist at all. The behaviour of creating a new instance is hard-coded into the interpreter, and __init__ is only called if it exists. You can define a method __new__, but it won't be called: # In Python 2 py> class NewStyle(object): ... def __new__(cls): ... print "called __new__" ... return super(NewStyle, cls).__new__(cls) ... def __init__(self): ... print "called __init__" ... py> instance = NewStyle() called __new__ called __init__ py> py> class OldStyle: ... def __new__(cls): ... print "called __new__" ... return super(OldStyle, cls).__new__(cls) ... def __init__(self): ... print "called __init__" ... py> instance = OldStyle() called __init__ In Python 3, old-style classes are gone. Even in Python 2, they're discouraged. -- Steve From sjeik_appie at hotmail.com Wed Aug 31 14:35:44 2016 From: sjeik_appie at hotmail.com (Albert-Jan Roskam) Date: Wed, 31 Aug 2016 18:35:44 +0000 Subject: [Tutor] __init__ In-Reply-To: <20160831152358.GT26300@ando.pearwood.info> References: <20160830.140813.17125.0@webmail12.dca.untd.com>, <20160831152358.GT26300@ando.pearwood.info> Message-ID: >In Python 3, old-style classes are gone. Even in Python 2, they're >discouraged. This suggests that old-style classes are still used, even in Python 3, doesn't it? albertjan at debian:~$ python3.5 Python 3.5.0 (default, Apr 13 2016, 20:39:27) [GCC 4.9.2] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import re, inspect >>> re.findall("class.+:", inspect.getsource(tkinter)) ['class Event:', 'class Variable:', 'class StringVar(Variable):', 'class IntVar(Variable):', 'class DoubleVar(Variable):', 'class BooleanVar(Variable):', 'class Misc:', 'className):', 'class(self):', 'class(self, className, sequence=None, func=None, add=None):', 'class(self, className, sequence):', 'class CallWrapper:', 'class XView:', 'class YView:', 'class Wm:', 'class Tk(Misc, Wm):', 'className):', 'class_tcl):', 'class_py):', "className='Tk', useTk=0):", 'class Pack:', 'class Place:', 'class Grid:', 'class BaseWidget(Misc):', 'classes:', 'classes:', 'class Widget(BaseWidget, Pack, Place, Grid):', 'class Toplevel(BaseWidget, Wm):', 'class Button(Widget):', 'class Canvas(Widget, XView, YView):', 'class Checkbutton(Widget):', 'class Entry(Widget, XView):', 'class Frame(Widget):', "class_' in cnf:", "class' in cnf:", 'class Label(Widget):', 'class Listbox(Widget, XView, YView):', 'class Menu(Widget):', 'class Menubutton(Widget):', 'class Message(Widget):', 'class Radiobutton(Widget):', 'class Scale(Widget):', 'class Scrollbar(Widget):', 'class Text(Widget, XView, YView):', 'class _setit:', 'class OptionMenu(Menubutton):', 'class Image:', 'class PhotoImage(Image):', 'class BitmapImage(Image):', 'class Spinbox(Widget, XView):', 'class LabelFrame(Widget):', 'class PanedWindow(Widget):'] I sometimes want to use the @property decorator in classes that inherit from e.g. tkinter.Frame. The getter then works, but the setter fails without any sign. So I then also inherit from object, as in class WickedFrame(tkinter.frame, object): @property def foo(self): return "foo" @foo.setter def foo(self, value): print("setter called") I do this in Python 2.7. Is this the recommended approach? I also like the fact that I can use super() that way. Thanks! Albert-Jan From monikajg at netzero.net Wed Aug 31 12:31:03 2016 From: monikajg at netzero.net (monikajg at netzero.net) Date: Wed, 31 Aug 2016 16:31:03 GMT Subject: [Tutor] generator object Message-ID: <20160831.093103.21019.1@webmail07.dca.untd.com> Aaron Maxwell made a clear distinction between generator function and that it returns a generator object. He emphasized that a couple of times. ---------- Original Message ---------- From: Alan Gauld via Tutor To: tutor at python.org Subject: Re: [Tutor] generator object Date: Wed, 31 Aug 2016 08:56:21 +0100 On 31/08/16 05:12, monikajg at netzero.net wrote: > > So generator function returns generator object according to Aaron Maxwell. I don't believe that's correct. A generator function can return any kind of object including basic types like numbers, bool etc.In addition, a generator function yields values which can also be of any type. It might be valid to say that a generator function *is* a generator object, but I'll leave that distinction to the language lawyers to debate. Alan G _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ____________________________________________________________ Health News 24 (Sponsored by Content.Ad) Don't Use Botox, Use This Instead: Granny Reveals $39 Method http://thirdpartyoffers.netzero.net/TGL3241/57c706939da2b6930d55st04duc From monikajg at netzero.net Wed Aug 31 12:58:42 2016 From: monikajg at netzero.net (monikajg at netzero.net) Date: Wed, 31 Aug 2016 16:58:42 GMT Subject: [Tutor] generator object Message-ID: <20160831.095842.21019.2@webmail07.dca.untd.com> Thank you everybody. This was very helpful Monika ---------- Original Message ---------- From: Steven D'Aprano To: tutor at python.org Subject: Re: [Tutor] generator object Date: Wed, 31 Aug 2016 21:24:57 +1000 On Wed, Aug 31, 2016 at 04:12:24AM +0000, monikajg at netzero.net wrote: > > So generator function returns generator object according to Aaron > Maxwell. But does this mean that each time yields "returns" it is a > generator object? So if there are 5 yield "returns" there are 5 > generator objects? Or is there always only one generator object > returned by the generator functions? > Can somebody please explain? The terminology can be confusing, because there are multiple very similar terms which are related. But fortunately, we can ask Python itself for help! Let's start by using the inspect module to take a look at an ordinary function: py> import inspect py> def func(): ... return 19 ... py> inspect.isfunction(func) True py> inspect.isgenerator(func) False py> inspect.isgeneratorfunction(func) False So that's pretty straight-forward: a regular function is just a function. What happens if we make something which people often call "a generator"? Let's make a function and use yield instead of return: py> def gen(): ... yield 19 ... py> inspect.isfunction(gen) True py> inspect.isgenerator(gen) False py> inspect.isgeneratorfunction(gen) True So there you have it: a function with "yield" inside is still a function, but it is also a "generator function". Even though people often call it "a generator", it isn't technically a generator. It's a generator function. If we call the generator function, what do we get? py> it = gen() py> inspect.isfunction(it) False py> inspect.isgenerator(it) True py> inspect.isgeneratorfunction(it) False So there we have it, all official: calling a generator FUNCTION returns a generator. But in practice, people will use the term "generator" for both generator functions like "gen", and the actual generators like "it". Normally the distinction isn't important, or it is obvious. When it isn't obvious, you can avoid ambiguity by referring to "gen" as the generator function, and "it" as the generator object. -- Steve _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ____________________________________________________________ moneynews.com (Sponsored by Content.Ad) 5 Stocks to Buy Now | Massive Market Correction http://thirdpartyoffers.netzero.net/TGL3241/57c70d06c606fd062da7st02duc From monikajg at netzero.net Wed Aug 31 13:59:25 2016 From: monikajg at netzero.net (monikajg at netzero.net) Date: Wed, 31 Aug 2016 17:59:25 GMT Subject: [Tutor] __init__ Message-ID: <20160831.105925.31443.0@webmail01.dca.untd.com> Thank you very much. This was very helpful. ---------- Original Message ---------- From: Steven D'Aprano To: tutor at python.org Subject: Re: [Tutor] __init__ Date: Wed, 31 Aug 2016 22:39:33 +1000 On Wed, Aug 31, 2016 at 04:05:26AM +0000, monikajg at netzero.net wrote: > Somebody in this line of emails mentioned that python provides default > __init__ if it its not stated in the class by the programmer. And that > it is called by __new__ That may have been me, except I didn't mention __new__. > Then later on you corrected that. Instantiation of classes is slightly different in Python 2 and 3. In Python 3, there is only one mechanism. When you have a class, and you create an instance: instance = MyClass(args) the following happens: instance = MyClass.__new__(args) instance.__init__(args) That is a simplified description, the actual details are a bit more complicated, but if you think of it like the above, you will be okay except for the most unusual situations. Does this mean that all classes must define __new__ and __init__? No! If you don't define them, your class will inherit them from the root of the class hierarchy, "object". object has those methods built-in: py> object.__new__ py> object.__init__ and if you don't override one or both, you get the superclass method and its default behaviour. object.__new__ actually creates the instance, and object.__init__ takes no arguments and does nothing. In Python 3, writing: class MyClass(object): or just class MyClass: has the same effect. Both cases inherit from object. Things are a bit more complicated in Python 2. If you inherit from object, or from some other type that inherits from object (such as int, float, list, dict etc) then it behaves just like Python 3. But if you don't inherit from object, if you write: class MyClass: with no parent classes listed, you get the legacy Python 1 behaviour, so-called "old-style" or "classic" classes. You probably don't want to use classic classes. All sorts of things don't work with them, such as super, property, classmethod, staticmethod, and __slots__. Avoid classic classes unless you know what you are doing. In a classic class, there is no __new__ method. Only __init__ is called. If you don't write an __init__ method, Python performs a default initialisation, but there's no method involved. The interpreter has the behaviour hard-coded, unless you override it. So for both Python 3 "new-style" classes, and Python 2 "old-style" classes, writing __init__ in optional. If you don't write it, you get the default behaviour. -- Steve _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ____________________________________________________________ Health News 24 (Sponsored by Content.Ad) Don't Use Botox, Use This Instead: Granny Reveals $39 Method http://thirdpartyoffers.netzero.net/TGL3241/57c71b3ecf4711b3e1670st02duc From alan.gauld at yahoo.co.uk Wed Aug 31 18:24:52 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 31 Aug 2016 23:24:52 +0100 Subject: [Tutor] generator object In-Reply-To: References: <20160830.211224.15943.2@webmail11.dca.untd.com> Message-ID: On 31/08/16 08:56, Alan Gauld via Tutor wrote: > A generator function can return any kind of object including > basic types like numbers, bool etc.In addition, a generator > function yields values which can also be of any type. Hmmm. After reading Steven's response I played around a bit. While a generator function can indeed have a return value in it I'm not sure how one would use it. I tried: def gen(x): if x > 0: return 42 else: yield x Then I tried x = gen(2) and x = list(2) But neither show any evidence of the return value. Can anyone provide a valid use-case for this feature? It definitely doesn't work the way I thought it did... But I've never needed to use return in a generator so never tried it before! What I expected/hoped it would do was act like a yield but also exit the function. No such luck. I can't even recall where I read about using returns in generator functions and what rationale was provided. It doesn't seem to be specifically discussed in the python docs. The only use I can see is to terminate the function immediately but the return value appears to disappear in smoke... -- 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 __peter__ at web.de Wed Aug 31 18:54:02 2016 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Sep 2016 00:54:02 +0200 Subject: [Tutor] generator object References: <20160830.211224.15943.2@webmail11.dca.untd.com> Message-ID: Alan Gauld via Tutor wrote: > On 31/08/16 08:56, Alan Gauld via Tutor wrote: > >> A generator function can return any kind of object including >> basic types like numbers, bool etc.In addition, a generator >> function yields values which can also be of any type. > > Hmmm. > After reading Steven's response I played around a bit. > > While a generator function can indeed have a return > value in it I'm not sure how one would use it. > > I tried: > > def gen(x): > if x > 0: return 42 > else: yield x > > Then I tried > > x = gen(2) > and > x = list(2) > > But neither show any evidence of the return value. > > Can anyone provide a valid use-case for this feature? > > It definitely doesn't work the way I thought it did... > But I've never needed to use return in a generator > so never tried it before! > > What I expected/hoped it would do was act like a > yield but also exit the function. No such luck. > > I can't even recall where I read about using returns > in generator functions and what rationale was > provided. It doesn't seem to be specifically > discussed in the python docs. The only use I > can see is to terminate the function immediately > but the return value appears to disappear in smoke... I don't have a use case, but here's how to retrieve the return value: >>> def gen(): ... return 42 ... yield ... >>> try: next(gen()) ... except StopIteration as err: print(err.value) ... 42 From alan.gauld at yahoo.co.uk Wed Aug 31 19:23:53 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 1 Sep 2016 00:23:53 +0100 Subject: [Tutor] generator object In-Reply-To: References: <20160830.211224.15943.2@webmail11.dca.untd.com> Message-ID: On 31/08/16 23:24, Alan Gauld via Tutor wrote: > Then I tried > ... > x = list(2) Should be list(gen(2)) I hope that was obvious... -- 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 Wed Aug 31 21:24:37 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 1 Sep 2016 11:24:37 +1000 Subject: [Tutor] __init__ In-Reply-To: References: <20160831152358.GT26300@ando.pearwood.info> Message-ID: <20160901012437.GU26300@ando.pearwood.info> On Wed, Aug 31, 2016 at 06:35:44PM +0000, Albert-Jan Roskam wrote: > > >In Python 3, old-style classes are gone. Even in Python 2, they're > >discouraged. > > This suggests that old-style classes are still used, even in Python 3, doesn't it? > > albertjan at debian:~$ python3.5 > Python 3.5.0 (default, Apr 13 2016, 20:39:27) > [GCC 4.9.2] on linux > Type "help", "copyright", "credits" or "license" for more information. > >>> import re, inspect > >>> re.findall("class.+:", inspect.getsource(tkinter)) > ['class Event:', 'class Variable:', 'class StringVar(Variable):', 'class IntVar(Variable):', 'class DoubleVar(Variable):', 'class BooleanVar(Variable):', 'class Misc:', 'className):', 'class(self):', 'class(self, className, sequence=None, func=None, add=None):', 'class(self, className, sequence):', 'class CallWrapper:', 'class XView:', 'class YView:', 'class Wm:', 'class Tk(Misc, Wm):', 'className):', 'class_tcl):', 'class_py):', "className='Tk', useTk=0):", 'class Pack:', 'class Place:', 'class Grid:', 'class BaseWidget(Misc):', 'classes:', 'classes:', 'class Widget(BaseWidget, Pack, Place, Grid):', 'class Toplevel(BaseWidget, Wm):', 'class Button(Widget):', 'class Canvas(Widget, XView, YView):', 'class Checkbutton(Widget):', 'class Entry(Widget, XView):', 'class Frame(Widget):', "class_' in cnf:", "class' in cnf:", 'class Label(Widget):', 'class Listbox(Widget, XView, YView):', 'class Menu(Widget):', 'class Menubutton(Widget):', 'class Message(Widget):', 'class Radiobutton(Widget):', 'class Scale(Widget):', 'class Scrollbar(Widget):', 'class Text(Widget, XView, YView):', 'class _setit:', 'class OptionMenu(Menubutton):', 'class Image:', 'class PhotoImage(Image):', 'class BitmapImage(Image):', 'class Spinbox(Widget, XView):', 'class LabelFrame(Widget):', 'class PanedWindow(Widget):'] No. A bare class with no declared parent has object automatically added, in Python 3. Compare the output of this: class K: pass print(K.__bases__) in Python 2 and Python 3, and you will see () in Python 2 (an empty tuple, i.e. no bases classes) but (,) in Python 3. > I sometimes want to use the @property decorator in classes that > inherit from e.g. tkinter.Frame. The getter then works, but the setter > fails without any sign. So I then also inherit from object, as in > > class WickedFrame(tkinter.frame, object): [...] > I do this in Python 2.7. Is this the recommended approach? I also like the fact that I can use super() that way. I believe that is fine. -- Steve From bcallow at lindenwold.k12.nj.us Wed Aug 31 21:29:31 2016 From: bcallow at lindenwold.k12.nj.us (Bryan Callow) Date: Wed, 31 Aug 2016 21:29:31 -0400 Subject: [Tutor] Help with NameError Message-ID: Could someone help me with a NameError that I can't seem to figure out. The program asks for an input and then runs two DC motors. It worked for a while and then when I reopened the program today I keep getting this error. Thank you. -Bryan import RPi.GPIO as GPIO from time import sleep GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) Motor1A = 16 Motor1B = 18 Motor1E = 22 Motor2A = 11 Motor2B = 13 Motor2E = 15 GPIO.setup(Motor1A,GPIO.OUT) GPIO.setup(Motor1B,GPIO.OUT) GPIO.setup(Motor1E,GPIO.OUT) GPIO.setup(Motor2A,GPIO.OUT) GPIO.setup(Motor2B,GPIO.OUT) GPIO.setup(Motor2E,GPIO.OUT) forward = ['f', 'F'] backward = ['b', 'B'] exit_ = ['e', 'E'] print('Which direction would you like to move?') direction = input("Type 'f' for forward, 'b' for backward, or 'e' to exit: ") while direction not in exit_: if direction in forward: print('Moving Forward!') GPIO.output(Motor1A,GPIO.HIGH) GPIO.output(Motor1B,GPIO.LOW) GPIO.output(Motor1E,GPIO.HIGH) GPIO.output(Motor2A,GPIO.HIGH) GPIO.output(Motor2B,GPIO.LOW) GPIO.output(Motor2E,GPIO.HIGH) sleep(2) print ("Stopping!") GPIO.output(Motor1E,GPIO.LOW) GPIO.output(Motor2E,GPIO.LOW) if direction in backward: print('Moving Backward!') GPIO.output(Motor1A,GPIO.LOW) GPIO.output(Motor1B,GPIO.HIGH) GPIO.output(Motor1E,GPIO.HIGH) GPIO.output(Motor2A,GPIO.LOW) GPIO.output(Motor2B,GPIO.HIGH) GPIO.output(Motor2E,GPIO.HIGH) sleep(2) print ("Stopping!") GPIO.output(Motor1E,GPIO.LOW) GPIO.output(Motor2E,GPIO.LOW) sleep(1) print('Which direction would you like to move?') direction = input("Type 'f' for forward, 'b' for backward, or 'e' to exit: ") print('done') From unee0x at gmail.com Wed Aug 31 23:18:06 2016 From: unee0x at gmail.com (kay Cee) Date: Wed, 31 Aug 2016 23:18:06 -0400 Subject: [Tutor] Inheritance vs Assignment Message-ID: <7BD64E0E-1FD4-4010-8E1F-5414D1BCA634@gmail.com> Suppose there is -----> Class a(): def__init__(self, var): pass Class b(a): def__init__(self): super().__init__(self, var) pass Note: syntax may be incorrect ... Is it better to do b = a() Instead of making b its own class? Also, what would be the benefit of making a separate class for b if any at all? Thanks in advance .... Unee0x