Re: [Tutor] Which is better in principle: to store (in file) calculated data or to re-calculate it upon restarting program?
On Tue, Jul 30, 2019 at 7:26 PM Mats Wichmann wrote: > > On 7/30/19 5:58 PM, Alan Gauld via Tutor wrote: > > On 30/07/2019 17:21, boB Stepp wrote: > > > >> musings I am wondering about -- in general -- whether it is best to > >> store calculated data values in a file and reload these values, or > >> whether to recalculate such data upon each new run of a program. > > > > It depends on the use case. > > > > For example a long running server process may not care about startup > > delays because it only starts once (or at least very rarely) so either > > approach would do but saving diskspace may be helpful so calculate the > > values. > > > > On the other hand a data batch processor running once as part of a > > chain working with high data volumes probably needs to start quickly. > > In which case do the calculations take longer than reading the > > extra data? Probably, so store in a file. > > > > There are other options too such as calculating the value every > > time it is used - only useful if the data might change > > dynamically during the program execution. > > > > It all depends on how much data?, how often it is used?, > > how often would it be calculated? How long does the process > > run for? etc. > > > Hey, boB - I bet you *knew* the answer was going to be "it depends" :) You are coming to know me all too well! ~(:>)) I just wanted to check with the professionals here if my thinking (Concealed behind the asked questions.) was correct or, if not, where I am off. > There are two very common classes of application that have to make this > very decision - real databases, and their toy cousins, spreadsheets. > > In the relational database world - characterized by very long-running > processes (like: unless it crashes, runs until reboot. and maybe even > beyond that - if you have a multi-mode replicated or distributed DB it > may survive failure of one point) - if a field is calculated it's not > stored. Because - what Alan said: in an RDBMS, data are _expected_ to > change during runtime. And then for performance reasons, there may be > some cases where it's precomputed and stored to avoid huge delays when > the computation is expensive. That world even has a term for that: a > materialized view (in contrast to a regular view). It can get pretty > tricky, you need something that causes the materialized view to update > when data has changed; for databases that don't natively support the > behavior you then have to fiddle with triggers and hopefully it works > out. More enlightened now? Not more enlightened, perhaps, but more convinced than ever on how difficult it is to manage the complexity of real world programs. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Which is better in principle: to store (in file) calculated data or to re-calculate it upon restarting program?
On Tue, Jul 30, 2019 at 7:05 PM Alan Gauld via Tutor wrote: > > On 30/07/2019 18:20, boB Stepp wrote: > > > What is the likelihood of file storage corruption? I have a vague > > sense that in earlier days of computing this was more likely to > > happen, but nowadays? Storing and recalculating does act as a good > > data integrity check of the file data. > > No it doesn't! You are quite likely to get a successful calculation > using nonsense data and therefore invalid results. But they look > valid - a number is a number... Though I may be dense here, for the particular example I started with the total score in a solitaire game is equal to the sum of all of the preceding scores plus the current one. If the data in the file somehow got mangled, it would be an extraordinary coincidence for every row to yield a correct total score if that total score was recalculated from the corrupted data. But the underlying question that I am trying to answer is how likely/unlikely is it for a file to get corrupted nowadays? Is it worthwhile verifying the integrity of every file in a program, or, at least, every data file accessed by a program every program run? Which leads to your point... > Checking data integrity is what checksums are for. When should this be done in normal programming practice? -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Which is better in principle: to store (in file) calculated data or to re-calculate it upon restarting program?
On Tue, Jul 30, 2019 at 12:05 PM Zachary Ware wrote: > > On Tue, Jul 30, 2019 at 11:24 AM boB Stepp wrote: > > In this trivial example I cannot imagine there is any realistic > > difference between the two approaches, but I am trying to generalize > > my thoughts for potentially much more expensive calculations, very > > large data sets, and what is the likelihood of storage errors > > occurring in files. Any thoughts on this? > > As with many things in programming, it comes down to how much time you > want to trade for space. If you have a lot of space and not much > time, store the calculated values. If you have a lot of time (or the > calculation time is negligible) and not much space, recalculate every > time. If you have plenty of both, store it and recalculate it anyway What is the likelihood of file storage corruption? I have a vague sense that in earlier days of computing this was more likely to happen, but nowadays? Storing and recalculating does act as a good data integrity check of the file data. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Which is better in principle: to store (in file) calculated data or to re-calculate it upon restarting program?
I have been using various iterations of a solitaire scorekeeper program to explore different programming thoughts. In my latest musings I am wondering about -- in general -- whether it is best to store calculated data values in a file and reload these values, or whether to recalculate such data upon each new run of a program. In terms of my solitaire scorekeeper program is it better to store "Hand Number, Date, Time, Score, Total Score" or instead, "Hand Number, Date, Time, Score"? Of course I don't really need to store hand number since it is easily determined by its row/record number in its csv file. In this trivial example I cannot imagine there is any realistic difference between the two approaches, but I am trying to generalize my thoughts for potentially much more expensive calculations, very large data sets, and what is the likelihood of storage errors occurring in files. Any thoughts on this? TIA! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Unit testing: Just the API or internal use only methods, too?
Peter Otten, while responding to one of my questions in the past, mentioned something in passing that apparently has been mulling around in the back of my head. I don't recall his exact words, but he essentially said that I should be testing the public interface to my classes, but not the methods only used internally by the class and not meant to be publicly accessible. Is this generally how I should be viewing testing? Would someone be willing to expand at some length on this topic? TIA! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python 3.7 Grids
On Sat, Jun 29, 2019 at 2:02 AM David Merrick wrote: > > Hi Looking for a way to use the determine the position of a card in a grid > using the mouse click event in Python. Code is attached. There are no > viruses. > > Unfortunately using Tinkter grids / frames can't determine between the two > demo cards. As Bob Gailer mentioned this is a text only list which does not allow attachments, so I cannot see what you are actually attempting with your code. But with what you said, two thoughts come to my mind: 1) You can embed each card image on a button widget and if such a button is clicked have the button's callback function respond accordingly. 2) tkinter allows you to know the size of your window and can report back what the cursor's current position is. If you ensure that your cards take up a known coordinate space in the window, when a mouse click event happens you can write code to determine if the cursor fell within either card's known coordinate space. Hope this gives you some idea of how to tackle your problem. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Query about python recipies for practices
On Sun, May 19, 2019 at 12:55 PM bijaya dalei <2212bij...@gmail.com> wrote: > > Hii, Good morning. I am a new user of python programming language. I have a > small query on "where to get python recepies for practices".plz > suggest.Thanks. It is not very clear to me what you are asking for, which may be why you have not gotten any responses so far. ActiveState used to have a Python "recipe" section. Apparently it has been moved to a GitHub repository at https://github.com/ActiveState/code I own a book, "Python Cookbook, 3rd ed." by Beazley and Jones. Perhaps that might help? Some cautionary words of warning: If this is an obscure way of getting a pre-packaged homework solution, then you are doing yourself a grave disservice! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looking for some direction
On Sun, May 12, 2019 at 5:19 PM boB Stepp wrote: > > On Sun, May 12, 2019 at 1:05 PM David L Neil > wrote: > > > I'm using Gnome Terminal under Fedora (Linux). This allows multiple > > terminals in tabs (and thus Ctrl-Tab rapid-switching). However, it > > irritates me that whilst I can set "profiles" for particular purposes; > > there does not seem to be a way to save a 'session'. Thus each time > > Terminal re-starts, I have to re-build each terminal, manually. > > > > (suggestions of other similar tools would be most welcome) > > I may be mistaken, but I think that a terminal multiplexer like tmux > (https://github.com/tmux/tmux/wiki) is capable of session management. > I have no personal use of tmux, but have been intrigued enough about > others referring to it that eventually I will get around to seriously > checking it out. Actually, tmux is starting to look more and more interesting. David, I think you might this helpful. I am currently looking at an introduction to tmux by a Stack Overflow developer. This article is at https://www.hamvocke.com/blog/a-quick-and-easy-guide-to-tmux/ (There was a link to this on the tmux wiki I sent out a link to earlier.) I think I may start playing around with this! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looking for some direction
On Sun, May 12, 2019 at 1:05 PM David L Neil wrote: > I'm using Gnome Terminal under Fedora (Linux). This allows multiple > terminals in tabs (and thus Ctrl-Tab rapid-switching). However, it > irritates me that whilst I can set "profiles" for particular purposes; > there does not seem to be a way to save a 'session'. Thus each time > Terminal re-starts, I have to re-build each terminal, manually. > > (suggestions of other similar tools would be most welcome) I may be mistaken, but I think that a terminal multiplexer like tmux (https://github.com/tmux/tmux/wiki) is capable of session management. I have no personal use of tmux, but have been intrigued enough about others referring to it that eventually I will get around to seriously checking it out. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Local variable look up outside the function and method
On Sun, May 12, 2019 at 8:05 AM Arup Rakshit wrote: > > In the following the function, x is reachable outside the scope of foo > function. > > In [1]: x = 10 > > In [2]: def foo(): >...: return x >...: > > In [3]: print(foo()) > 10 To what the others have said I wish to point out that if x is reassigned _inside the function_ x's scope is now local inside the function while x also still has a module scope. Consider: 3.6.8: x = 10 3.6.8: def foo(): ... x = 5 ... print("In foo x =", x) ... 3.6.8: foo() In foo x = 5 3.6.8: print("In module scope, x =", x) In module scope, x = 10 boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Collating date data from a csv file
On Wed, May 8, 2019 at 10:29 PM boB Stepp wrote: > > On Wed, May 8, 2019 at 10:09 PM Cameron Simpson wrote: > > > > A defaultdict is a dict which magicly makes missing elements when they > > get access, using a factory function you supply. Here we're using "int" > > as that factory, as int() returns zero. > > Is int() guaranteed to always return zero as Python versions progress? > More importantly, perhaps, where would I go to look to find the > answer to this question myself? It must be time to go to bed! Somehow my eyes missed the int() return behavior at https://docs.python.org/3/library/functions.html#int my first time through. Sorry for the noise! > boB -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Collating date data from a csv file
On Wed, May 8, 2019 at 10:09 PM Cameron Simpson wrote: > > A defaultdict is a dict which magicly makes missing elements when they > get access, using a factory function you supply. Here we're using "int" > as that factory, as int() returns zero. Is int() guaranteed to always return zero as Python versions progress? More importantly, perhaps, where would I go to look to find the answer to this question myself? -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Off-Topic: Tutor group specific to Java
On Wed, Apr 17, 2019 at 11:09 AM Karthik Bhat wrote: > > Hello Guys, > This is kind of off-topic, but I would really appreciate it if > anyone could provide me with a tutor mailing list/group specific to Java. > I am a beginner, and it would be really helpful for me. Try Java Ranch: https://javaranch.com/ -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Questions about the deprecation of standard library modules
While reading in chapter 3 of "Learning Python, 5th ed." by Mark Lutz, I was playing around with reload() in the imp module. In the interpreter I did a "from imp import reload" and then help(reload). This had a warning that it was deprecated. After a search online I found that the entire imp library was deprecated since Python 3.4. The aforementioned book covers through Python 3.3. This got me to wondering when the imp module would be removed from Python 3, which led me to finding PEP 4. In it it says: Module name: imp Rationale: Replaced by the importlib module. Date: 2013-02-10 Documentation: Deprecated as of Python 3.4. There is no mention as to _when_ the module might be removed. PEP 4 says that a deprecated module may be removed as early as the next Python release after it becomes deprecated. Also the PEP states that if a module exists in both Python 2.7 and Python 3.5, it will not be removed until Python 2.7 is no longer supported, which, I suppose, means next year. So my main question is how does one know in which Python version a deprecated module will be removed? I'm not too concerned about the imp module, but _do_ want to know how the removal process works for deprecated standard library modules that I might be interested in. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] [OT] Problem with auto-complete package installation in Atom [Was: Re: After virtualenv, how to use ide]
On Sun, Mar 24, 2019 at 8:51 PM anand warik wrote: > > I am sorry for not sticking to my original question but editors are > complicated in itself. So many costimization instruction to read through just > to finally execute a simple .Py file which can be just executed using the > terminal. > > I am sorry I didn't documented my details about the system, but I certainly > lost the track through how I installed Anaconda for Spyder and then atom. > Next time onwards would me more careful. > > It's true I am not professional programmer and therefore trying to make sense > of the big picture when learning programming from various sources. Picking up > pieces from here and there and applying on the system only to forget how at > all I did it in first place. > > Sorry for the inconvenience caused, will be careful next time My intent was not to criticize you, but to help you have the best chance of getting help and to briefly share my struggles to settle on a coding editor. There is nothing to be sorry about! You certainly caused me no inconvenience!! Just because an editor you might use has plenty of customization options and be overly packed with features does not usually mean you need to concern yourself with them, especially starting out. As long as you can create a text file easily and save it where you want to save it, you can use it. You can always run your program from the terminal and many think that is a good idea to do anyway. Sometimes when you run a program from within the editor/IDE it can hide some issues from you. Most editors/IDEs come preset out of the box, so to speak, to be able to do sensible syntax highlighting, etc., so you can worry about fine tuning these things later when you have time and inclination. As for forgetting things, I am a past master at this! But I keep chugging along and people here are quite patient with me. But it pays to try to focus on the details of what you are doing programming-wise as the whole process can and does crash for want of an overlooked detail. Or, in my case, many overlooked details! Keep trying and always try to give the best, most helpful description of problems you are experiencing, what you expected to happen and what actually did happen, so that you have the best chance of getting useful help. Take care! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to avoid "UnboundLocalError: local variable 'goal_year' referenced before assignment"?
Oh, happy day! eval() has been expunged from my program!! I will now continue from where I left off earlier. On Sun, Mar 24, 2019 at 12:22 AM Cameron Simpson wrote: > > On 23Mar2019 22:15, boB Stepp wrote: > > The lambda is just a single line function definition, and doesn't get a > function name. > So your get_input name now accepts a "date_constructor" parameter and > you would change the input step from this: > > try: > identifier = int(input(input_prompt)) > if date_value_err_ck: > date(*date_value_err_ck) > except ValueError: > > to this: > > try: > value = int(input(input_prompt)) > date = date_constructor(value) > except ValueError: You could not know this from the code I showed (As I pared it down to illustrate my problem.), but I am also using get_input() to pull in from the user non-date values, too, but they are also all integers: pages_read and total_pages_to_read. Because of this, for these latter two items, "date_value_err_ck" will be assigned "None", which is why I have the "if date_value_err_ck:". > So you're passing in a function to make the date, and only calling it > once you've read in the value. > > This solves your use of goal_year before it is defined in 2 ways: it > doesn't use the value before the call to get_input and also the name > "goal_year" in the constructor function is local to that function - it > may as well be called "year". > > Now to your conditions. You have: > > 'conditions': [ > ('goal_year < date.today().year', > "Have you invented a time machine? If not, please enter a" > " year that makes more sense!"), > ('goal_year >= date.today().year + 100', > "Have you discovered the secret to eternal life? And how" > " long is this book anyway? Please enter a year that" > " makes more sense.")]} > > These seem to be tests for bad values (personally I tend to write tests > for good values, but this is an arbitrary choice). These should also be > written as lambdas: I just like writing corny error messages in response to bad values. ~(:>)) > But wait, there's more! > > After you have phase 1 complete (inputting goal_year) you then want > goal_month. > > Let me introduce you to the closure: > > For the goal_year you have the year-based constructor using only the > input value: > > 'date_constructor': lambda goal_year: datetime.date(goal_year, 1, 1), > > in your setup dict. For the goal_month you want both the goal_year and > the input value. So... > > 'date_constructor': lambda goal_month: datetime.date(goal_year, > goal_month, 1), > > But, I hear you ask, I'm not passing in the goal_year to the get_input() > for the month value! Indeed, your code will look like this: > > goal_year_params = { > > 'date_constructor': lambda goal_year: datetime.date(goal_year, 1, 1), > > } > goal_year = get_input(**goal_year_params) > goal_month_params = { > > 'date_constructor': lambda goal_month: datetime.date(goal_year, > goal_month, 1), > > } > goal_month = get_input(**goal_month_params) > > That's your plan, yes? You understand me perfectly! > Well, when you define the goal_month constructor lambda function, > goal_year _is_ a local variable. And _because_ it is not a parameter of > the lambda, the lambda finds it in the scope where it was defined: the > scope at the bottom of your programme. > > This is called a "closure": functions has access to the scope they are > define in for identifiers not locally defined (eg in the parameters or > the function local variables - which are those assigned to in the code). This is so cool and useful! I recall seeing this mentioned for nested functions, but did not know it worked for lambdas as well. This has been incredibly helpful and educational! Many thanks!! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] [OT] Problem with auto-complete package installation in Atom [Was: Re: After virtualenv, how to use ide]
On Sun, Mar 24, 2019 at 2:45 AM anand warik wrote: > > I gave up on Spyder and shifted to Atom, which seems easy to port to > different versions of python created by virtual environments. But now facing > a new problem. I have installed a package named autocomplete-python on atom > but it doesn't seem to work. I checked few links on stackoverflow as well but > still the problem persists. Can someone help me with this? This is actually a question about the Atom code editor, not one about Python, so it is really off-topic for this forum as well as unrelated to your originating topic. However, Tutor is a friendly place, so if someone knows much about Atom, I am sure they will try to help. But I must say, you did not give anyone much information to enable such help to happen. "... but it doesn't seem to work..." is an extraordinarily vague problem description! So you may wish to flesh out the details of your exact problem if you seek help here or elsewhere. But that is not what I wish to discuss. I am going to assume that you are not a professional programmer. If that is incorrect, I profusely apologize in advance! But that is okay. I am not a professional nor expert programmer myself. Because of this, I recall agonizing over the choice of code editor, or, possibly even worse, deciding whether to use an IDE or editor. This is a difficult decision about which many wax poetic and express their opinions with great emotion. If you wish to be amused, just do a search for Emacs vs. Vim editor wars! So the reality of it, whether you are a non-expert like me or a professional coder, choice of editor/IDE is an intensely personal choice. You will spend many hours/days/weeks/months/years/... of your life staring at your choice of editor/IDE, so you should pick something that works well for you. But editor hopping is not the answer! Instead, I would advise you to carefully evaluate your actual *needs*, and cull that list down to something that satisfies your sense of aesthetics. In my case I write some programs to make my life easier at work (*not* programming related). While there my time is split between PCs that are Windows-based and thin-clients connecting to a Solaris-based server. Whatever editor I use at work needs to be available in both environments, and the Solaris one does *not* allow me to install any new software, so it became my primary determinant of editor. When it came down to it, the only substantial code editing support was limited to vi until recently when our servers were upgraded with a newer version of Solaris (Yay!) which came with Vim/gVim. On the other hand, when I do my actual "fun" programming and learning, I mostly do that at home where I can install anything I like. So initially I tried all kinds of editors and IDEs and wasted quite a lot of time! And I did not get comfortable with anything. So I finally decided to just stick with vi/Vim/gVim/Neovim. The point is to stick with something long enough that you can realize its full potential, or, at least work your way in that direction. So, research your needs, both current and future. From that short list select what you will enjoy interacting with on a daily basis. BTW, back to Atom: Your question(s) about it would probably get better results on whatever forums are devoted to it. I am sure there will be at least one if not more. Cheers! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to avoid "UnboundLocalError: local variable 'goal_year' referenced before assignment"?
Ah! After another long break from coding, I resume a pattern of one step forward, who knows how many steps back, as I forget what I once remembered and understood. It is the wee morning hours where I am at, so I don't think I will make it through everything, but I will make a start... On Sun, Mar 24, 2019 at 12:22 AM Cameron Simpson wrote: > > Discussion below your post here, since I feel I should quote it all: > > On 23Mar2019 22:15, boB Stepp wrote: > >Traceback (most recent call last): > > File "pages_per_day.py", line 250, in > >start_pgm() > > File "pages_per_day.py", line 246, in start_pgm > >goal_date_obj, pages_read, total_pages_to_read = get_inputs() > > File "pages_per_day.py", line 63, in get_inputs > >'date_value_err_ck': (goal_year, 1, 1), > >UnboundLocalError: local variable 'goal_year' referenced before assignment > > > >I understand this result, but cannot come up with a way to implement > >my desired DRY strategy as I am stuck on how to get around this "local > >variable ... referenced before assignment" issue. On subsequent > >passes "goal_year" will become "goal_month" and then "goal_day" as the > >user needs to input all three of these numbers. Is there a way to > >accomplish my goal or am I attempting to be too clever? > > You're not attemnpting to be too clever, but you are making some basic > errors. For example, you can't just run a string like 'goal_year < > date.today).year' and you shouldn't be trying i.e. do _not_ reach for > the eval() function. Too late! About the time your message hit my inbox, I just finished a working replacement after pulling the the eval() trigger. I found a non-eval() workaround for dealing with date(*date_value_err_ck), but could not come up with anything better than using eval(condition.format(user_input)) to replace the "if condition:", where the embedded "{0}" in "condition" from the calling code is being used to pass in the actual user input value. I imagine a clever user (other than myself) could now wreak all sorts of havoc! I totally got rid of "identifier" as an argument. > Let's look at your get_input() function. It basicly loops until you get > a value you're happy with, and returns that value. Or it would if it > were correct. Let's examine the main loop body: > > try: > identifier = int(input(input_prompt)) > if date_value_err_ck: > date(*date_value_err_ck) > except ValueError: > print(err_msg) > continue > for (condition, condition_msg) in conditions: > if condition: > print(condition_msg) > break > else: > return identifier > > To start with, you have confusion in the code bwteen the name you're > intending to use for the input value (the "identifier" parameter) and > the value you're reading from the user. You go: It wasn't really confusion on my part. What I *wanted* to do was to substitute a more specific identifier from the calling code for the generic "identifier" in the get_input() function, and use it both for the actual user input and to fill in that value wherever I need it. But I could not find a way to accomplish this and just left my question at the last error state. But I guess this is not a doable thing. > identifier = int(input(input_prompt)) > > That immediatey destroys the name you passed in as a parameter. Instead, > use a distinct variable for the input value. Let's be imaginitive and > call it "value": Or "user_input", which I finally wound up with. > Then you try to create a date from that value (though you don't save it > anywhere). I presume you want to use the datetime.date() constructor. > So: > > # at the start of your programme > import datetime > > then in the function: > > date = datetime.date(*date_value_err_ck) > > I think your plan is that datetime.date() will also raise a ValueError > for a bad year number in "value". So you want, in fact, to call: That is, in fact, the plan. Since I only want to check for a bad year, then a bad month, and finally, a bad day of the month, I saw no point in binding a name to the date object. In the part of the code I did not include, I create a date object from date(goal_year, goal_month, goal_day) to use in the rest of the program. > Let me introduce you to the lambda. Or, in my case, "reintroduce" me to the lambda. It has been probably at least a couple of years since I had need of this and I had totally forgotten about it! There are those backward steps again! I guess I will have to head for bed now and look mo
[Tutor] How to avoid "UnboundLocalError: local variable 'goal_year' referenced before assignment"?
I have just written a small program earlier today to allow the user (me) to enter a date by which I wish to finish reading a book (= massive programming-related book) and calculate how many pages I need to read each day (starting today) in order to finish the book by the target date. Looking over my code I found that I was repeating a fairly regular pattern in collecting the user input, so I thought I would *improve* my working program by removing the duplicated code into a single function. So I came up with: from datetime import date def get_input(greeting_msg, identifier, input_prompt, date_value_err_ck, err_msg, conditions): """ ??? """ if greeting_msg: print(greeting_msg) while True: try: identifier = int(input(input_prompt)) if date_value_err_ck: date(*date_value_err_ck) except ValueError: print(err_msg) continue for (condition, condition_msg) in conditions: if condition: print(condition_msg) break else: return identifier When I attempt to use this function with: goal_year_params = { 'greeting_msg': "Please enter the date by which you wish to attain" " your goal.\n", 'identifier': 'goal_year', 'input_prompt': "Enter year of your goal as an integer: ", 'date_value_err_ck': (goal_year, 1, 1), 'err_msg': "That is not a valid year. Please try again.", 'conditions': [ ('goal_year < date.today().year', "Have you invented a time machine? If not, please enter a" " year that makes more sense!"), ('goal_year >= date.today().year + 100', "Have you discovered the secret to eternal life? And how" " long is this book anyway? Please enter a year that" " makes more sense.")]} goal_year = get_input(**goal_year_params) I get the following traceback: Traceback (most recent call last): File "pages_per_day.py", line 250, in start_pgm() File "pages_per_day.py", line 246, in start_pgm goal_date_obj, pages_read, total_pages_to_read = get_inputs() File "pages_per_day.py", line 63, in get_inputs 'date_value_err_ck': (goal_year, 1, 1), UnboundLocalError: local variable 'goal_year' referenced before assignment I understand this result, but cannot come up with a way to implement my desired DRY strategy as I am stuck on how to get around this "local variable ... referenced before assignment" issue. On subsequent passes "goal_year" will become "goal_month" and then "goal_day" as the user needs to input all three of these numbers. Is there a way to accomplish my goal or am I attempting to be too clever? -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] After virtualenv, how to use ide
On Sat, Mar 23, 2019 at 12:50 PM anand warik wrote: > > I had installed Python on Ubuntu 14.04 using Anaconda package long back > after failing to install independently for a long time. I was quietly using > it's packaged ide Spyder and had no troubles, in fact I love spider more > then atom. I recently learned how to setup a virtual environment though, > which recommends to never use system wide Python install. But even after > activating the virtual environment, I don't know how can i ask the spyder > ide to use the new Python directory. Can anyone help me change the setting > of Spyder so that it uses different versions? A quick search yields this Stack Overflow thread with what appears to be several useful links embedded: https://stackoverflow.com/questions/30170468/how-to-run-spyder-in-virtual-environment -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Is this the preferred way to change terminal screen color using curses?
On Sat, Mar 2, 2019 at 4:28 PM Cameron Simpson wrote: > Is the painting of the screen with spaces actually required? I would > have thought not (again, untested). The main window (stdscr) should > start filled with spaces. I had read this along the way, but had forgotten it. > [Reads more closely...] probably you want to call bkgd() or wbkgd() > instead. "man curs_bkgd" says: > >bkgd >The bkgd and wbkgd functions set the background property of the >current or specified window and then apply this setting to every >character position in that window: >· The rendition of every character on the screen is changed to >the new background rendition. >· Wherever the former background character appears, it is changed >to the new background character. I had seen this, but I have been giving way too much credence to the names given to these methods. This is the second time I have been badly burned by the names used. I had ASSumed that if there is a bkgdset() method, that the window attributes need to be initialized first if one is not satisfied with the default behavior. And I *did* try using bkgdset() by itself without manually populating spaces, but it did not change the color of anything but the window border I had used in my original trial code. I tried your suggestion with bkgd() and it worked beautifully. BTW, my Linux Mint installation did *not* have the man pages for ncurses, even though it was installed. I had to manually fetch the man pages myself. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Is this the preferred way to change terminal screen color using curses?
I wanted to be able to change the background screen color of a terminal window using curses. My weak Google-Foo did not turn up a clear example of how to do this despite much searching. The two _obvious_curses methods to attempt this seemed to be window.bkgdset(ch, attr) to initially set a window's background attributes and window.bkgd(ch, attr) to change them to new values. The thing that has puzzled me is that "ch" is a mandatory parameter to supply. So after a variety of experimental efforts I came up with the following approach which seems to do what I want to do -- just change the terminal's background color at will. But since I did *not* locate any clear examples online on how to do this, I cannot help but wonder if there is an easier approach to do what I want to do? My code follows. As always I am open to any constructive criticism even if it is off this email's topic, though this code is not meant to be a polished product. #!/usr/bin/env python3 import curses def start_cli(stdscr): max_height, max_width = stdscr.getmaxyx() curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_CYAN) PAIR_BLACK_ON_CYAN = curses.color_pair(1) stdscr.clear() stdscr.bkgdset(' ', PAIR_BLACK_ON_CYAN) # Fill screen with spaces to color screen background: for y in range(max_height): try: stdscr.addstr(y, 0, ' ' * max_width) except curses.error as error: if y == max_height - 1: # Ignore error from writing to lower right-hand screen corner: pass else: raise error # Make cursor invisible to ensure *entire* screen is colored: curses.curs_set(0) stdscr.refresh() # Pause program until user presses key: stdscr.getkey() # Change background screen color: curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_RED) PAIR_BLACK_ON_RED = curses.color_pair(2) change_bkgd_color(stdscr, PAIR_BLACK_ON_RED) stdscr.getkey() def change_bkgd_color(window_obj, color_pair): window_obj.bkgd(' ', color_pair) if __name__ == '__main__': input("Press ENTER to change screen to first color, then press" " any key for next color change until the program exits.") curses.wrapper(start_cli) -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ANSI / VT100 Escape Codes in Windows 7 Environment
On Wed, Feb 27, 2019 at 6:50 PM Chip Wachob wrote: > > Hello again, > > As always, this list has been very helpful, and thank you. > > So, I thought I was good to go until I attempted to run my code on a > Windows 7 vintage machine this morning. The application is intended to be > run in the command window in Windows, from the terminal in Linux... > > In the code I had included the ANSI escape characters so I could invert the > text and change the color. Basically, I wanted to make the warning / error > messages stand out from the crowd. As I have been on a "curses" kick lately, I wonder if it would work for you? Of course this means another module, but it is in the standard lib on all non-Windows Python versions. For Windows I found this thread on stackoverflow: https://stackoverflow.com/questions/32417379/what-is-needed-for-curses-in-python-3-4-on-windows7 The checked answer gives a link to binaries for Windows, which seems to support all Python versions through 3.7, including 2.7. Just a thought... -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Why does using "window.addchr()" to place a character at the lower right corner raise an exception?
On Wed, Feb 27, 2019 at 8:09 PM Alex Kleider wrote: > > On 2019-02-27 17:48, boB Stepp wrote: > > Under https://docs.python.org/3/library/curses.html#window-objects in > > the curses docs, it states: > > > > > > window.addch(ch[, attr]) > > window.addch(y, x, ch[, attr]) > > [...] > > > > Note > > > > Writing outside the window, subwindow, or pad raises a curses.error. > > Attempting to write to the lower right corner of a window, subwindow, > > or pad will cause an exception to be raised after the character is > > printed. > > Could it be that as soon as the character is printed the cursor moves to > the 'next location' which is outside of the 'window, subwindow, or pad' > and it is this which causes the error to be raised? Alex, I think you have nailed it! Everything I have read so far indicates that an exception will be thrown whenever attempting to write outside of a window, subwindow or pad. So it would appear to follow that if for some reason I need to write something to that very last cell I will have to handle the exception generated. Thanks! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Why does using "window.addchr()" to place a character at the lower right corner raise an exception?
Under https://docs.python.org/3/library/curses.html#window-objects in the curses docs, it states: window.addch(ch[, attr]) window.addch(y, x, ch[, attr]) [...] Note Writing outside the window, subwindow, or pad raises a curses.error. Attempting to write to the lower right corner of a window, subwindow, or pad will cause an exception to be raised after the character is printed. Why is this? What is special about the lower right corner of a terminal window? I am guessing this is some relic of the original terminal era. TIA! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to use "curses.resizeterm(nlines, ncols)"
On Sun, Feb 24, 2019 at 4:40 PM Cameron Simpson wrote: > I've modified your script. Please try the script appended below. The > short answer is that resizeterm() is _not_ normally useful to you, the > programmer; it will only be useful if curses does not get to notice > terminal size changes - _then_ you could use it to provide that > facility. > > The script below is like yours: 'q' to quit, other keys to refresh and > retest. Notice that the version below does not update (max_y,max_x) or > call resizeterm(); initially you want to see what is_term_resized() > does. It also shows you what got tested. > #!/usr/bin/env python3 > > import curses > > def start_cli(stdscr): > max_y, max_x = stdscr.getmaxyx() > stdscr.clear() > stdscr.border() > stdscr.addstr(2, 2, "This is the beginning!") > stdscr.refresh() > while True: > char = chr(stdscr.getch()) > if char in 'Qq': > return > tested = "is_term_resized(max_x=%d, max_y=%d)" % (max_x, max_y) > internal = "getmaxyx() => y=%d, x=%d" % stdscr.getmaxyx() > resized = curses.is_term_resized(max_y, max_x) > result = "%s => %s" % (tested, resized) > stdscr.clear() > stdscr.addstr(max_y//2, max_x//2, result) > stdscr.addstr(max_y//2 + 1, max_x//2, internal) > if curses.is_term_resized(max_y, max_x): > ##max_y, max_x = stdscr.getmaxyx() > stdscr.addstr(max_y//2 + 2, max_x//2, "You resized the terminal!") > ##stdscr.addstr(max_y//2 + 2, max_x//2, "Resizing your window -- > NOW!") > ##curses.resizeterm(max_y, max_x) > else: > stdscr.addstr(max_y//2 + 2, max_x//2, "Not resized.") > stdscr.border() > stdscr.refresh() > > if __name__ == '__main__': > curses.wrapper(start_cli) While playing around with the above as I manually resized the terminal window I noticed the program crashing with a curses.ERR exception if I shrank the window so much that the program could not place the text at the programmed coordinates. This makes sense. But, as usual, this has gotten me to wonder that if I ever use curses to write a program that others would be using if it is worthwhile to at least warn the users against overly shrinking their terminal window or somehow trying to handle the resulting exception? Or does such a user "deserve" what he/she gets? ~(:>)) -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to use "curses.resizeterm(nlines, ncols)"
On Sun, Feb 24, 2019 at 2:52 PM Mats Wichmann wrote: > > On 2/24/19 1:30 PM, boB Stepp wrote: > > > So what am I misunderstanding? Can someone show me a code snippet > > that I can run which will demonstrate the usefulness and usage of > > curses.resizeterm()? > > > > TIA! > > > > If it's snippets you want, I always look at programcreek. These are > always part of something bigger so they may not fit your request to have > them be something you can run. > > https://www.programcreek.com/python/example/57429/curses.is_term_resized Thanks for the link! It looks useful for future research! However, in the context of the current discussion, especially after Cameron's revelations, I cannot help but wonder if the writers of the three code snippets did not truly understand resizeterm()? Especially the first example is very similar to my testing script. But I did not go to the full-fledge programs to see if there was something unusual going on, so I may be overly harsh is my first impression. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to use "curses.resizeterm(nlines, ncols)"
On Sun, Feb 24, 2019 at 4:40 PM Cameron Simpson wrote: > > On 24Feb2019 14:30, boB Stepp wrote: > >What you say makes sense and supports much of what I had concluded > >from my coding experiments. However, I still cannot get the function > >call, curses.resizeterm(), to do anything meaningful, which suggests > >that I still do not truly understand its usage. > > Likely so. The important thing you may be missing is that curses > _itself_ calls resizeterm() automatically when it gets a SIGWINCH, so in > normal situations you do not need to call this function. AHA! It is exactly that. How am I to know this from reading the existing Python 3 docs??? I spent *much* time trying different coding efforts to get resizeterm() to do something, ANYTHING, when all along this was happening automatically behind the scenes. > Because of this, getmaxyx() is always correct for the size of the > terminal. > > Secondarily, resizeterm() does not make a change to the terminal itself. I realized this before I sent my original post. I really think the name chosen, resizeterm, is a very misleading name! > >I created the > >following script to test things out: > [...] > > I've modified your script. Please try the script appended below. The > short answer is that resizeterm() is _not_ normally useful to you, the > programmer; it will only be useful if curses does not get to notice > terminal size changes - _then_ you could use it to provide that > facility. Thanks for the additional clarity provided with your modifications! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to use "curses.resizeterm(nlines, ncols)"
On Sun, Feb 24, 2019 at 1:39 AM Cameron Simpson wrote: > It looks like the resizeterm() function updates the curses _internal_ > records of what it believes the physcial terminal size to be. When you > physically resize a terminal the processes within it receive a SIGWINCH > signal, and those which pay attention to that signal should then consult > the terminal to find out its new size. > > The curses library notices this signal, and calls resizeterm() to update > its own internal idea of the terminal size so that it knows how to draw > correctly on the screen. It does _not_ change the terminal; it changes > curses' beliefs _about_ the terminal. > > If you call resizeterm() yourself you will cause curses to act from then > on as though the physcial terminal has the size you supplied. That may > make for bad rendering if that size does not match reality (consider > cursor motions "from the right edge" or "from the bottom edge" - their > sizes are computed from where curses thinks those edges are). > > Test the function curses.is_term_resized(nlines,ncols), whose doco says: > > Return True if resize_term() would modify the window structure, False > otherwise. > > The is_term_resized() function looks up the current physical size and > reports False if that matches curses current beliefs, and True if it > does not match, meaning that the physical size has changed since curses > last set up its beliefs (for example, in some environment where the > resize _doesn't_ propagate a SIGWINCH to the process using curses, so it > hasn't noticed). > > Does this clarify things for you? What you say makes sense and supports much of what I had concluded from my coding experiments. However, I still cannot get the function call, curses.resizeterm(), to do anything meaningful, which suggests that I still do not truly understand its usage. I created the following script to test things out: #!/usr/bin/env python3 import curses def start_cli(stdscr): max_y, max_x = stdscr.getmaxyx() stdscr.clear() stdscr.border() stdscr.addstr(2, 2, "This is the beginning!") stdscr.refresh() while True: char = chr(stdscr.getch()) if char in 'Qq': return if curses.is_term_resized(max_y, max_x): max_y, max_x = stdscr.getmaxyx() stdscr.clear() stdscr.addstr(max_y//2, max_x//2, "You resized the terminal!") stdscr.addstr(max_y//2 + 1, max_x//2, "Resizing your window -- NOW!") #curses.resizeterm(max_y, max_x) stdscr.border() stdscr.refresh() if __name__ == '__main__': curses.wrapper(start_cli) Notice that I have "curses.resizeterm( ..." commented out. Whether I comment it out or leave it in, the behavior I observe while manually resizing my terminal window is the same. The stdscr.border() still tracks around the limits of the full terminal screen size. I had also tried not adding stdscr.border() in the if block, thinking that maybe curses.resizeterm() would redraw the border once I refreshed the screen, but that did not happen. So what am I misunderstanding? Can someone show me a code snippet that I can run which will demonstrate the usefulness and usage of curses.resizeterm()? TIA! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] How to use "curses.resizeterm(nlines, ncols)"
I am trying to understand the functionality that the Python module, curses, provides. But I am stuck on how to use the command, curses.resizeterm(nlines, ncols). At https://docs.python.org/3/library/curses.html#curses.resizeterm it says: curses.resizeterm(nlines, ncols)¶ Resize the standard and current windows to the specified dimensions, and adjusts other bookkeeping data used by the curses library that record the window dimensions (in particular the SIGWINCH handler). After much experimentation -- to no good effect -- I have concluded that "resizeterm" does *not* mean resize the terminal window that the curses program is running within. Can someone give me a working example of how to use this command? TIA! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Good tutorials about Python 2 and 3 OOP by Leonardo Giordani
I have stumbled upon some articles by Leonardo Giordani that deal with OOP in Python. He has two sets of articles. The one concerning Python 2 is located at: http://blog.thedigitalcatonline.com/blog/2014/03/05/oop-concepts-in-python-2-dot-x-part-1/ The one concerning Python 3 is at: http://blog.thedigitalcatonline.com/blog/2014/08/20/python-3-oop-part-1-objects-and-types/ The links for the next in each series is at the end of each article. I have read most of the Python 2 first article and find it very well written. I hope these will be useful to others. Also, it looks like he has quite a few other articles that look equally interesting! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Fwd: [Tkinter-discuss] New docs: using tkinter GUIs on Android
I thought that this might be of interest to the group for those who do not follow the Tkinter mailing list as I have seen questions here about how to do Python GUIs in Android where the usual response is to try Kivy. Perhaps there is now a tkinter solution? -- Forwarded message - From: Mark Lutz Date: Sun, Feb 10, 2019 at 10:07 AM Subject: [Tkinter-discuss] New docs: using tkinter GUIs on Android To: , I've just posted guides for running Python tkinter programs on Android in the Pydroid 3 app's IDE. The first covers multiple programs, and the second focuses on a content-sync program: https://learning-python.com/using-tkinter-programs-on-android.html https://learning-python.com/mergeall-android-scripts/_README.html And yes, you read that right: Python tkinter GUIs, including the calendar, calculator, text editor, and incremental backup tool described in these docs, now work on your smartphone in addition to your PC, though they come with a few rough edges (and advertising) on Android today. And there was much rejoicing, --M. Lutz (http://learning-python.com) ___ Tkinter-discuss mailing list tkinter-disc...@python.org https://mail.python.org/mailman/listinfo/tkinter-discuss -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Putting a Bow on It
On Fri, Feb 8, 2019 at 12:35 PM Chip Wachob wrote: > > Hello, > > I've been off working on other projects, but I'm finally back to the > project that so many here have helped me work through. Thank you to the > group at large. > > So, this leads me to my question for today. > > I'm not sure what the "correct" term is for this, but I want to create what > I'll call a Package. I have not looked into this topic, but your term is very close to the mark as I understand it. > I want to bundle all my scripts, extra libraries, etc into one file. If I > can include a copy of Python with it that would be even better. > > I'm looking for the simplest approach for the user to install. Eg: > libraries will install themselves in the correct directories, etc, so that > there is minimal pain on the part of the user. Searching for "python packaging tutorials" a sampling of what I get is: 1) Packaging Python Projects: https://packaging.python.org/tutorials/packaging-projects/ 2) A Simple Guide for Python Packaging: https://medium.com/small-things-about-python/lets-talk-about-python-packaging-6d84b81f1bb5 Etc. There are also ways to create frozen binaries. I just bought a book today that I have been flipping through tonight, "Serious Python" by Julien Danjou. His chapter 5 is entitled "Distributing Your Software". He discusses the history of Python packaging and says that setuptools is "... the standard for advanced package installations, was at first deprecated but is now back in active development and the de facto standard." This book has just been released this year and is written around Python 3.7 being the latest version, so hopefully his comment is accurate for 2019. > I would need to do this for both Windows and Linux so something that is > platform agnostic would be great. In the book's chapter I mentioned, the author gives a warning about portability (from page 63): "If the Wheel you build contains binary programs or libraries (like a Python extension written in C), the binary Wheel might not be as portable as you imagine. It will work by default on some platforms, such as Darwin (macOS) or Microsoft Windows, but it might not work on all Linux distributions. The PEP 513 (https://www.python.org/dev/peps/pep-0513) targets this Linux problem by defining a new platform tag named manylinux1 and a minimal set of libraries that are guaranteed to be available on that platform." So apparently there is not yet a platform agnostic panacea for program installations with all of their possible dependencies. Sorry I know so little about this, but perhaps this might get you pointed in a helpful direction. Hopefully the professionals will weigh in on your questions soon. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] OT: A bit of humor related to my sporadic quest to learn Python
My son sent me this link, which I think captures my situation with Python quite nicely: https://cdn-images-1.medium.com/max/720/1*7RZKI-g4K_syDf6XQEGWKw.jpeg -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Defining variable arguments in a function in python
On Mon, Dec 31, 2018 at 10:36 AM David Rock wrote: > > > On Dec 30, 2018, at 18:39, Alan Gauld via Tutor wrote: > > > > On 30/12/2018 22:25, Avi Gross wrote: > > > >> I admit I have not studied the charter for the group. > > > > As moderator I feel the need to step in here because the > > charter is extremely apropos to that function and some > > clarification may be helpful. > > I would like to add an observation… > > The core complaint appears to be the length of the postings. To my eye, > Avi’s style of posting is extremely verbose, which is not necessarily a bad > thing; but perhaps taking some time to distill the thoughts to make a > concise, on topic, point would be helpful in this case. When discussions > appear to ramble at length in odd tangents, the helpfulness to the beginner > is diluted and the original point of the discussion is lost. While I guess I am not considered here a rank beginner anymore, I still know I have a LOT to learn. In general I *try* to read all posts on both the Tutor list and the main Python list. However, I must echo David's point -- I find Avi's posts way too long and rambling, and while I am sure there are many useful nuggets to explore, I find myself more and more often just doing a quick scan for anything that just *pops out* that interests me, and, if not, hit delete. To Avi: I know I would enjoy your posts much more if you would: (1) Get to the point quickly and stay on topic while addressing that point. Or, (2) When you have a variety of disparate topics you would like to discuss, break your one long post into a series of separate emails, each with an appropriate subject line, and stick to each post's topic implied by the subject line you choose. I know I am often quite guilty on rambling on, so I know how hard it is to do this. I say all of this, Avi, not to be critical, but to hopefully enhance everyone's opportunity to process and learn from your thoughts. In any event, I hope all you Pythonistas have both a HAPPY AND BLESSED NEW YEAR!!! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] loop error
Greetings Aine! On Thu, Dec 20, 2018 at 6:57 PM Aine Gormley wrote: > > Hello, could somebody take a quick look at my code? I am unsure why I am > getting a loop error? This is a plain text only list that does not (typically) allow file attachments. So I do not see any code. So if you wish for someone on this list to assist you, you need to copy and paste the relevant code into a plain text email, including a copy and paste of the error messages you are receiving. It is also helpful to mention your operating system and what version of Python you are using. An even better approach would be to construct the smallest possible runnable example code that reproduces your problem. Good luck and better thinking! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (no subject)
Greetings! On Sat, Oct 27, 2018 at 6:48 AM Jesse Stockman wrote: > > Hi there > > I need to draw a patten with turtle in python 3.7 but I cant get it to work > ... What is the problem? Describe what you expected to happen, what did happen, and *copy and paste* the Traceback that Python generates. I had a bit of time, so I ran your code as you had it in your email, and I got the following: Traceback (most recent call last): File "draw_body.py", line 69, in main() File "draw_body.py", line 26, in main draw_podium(winner_color, second_color, third_color) NameError: name 'draw_podium' is not defined If you look at your code, your main() function calls this draw_podium() function, but you never give us that function in your email. Likewise, darw_third() [Note the spelling error here.], draw_winner(), and draw_second() are not defined anywhere in the code you provided. Looks like your next step is to write those functions. BTW "hight" should be "height", but as long as you are consistent, that spelling error should not cause any issues. One thing you can do to check for further issues with the code you *have* written so far, is to provide the missing functions with "pass" in each function's body, and then run your program and see if any other errors emerge. E.g., draw_podium(winner_color, second_color, third_color): pass draw_third(third_color): pass Etc. Hope this helps! > ...here are the specs of the pattern and my code so far can you please help > > • Specifications of the pattern o The radius of the three heads is 10. > o The length of legs is 30. o The length of the sizes of the two triangles > (the body of runner-up and third-place) is 40. They are all equal-size > triangles. The winner’s body is a 40x40 square. o The width of the three > blocks of the podium is 60. The heights are 90, 60, and 40 respectively. > > And my code so far > > from turtle import * > > x = 0 > y = 0 > radius = 0 > x1 = 0 > x2 = 0 > y1 = 0 > y2 = 0 > color = 0 > width = 0 > hight =0 > > > > def main(): > speed(0) > pensize(3) > pencolor("black") > > winner_color = "red" > second_color = "orange" > third_color = "purple" > draw_podium(winner_color, second_color, third_color) > darw_third(third_color) > draw_winner(winner_color) > draw_second(second_color) > > def move_to(x, y): > x = int(input("input X coordinate: ")) > y = int(input("input y coordinate: ")) > penup() > goto(x, y) > pendown() > > def draw_head(x, y, radius): > radius = int(input("input radius: ")) > move_to(x, y) > circle(radius) > > def draw_line(x1, y1, x2, y2): > x1 = int(input("line start X: ")) > y1 = int(input("line start Y: ")) > x2 = int(input("line end X: ")) > y2 = int(input("line end Y: ")) > penup() > goto(x1,y1) > pendown() > goto(x2,y2) > > def draw_block(x, y, hight, width, color): > move_to(x, y) > hight = int(input("input hight: ")) > width = int(input("input width: ")) > color(winner_color) > begin_fill() > forward(width) > left(90) > forward(hight) > left(90) > forward(width) > left(90) > forward(hight) > end_fill() > > > main() > draw_block(x, y, hight, width, color) > > > exitonclick() -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fwd: Can tempfile.NamedTemporaryFile(delete=False) be used to create *permanent* uniquely named files?
On Mon, Oct 22, 2018 at 11:57 AM Mats Wichmann wrote: > > On 10/22/18 8:24 AM, boB Stepp wrote: > > Forwarding to the Tutor list. Herr Maier offers a good idea that > > would take away much of a remaining issue -- the name "Temporary". I > > need to look into the functools library to see what "partial" does. > > > if you really don't care what the file is called because you will > maintain a map which leads you to the filename, you might as well use a > uuid. Wouldn't I have to write a check to ensure such a named file (However unlikely that would be.) did not exist before creating it? And if yes, would not that get into the same potential security issue that cause tempfile.mktemp() to be deprecated? -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What is the best way for a program suite to know where it is installed?
On Mon, Oct 22, 2018 at 9:47 AM Mats Wichmann wrote: > > On 10/20/18 9:00 PM, boB Stepp wrote: > > So far the best method I've come up with is to make use of "__file__" > > for the initiating program file. But from past discussions I am not > > certain this is the *best* way. Is the *best* way going to get me > > into best techniques for installing and distributing programs? If so, > > this strikes me as a huge mess to dive into! > > > > TIA! > > > > As you've concluded by now, this isn't a completely trivial exercise, > and you'll possibly get asked the question "why do you think you need to > know that?". Actually no one has yet asked me this question, and you have me intrigued. Importing the various program modules/module contents is no issue. Where I believe I need to know the paths to things are to get to data folders, config files, and occasionally utility programs that I have written that are on my hard drive, but not copied to my current program suite. Unless there is some built-into-Python-easy way to find such things, I do not see any other alternative than determining the path to the desired files. Is there a better way? > Probably though this is considered one of the more reliable ways: > > import os > > if __name__ == '__main__': > script_path = os.path.dirname(os.path.realpath(__file__)) > print("Main module at", script_path) Despite the past thread I mentioned in this thread's originating post, I have switched to using pathlib.Path for doing this sort of thing. Something I read on the main list in the past year I found convincing, though I now don't remember now why I was so convinced. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Fwd: Can tempfile.NamedTemporaryFile(delete=False) be used to create *permanent* uniquely named files?
Forwarding to the Tutor list. Herr Maier offers a good idea that would take away much of a remaining issue -- the name "Temporary". I need to look into the functools library to see what "partial" does. -- Forwarded message - From: Wolfgang Maier Date: Mon, Oct 22, 2018 at 5:25 AM Subject: Re: Can tempfile.NamedTemporaryFile(delete=False) be used to create *permanent* uniquely named files? To: boB Stepp On 21.10.18 08:13, boB Stepp wrote: > Use case: I want to allow a user of my Solitaire Scorekeeper program > to be able to give any name he wants to each game of solitaire he > wishes to record. My thought for permanent storage of each game's > parameters is to use a dictionary to map the user-chosen game names to > a unique json filename. This way I hope no shenanigans can occur with > weird characters/non-printing characters. > > My initial thought was to just have a sequence of game names with > incrementing numerical suffixes: game_0, game_1, ... , game_n. But > this would require the program to keep track of what the next > available numerical suffix is. Additionally, if a user chooses to > delete a game, then there would be a gap in the numerical sequence of > the game filenames. I find such a gap aesthetically displeasing and > would probably go to additional efforts to reuse such deleted > filenames, so there would be no such "gaps". > > So I am now wondering if using > tempfile.NamedTemporaryFile(delete=False) would solve this problem > nicely? As I am not very familiar with this library, are there any > unforeseen issues I should be made aware of? Would this work equally > well on all operating systems? > > TIA! > This sounds like a good though surprising use case. The only odd thing about this is the misleading name then of the function, plus there is the (vague) possibility that the stdlib module might evolve and no longer support this undocumented (given that the first sentence in the module description reads: "This module creates temporary files and directories.") use case. I would probably address these issues and the handling of the dir parameter via a partial function like this: from functools import partial SavedGameFile = partial( tempfile.NamedTemporaryFile, dir=my_saved_games_dir ) # if you like also set the suffix here SavedGameFile.__doc__ = """\ Create and return a saved game file, ... """ This way you have a good name for the function, and you can redefine the function, if you ever want/need to move away from NamedTemporaryFile, without having to rewrite every function call. Wolfgang -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can tempfile.NamedTemporaryFile(delete=False) be used to create *permanent* uniquely named files?
On Sun, Oct 21, 2018 at 1:47 AM Quentin Agren wrote: > > Hi Robert, > > Far from being an expert, my two cents on this: > > - As I understand it, you should at least use the 'dir' parameter to > NamedTemporaryFile, otherwise your files will be created in a '/tmp/'-like > directory that may be wiped clean by the OS now and then. I am planning to set both the "dir" and "suffix" parameters if I go this route and probably the "mode" parameter, too. > - I seems that the only functionality you desire from tempfile is the > generation of a random file name (and maybe ensuring that no collision > occurs). You could use the 'random' standard library module to generate such > names easily (which is about what tempfile does under the hood) It is important for me to have no name collisions however unlikely such an event might be. > import random > CHARS = 'abcdefghijklmnopqrstuvw1234567890' > def random_name(length): > return ''.join([random.choice(CHARS) for _ in range(length)]) It occurred to me to do this type of approach. But why write this myself when a standard library module may give me what I want with only one or two lines of code? When I searched online others have recommended using the uuid library to generate names. But one still has to check that it does not already exist (However unlikely.) and format the final filename. And I would have to do the same for the code snippet you supplied, adding a few additional lines of code. But thank you for your input! It may turn out that there is something undesirable that I am unaware of in the NamedTemporaryFile approach, other than what I really want is a NamedPermanentFile approach, but the standard library naming suggest otherwise! ~(:>)) boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Can tempfile.NamedTemporaryFile(delete=False) be used to create *permanent* uniquely named files?
Use case: I want to allow a user of my Solitaire Scorekeeper program to be able to give any name he wants to each game of solitaire he wishes to record. My thought for permanent storage of each game's parameters is to use a dictionary to map the user-chosen game names to a unique json filename. This way I hope no shenanigans can occur with weird characters/non-printing characters. My initial thought was to just have a sequence of game names with incrementing numerical suffixes: game_0, game_1, ... , game_n. But this would require the program to keep track of what the next available numerical suffix is. Additionally, if a user chooses to delete a game, then there would be a gap in the numerical sequence of the game filenames. I find such a gap aesthetically displeasing and would probably go to additional efforts to reuse such deleted filenames, so there would be no such "gaps". So I am now wondering if using tempfile.NamedTemporaryFile(delete=False) would solve this problem nicely? As I am not very familiar with this library, are there any unforeseen issues I should be made aware of? Would this work equally well on all operating systems? TIA! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] When are "__init__.py" files needed and not needed in a project?
On Sat, Oct 20, 2018 at 11:21 PM Alex Kleider wrote: > > On 2018-10-20 14:52, boB Stepp wrote: > > > >> > In case it helps, my current project structure is: > >> > > >> > ~/Projects/solitaire_scorekeeper/# I left off the actual project > >> > folder in my original email > >> > data/ > >> > docs/ > >> > tests/ > >> > .git/ > >> > main.py > >> > .gitignore > > > I'm curious to know where under the above structure you keep your code > files? (...or is all your code within main.py?) For this project, I am hoping that in the end there will not be a lot of code, so I am currently putting all code in main.py. If this gets too unwieldy I will move all refactored source code files into a new "src" subdirectory. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] What is the best way for a program suite to know where it is installed?
I was just re-reading the entire thread at https://www.mail-archive.com/tutor@python.org/msg77864.html And I have asked similar questions previous to that thread. I still do not have a satisfactory answer for the subject line's question that both makes sense to me and seems to be good programming practice. And that works for any OS that the program suite is installed under. A constantly recurring situation I am having is a programming project with a nested directory structure. Usually I will have "tests" and "data" folders nested under the top level project folder. There may be others as well depending on the complexity of the project I am attempting. As far as I can tell, I cannot make any assumptions about what the current working directory is when a user starts the program. So how can one of my programs *know* what the absolute path is to, say, the top level of the program suite? If I could always reliably determine this by my program's code, every other location could be determined from the known nested structure of the program suite. [But I have a dim recollection that either Ben or Cameron thought relying on the "known nested structure" is brittle at best.] So far the best method I've come up with is to make use of "__file__" for the initiating program file. But from past discussions I am not certain this is the *best* way. Is the *best* way going to get me into best techniques for installing and distributing programs? If so, this strikes me as a huge mess to dive into! TIA! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] When are "__init__.py" files needed and not needed in a project?
On Sat, Oct 20, 2018 at 1:36 PM Peter Otten <__pete...@web.de> wrote: > > boB Stepp wrote: > > > Linux Mint 19 Cinnamon, Python 3.6.6 [snip] > > I was expecting this error and will shortly correct it. So my > > question remains, when are "__init__.py" files needed and when are > > they not? > > I am struggling with the differences between the two types of packages > myself, so my first guess was that you accidentally found out that test > discovery doesn't work for namespace packages. However > > https://docs.python.org/dev/library/unittest.html#test-discovery > > expicitly states > > """ > Changed in version 3.4: Test discovery supports namespace packages. > """ > > Perhaps you should file a bug report. I just waded through PEP 420 describing "implicit namespace packages". I think I have a cursory understanding now, but not enough to feel confidant to file a bug report. It *seems* that with my project structure below (Note the slight correction.) if I initiate test discovery in the top level directory (The one holding main.py.) and have no __init__.py files anywhere, that my initial effort should have run the one test with the resulting error instead of running 0 tests. Can anything reading this duplicate my issue? If yes, then I will endeavour to file a bug report. But otherwise, I would suspect something screwy that I have done and am currently unaware of what it may be. > > In case it helps, my current project structure is: > > > > ~/Projects > > data/ > > docs/ > > tests/ > > .git/ > > main.py > > .gitignore Just noticed that I mistyped the top level of my project structure. It should be: ~/Projects/solitaire_scorekeeper/ etc. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] When are "__init__.py" files needed and not needed in a project?
Linux Mint 19 Cinnamon, Python 3.6.6 I would have sworn that I had read, either on this list or the main Python list, that in the most recent versions of Python 3 that "__init__.py" files were no longer needed in nested project file structures. But when I attempted to run tests for the first time on my new Solitaire Scorekeeper project (Finally getting around to this!), I got: bob@Dream-Machine1:~/Projects/solitaire_scorekeeper$ python3 -m unittest -- Ran 0 tests in 0.000s OK So no tests were run. So it immediately occurred to me to add an empty "__init__.py" file to my "tests" subfolder and got what I was currently expecting: bob@Dream-Machine1:~/Projects/solitaire_scorekeeper$ python3 -m unittest E == ERROR: test_get_gamenames_bad_path (tests.tests_main.TestGameNamesMapperMethods) Test that when the method, get_gamenames(), is passed a path to a -- Traceback (most recent call last): File "/home/bob/Projects/solitaire_scorekeeper/tests/tests_main.py", line 20, in test_get_gamenames_bad_path self.assertEqual(gamenames.gamenames(), {}) NameError: name 'self' is not defined -- Ran 1 test in 0.000s FAILED (errors=1) I was expecting this error and will shortly correct it. So my question remains, when are "__init__.py" files needed and when are they not? In case it helps, my current project structure is: ~/Projects data/ docs/ tests/ .git/ main.py .gitignore TIA! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Advanced python recommendations
On Wed, Oct 10, 2018 at 12:09 PM Mats Wichmann wrote: > This is actually the concept of test driven development (TDD), which I'm > not a huge proponent of personally, but kind of useful for this: I'm curious: What are the things you find less than satisfactory for TDD? -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Advanced python recommendations
On Tue, Oct 9, 2018 at 6:54 PM Mariam Haji wrote: > > Hi guys, I am on the last exercises of learn python the hard by Zed.A Shaw > and I am looking for recommendations on what to follow next or what book to > try next to advance my python skills to intermediate level. If you are a fan of Zed Shaw's approach, I noticed while at Barnes & Noble a while back that he has released a sequel to the book you cited, but only for the Python 3 version. You may be interested in that. But I imagine taking time to imagine, detail and write the code for projects would help you the most, as the others have said. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] OT: How to automate the setting of file permissions for all files in a collection of programs?
At work I have accumulated a motley collection of programs I have written since I started around 2012. These all run on the Solaris OS. As long-time readers of my past ramblings may recall, I am not allowed to install any outside programs on this Solaris system, but I am allowed to write my own programs to my heart's content, using only whatever programming-related tools that happen to be installed on a rather bare-bones OS install. We have just recently completed upgrades on hardware, Solaris and treatment planning software. On the good news side we went from the vi editor to Vim/gVim; from Python 2.4 to 2.7; in addition to Tkinter there is now a Python interface to GTK; went from no SQLite to having it; and a few other goodies that currently slip my mind. But on the bad side the only version control system installed, SCCS (RIP!) went bye-bye with _nothing_ to replace it. And as usual the radiation therapy planning software we use was upgraded from version 9.10 to 16.2, breaking several of my programs, requiring updates on my part that I recently completed. So as to not lose the benefits of a version control system, I have installed Git on my windows PC. My current workflow now has gotten more complex, and I'm sure can be improved by those thinking more clearly than I (And surely more knowledgeable!), and is as follows: 1) Using CuteFTP copy all of my original working code (Now with problems due to the planning software upgrade.) to my windows PC. 2) Put this code under Git version control. 3) Create a development branch. 4) FTP this back to Solaris for code repair, testing, etc. BUT! This process has changed all of the Unix file permissions on what are (For me.) many files, some planning system proprietary scripting files, some Perl files, some shell script files and some Python files. So before I can do anything further I must go through all of these files and change their permissions to the values I need them to be. This is quite tedious and error prone. So I wish to either fix the process, or, failing that, automate the process of correcting the file permissions. If there is a way in this CuteFTP software to maintain file permissions in this back-and-forth transferring between a Windows and Solaris environment, I have yet to find it in the software's help (Though I have not yet had much time to invest in this search, so I may not have found it yet.). It occurs to me that in theory it should be possible to automate this either with a shell script or a Python program. Is there a standard way of handling this sort of thing? Bear in mind that if a typical solution would require the installation of a software package in the Solaris environment, I am not allowed to do so. I am not allowed to use Python pip either. Strange rules ... -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Contour Plots
Welcome Tara! On Tue, Aug 28, 2018 at 6:46 PM Tara 38 wrote: > > Hi, > > > I wonder if someone can give me some advice? I need to build a contour plot > (ideally with Seaborn) in python. The plot would document text data. I cannot > work out how I need to convert the data file (currently csv file) so that I > have 3 variables that I can then plot as a contour map and visualize in > Seaborn. > > > Really stuck as to where to even start. You really did not give many details or your Python background and knowledge, so it is difficult to know exactly what you need help with. But from your description as is, it sounds like your immediate problem is extracting data from your csv file. Python 2 and 3 have a csv module to facilitate handling this type of file. The Python 3 docs for it are at https://docs.python.org/3/library/csv.html A Python csv tutorial (after Googling) can be found at https://www.blog.pythonlibrary.org/2014/02/26/python-101-reading-and-writing-csv-files/ There are many others you can find via a search if you don't like that one. If your problems lie with generating Seaborn plots another search found their official tutorial at https://seaborn.pydata.org/tutorial.html If the above does not sufficiently help then you will have to provide additional information as to what exactly you are trying to do, how are you trying to do it, where are you getting stuck, etc. HTH! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to have unique identifiers for multiple object instances of a given class?
On Mon, Aug 27, 2018 at 3:44 AM Alan Gauld via Tutor wrote: > > On 27/08/18 04:58, boB Stepp wrote: > >> Maybe JSON for that? Or even a shelve database? > > > > I plan to keep this simple. I will use a ".cfg" file to store game > > configuration information and a ".csv" file to store the actual > > records of hands played. But I will have to be careful how I generate > > the base filenames to avoid duplicates and potential nasty > > user-generated names. Though this project is only meant for my use > > > If you go with a single JSON file or shelve you have > no worries about name clashes. JSON is specifically > designed to store multiple complex object records. > And it retains the readability of CSV (unlike shelve). Wouldn't a single JSON file be wasteful? If I used this program for a couple of years or so and habitually played a lot of solitaire, that would be a lot of stuff to load into RAM when on any given solitaire session I might only play one to three kinds of solitaire. But perhaps I am misunderstanding JSON's capabilities as I only have a cursory knowledge of it from considering it for other projects. OTOH, even if I loaded into RAM all games I might have ever played I doubt I would stress out my RAM capacity, so perhaps this is a non-issue for this type of program on any modern computer. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to have unique identifiers for multiple object instances of a given class?
On Sun, Aug 26, 2018 at 6:10 PM Alan Gauld via Tutor wrote: > > On 26/08/18 23:38, boB Stepp wrote: > > > class SolitaireGame(): > > def __init__(self, name): > > self.name = name > > > Say I go with the aforementioned game with 13 separate scores to keep > > track of. The names of these games might be "Two_Mastery", > > "Three_Mastery", ... , "Ace_Mastery". In principle I want 13 objects > > with each one keeping track of each of the above games. Then I might > > want to switch to "Spider_Solitaire", keep track of its score, then go > > to something else, then back to Mastery, etc. How on earth am I to > > generate unique identifiers for each of these SolitaireGame objects in > > a rational way, not knowing in advance moment to moment what type of > > solitaire game I might be playing? > > A dictionary of objects keyed by name? So you are saying do something like: class SolitaireGame(): def __init__(self, name): self.name = name def describe_self(self): print("This game of solitaire is called", self.name, ".") game_objects = {} def make_new_game_object(name): global game_objects game_objects[name[ = SolitaireGame(name) make_new_game_object('Chinese Solitaire') make_new_game_object('Ace Mastery') make_new_game_object('King Mastery') make_new_game_object('Spider') If I run the above in the interactive interpreter: 3.6.6: game_objects {'Chinese Solitaire': <__main__.SolitaireGame object at 0x7f3991d5e400>, 'Ace Mastery': <__main__.SolitaireGame object at 0x7f3991d5e470>, 'King Mastery': <__main__.SolitaireGame object at 0x7f3991d5e438>, 'Spider': <__main__.SolitaireGame object at 0x7f3991d5e4e0>} 3.6.6: game_objects['Spider'].describe_self() This game of solitaire is called Spider. This would seem to work, though I would have to be very careful to not allow the user to create a new game with the same name (Now a key.) which would overwrite an already existing game object. > If using a GUI add the names to a drop down or listbox > to ease later selection. Ultimately I would add a GUI interface. > Does that work for you? If what I wrote above describes what you intend, then yes. > > between them at will. Of course the intent is to persistently store > > these objects on disk upon program closure. > > Maybe JSON for that? Or even a shelve database? I plan to keep this simple. I will use a ".cfg" file to store game configuration information and a ".csv" file to store the actual records of hands played. But I will have to be careful how I generate the base filenames to avoid duplicates and potential nasty user-generated names. Though this project is only meant for my use ... -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to have unique identifiers for multiple object instances of a given class?
On Sun, Aug 26, 2018 at 7:48 PM Steven D'Aprano wrote: > > On Sun, Aug 26, 2018 at 05:38:52PM -0500, boB Stepp wrote: > > > I feel that I may be missing something truly obvious. I am pondering > > the design of a solitaire scorekeeper program. It is just meant to be > > an electronic scorekeeper for hands of solitaire that I plan with a > > "real" deck of cards, instead of a computer game. I might want to > > play and track a variety of solitaire games. And I might want to play > > one game for a bit and then switch to another. > > > What you say is a little ambiguous. When you say solitaire, do you mean > the specific card game known as "Solitaire", or do you mean the generic > term for dozens of different solitaire-type single person card games? > > When you describe changing games, do you mean changing from (say) > "Grandfather's Clock" to "Spider" to "Solitaire", or do you mean > start a new game by reshuffling the cards and dealing out a new hand? There are probably hundreds if not thousands of games that generically fit under the description solitaire. I am only interested in ones that I might play that will have a score result for each hand played with all such scores added together to form a cumulative score for a particular game. > It might help if you explain how you currently track these games, on > paper. The example that I partially gave in my original posting was a game I was told was called "Mastery" when I was a child. In it you count out a pile of 13 cards that is placed to the player's left, face up. Then to the right of this "pile" are placed 4 cards in a row, which is the area where you can play red on black, black on red in descending sequence. Finally you place a single card face up above all of this. In many games, this is where aces are placed and you eventually build up stacks of each suit until you, if fortunate, exhaust the entire deck in this area, where you would have four suit stacks going "A, 2, 3, ... , J, Q, K" in that order. In Mastery, the starting card can be any of the 13 cards. Say it was a 5. Then you would try to get all of the cards into segregated suit stacks where the bottom-most card was the 5 of each suit. So the sequence in a perfectly played game would be "5, 6, 7, ... , J, Q, K, A, 2, 3, 4" In the end any cards in the left-most pile count 2 points against you, while every card in the top-most up to 4 stacks count 1 point for you. So the worst score possible on a hand would be "-26", while the best score possible would be "+52". I hope that this example is clearer than mud! The adult who taught me this particular game when I was a kid kept a spiral bound notebook which he divided into 13 sections, one for each rank of card (A, 2, 3, ... , J, Q, K). Any one of these ranks might start the top-most piles of a particular hand. So for each hand played he would write down the new cumulative score for that section of his notebook. But there are other types of solitaire that I play that might be scored differently. I want my program to work with any such game where a given played hand can have a worst score, a best score, or any integer in between, where the cumulative score over all hands played of that particular game type would reflect the current state of the game. The way the scorekeeper program would work as I currently envisage it would be the player opens an existing game from disk, starts a new game or switches to a game already open. If it is a new game the player will be asked for the minimum possible score per hand, the maximum possible score per hand, and a name for that particular solitaire game he/she wishes to keep track of the cumulative scores for. As for the persistent storage I will have two files per game, a ".cfg" file storing the min and max possible scores (Later if I add features there might be more things in this file.) and a ".csv" file which will retain in played order the date played, time played, and score for the hand played. I figure cumulative scores can be calculated on the fly from this information. Later on if I like what I've done I might add the ability to do various statistical analyses of the hands played, such as average score per hand, number of instances of a particular score or scores, etc. But right now I'm stuck on how to identify each active object with a valid Python identifier. Alan's suggestion of a dictionary of objects sounds like a possibility, but I have no idea if that is the "best " way to do what I am trying to do. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] How to have unique identifiers for multiple object instances of a given class?
Python 3.6.6, Linux Mint I feel that I may be missing something truly obvious. I am pondering the design of a solitaire scorekeeper program. It is just meant to be an electronic scorekeeper for hands of solitaire that I plan with a "real" deck of cards, instead of a computer game. I might want to play and track a variety of solitaire games. And I might want to play one game for a bit and then switch to another. One version of solitaire I might play has thirteen possible separately scored versions, depending on which of thirteen cards gets turned up in the beginning (2, 3, 4, ... , J, Q, K, A). So each hand played needs to be scored under its own card. I would need to be able to switch back and forth between all thirteen at need to enter a score for a hand. So no matter what solitaire game I am playing it seems that it would boil down to: class SolitaireGame(): def __init__(self, name): self.name = name Say I go with the aforementioned game with 13 separate scores to keep track of. The names of these games might be "Two_Mastery", "Three_Mastery", ... , "Ace_Mastery". In principle I want 13 objects with each one keeping track of each of the above games. Then I might want to switch to "Spider_Solitaire", keep track of its score, then go to something else, then back to Mastery, etc. How on earth am I to generate unique identifiers for each of these SolitaireGame objects in a rational way, not knowing in advance moment to moment what type of solitaire game I might be playing? I am *not* wanting to discard one object prior to creating a new one for a new game. I would like to have all such objects to peacefully coexist and be able to switch between them at will. Of course the intent is to persistently store these objects on disk upon program closure. TIA! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to write a function which reads files
On Wed, Aug 8, 2018 at 8:30 PM boB Stepp wrote: > > On Tue, Aug 7, 2018 at 9:13 AM Rafael Knuth wrote: Curses! Sorry, Chris! This should be: > > Chris Warrick wrote: > > > Also, consider using snake_case instead of PascalCase for your > > > function name, since the latter is typically used for classes, and > > > perhaps call it read_file to better describe it? > > > > thanks, I wasn't aware of the naming conventions for functions and classes. > > will bear that in mind! > > Have you had a look at PEP 8 yet? It covers most of the Python > stylistic conventions, particularly if you intend to contribute to > Python and its standard libraries. It may be found at: > https://www.python.org/dev/peps/pep-0008/ -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to write a function which reads files
On Tue, Aug 7, 2018 at 9:13 AM Rafael Knuth wrote: > Alan Gauld wrote: > > Also, consider using snake_case instead of PascalCase for your > > function name, since the latter is typically used for classes, and > > perhaps call it read_file to better describe it? > > thanks, I wasn't aware of the naming conventions for functions and classes. > will bear that in mind! Have you had a look at PEP 8 yet? It covers most of the Python stylistic conventions, particularly if you intend to contribute to Python and its standard libraries. It may be found at: https://www.python.org/dev/peps/pep-0008/ -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Questions about the formatting of docstrings
On Fri, Jul 27, 2018 at 12:50 AM Steven D'Aprano wrote: > > On Thu, Jul 26, 2018 at 11:34:11PM -0500, boB Stepp wrote: > > (1) The author claims that reStructuredText is the official Python > > documentation standard. Is this true? If yes, is this something I > > should be doing for my own projects? > > Yes, it is true. If you write documentation for the Python standard > library, they are supposed to be in ReST. Docstrings you read in > the interactive interpreter often aren't, but the documentation you read > on the web page has all been automatically generated from ReST text > files. What tool is being used to generate the documentation from the ReST text files? Thanks! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Questions about the formatting of docstrings
I am near the end of reading "Documenting Python Code: A Complete Guide" by James Mertz, found at https://realpython.com/documenting-python-code/ This has led me to a few questions: (1) The author claims that reStructuredText is the official Python documentation standard. Is this true? If yes, is this something I should be doing for my own projects? (2) How would type hints work with this reStructuredText formatting? In part of the author's reStructuredText example he has: [...] :param file_loc: The file location of the spreadsheet :type file_loc: str [...] It seems to me that if type hinting is being used, then the ":type" info is redundant, so I wonder if special provision is made for avoiding this redundancy when using type hinting? TIA! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Wish to upgrade Python 3.6.5 to Python 3.6.6 for Linux Mint 19
On Sat, Jul 14, 2018 at 8:23 PM Mats Wichmann wrote: > > take a look at pyenv. should make it fairly easy. > > https://github.com/pyenv/pyenv I just completed getting access to Python 3.6.6 using pyenv, so I guess I'll post my experience for future searchers. It was not totally painless, and I am still pondering whether I used "sudo" inappropriately or not. Recall I am on Linux Mint 19 Cinnamon edition. First, the page Mats linked to mentioned an automatic installer for pyenv in another GitHub project of the author's, so I used that. It was here: https://github.com/pyenv/pyenv-installer I used the recommended "GitHub way" instead of the PyPi way which apparently is still in development and doesn't work for Python 3 anyway. So I ran: $ curl -L https://github.com/pyenv/pyenv-installer/raw/master/bin/pyenv-installer | bash Then I added to the end of my .bashrc: export PATH="/home/bob/.pyenv/bin:$PATH" eval "$(pyenv init -)" eval "$(pyenv virtualenv-init -)" This apparently allows pyenv's "shims" to take precedence in the search path for Python versions. Warning: On the page Mats linked there are some reports of getting into an infinite search loop if these lines are added to .bashrc. After pondering the specifics I did not think it would affect me, so I went ahead with what I did. I then did the suggested restart of my shell with: $ exec "$SHELL" pyenv seemed to be successfully installed. I ran $ pyenv update just to be sure I had the latest, greatest, which I did. I then ran $pyenv install --list to see if Python 3.6.6 was available. It was and the list of available versions is HUGE running from 2.1.3 to 3.8-dev to Active Python versions to Anaconda versions, IronPython, Jython, MiniConda, PyPy, Stackless, etc. So I thought I was ready to download and install Python 3.6.6 with $ pyenv install 3.6.6 It *did* download from https://www.python.org/ftp/python/3.6.6/Python-3.6.6.tar.xz, something you could tell I was concerned about from my earlier posts. Unfortunately I got: Installing Python-3.6.6... BUILD FAILED (LinuxMint 19 using python-build 20180424) So I went to https://github.com/pyenv/pyenv/wiki/Common-build-problems, which at the very top of the page recommended running this: $ sudo apt-get install -y make build-essential libssl-dev zlib1g-dev libbz2-dev \ libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev \ xz-utils tk-dev libffi-dev So without pausing for further thought I did run it, but now wonder if this will cause me future consequences with system stuff as later I read on the FAQ page a similar command without granting sudo privileges. So I jumped into the fire on this one without fully understanding what I was doing. But after doing this I was able to get 3.6.6, but there was still one more thing to do and that was to run $ pyenv global 3.6.6 because I did want to be able to type python3 in the shell and get specifically 3.6.6 as my default version -- for now at least. I probably did not do everything like I should, but maybe this will help someone down the line do better. So far I seem to have everything working and doing what I had hoped for. pyenv looks like a fine tool for managing as many Python versions as one wants to play around with, and does seem to support virtual environments with a plugin. boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Wish to upgrade Python 3.6.5 to Python 3.6.6 for Linux Mint 19
On Sun, Jul 15, 2018 at 3:30 PM Terry Carroll wrote: > That being said, if you do want to update to the latest version available > for Mint, this command should do it for you: > >sudo apt-get install --only-upgrade python3 > > If Mint doesn't have a vetted 3.6.6 yet, I would leave it alone. This is what led me to my question, I could not find a "vetted 3.6.6". However, I will keep your suggested command in mind for the future. I have decided I am going to try out Mats' suggestion of pyenv. It seems clean, flexible, and does not mess with the system Python. Thanks! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Wish to upgrade Python 3.6.5 to Python 3.6.6 for Linux Mint 19
On Sun, Jul 15, 2018 at 1:38 AM boB Stepp wrote: > > On Sat, Jul 14, 2018 at 11:52 PM boB Stepp wrote: > > > > On Sat, Jul 14, 2018 at 8:43 PM boB Stepp wrote: > > > > > > On Sat, Jul 14, 2018 at 8:23 PM Mats Wichmann wrote: > > > > > > > > take a look at pyenv. should make it fairly easy. > > > > > > > > https://github.com/pyenv/pyenv > > > > > > This does look interesting. On the linked page, after installing and > > > configuring pyenv, it says to install Python as follows giving a 2.7.8 > > > example: > > > > > > $ pyenv install 2.7.8 > > > > > > Where and how does it get its Python installation? > > > > After a lot of searching, I'm still not sure how pyenv is working its > > magic. On https://github.com/pyenv/pyenv/wiki it says: > > > > "pyenv will try its best to download and compile the wanted Python version, > > ..." > > > > This suggests that it is getting the source from somewhere > > (python.org/downloads ?) and then compiling it locally. Is this what > > it actually does? > > After too much fruitless searching I finally found a more direct > confirmation of what I was suspecting to be true at Oops! Too sleepy. Forgot to paste the link where I found the below info. It's at: https://bastibe.de/2017-11-20-pyenv.html > "In contrast, with PyEnv, you install a Python. This can be a version > of CPython, PyPy, IronPython, Jython, Pyston, stackless, miniconda, or > even Anaconda. It downloads the sources from the official repos, and > compiles them on your machine [1]. Plus, it provides an easy and > transparent way of switching between installed versions (including any > system-installed versions). After that, you use Python's own venv and > pip." > > This sounds like exactly what I need! Thanks for this, Mats!! I will > give it a whirl later today after I wake up. > > -- > boB -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Wish to upgrade Python 3.6.5 to Python 3.6.6 for Linux Mint 19
On Sat, Jul 14, 2018 at 11:52 PM boB Stepp wrote: > > On Sat, Jul 14, 2018 at 8:43 PM boB Stepp wrote: > > > > On Sat, Jul 14, 2018 at 8:23 PM Mats Wichmann wrote: > > > > > > take a look at pyenv. should make it fairly easy. > > > > > > https://github.com/pyenv/pyenv > > > > This does look interesting. On the linked page, after installing and > > configuring pyenv, it says to install Python as follows giving a 2.7.8 > > example: > > > > $ pyenv install 2.7.8 > > > > Where and how does it get its Python installation? > > After a lot of searching, I'm still not sure how pyenv is working its > magic. On https://github.com/pyenv/pyenv/wiki it says: > > "pyenv will try its best to download and compile the wanted Python version, > ..." > > This suggests that it is getting the source from somewhere > (python.org/downloads ?) and then compiling it locally. Is this what > it actually does? After too much fruitless searching I finally found a more direct confirmation of what I was suspecting to be true at "In contrast, with PyEnv, you install a Python. This can be a version of CPython, PyPy, IronPython, Jython, Pyston, stackless, miniconda, or even Anaconda. It downloads the sources from the official repos, and compiles them on your machine [1]. Plus, it provides an easy and transparent way of switching between installed versions (including any system-installed versions). After that, you use Python's own venv and pip." This sounds like exactly what I need! Thanks for this, Mats!! I will give it a whirl later today after I wake up. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Wish to upgrade Python 3.6.5 to Python 3.6.6 for Linux Mint 19
On Sat, Jul 14, 2018 at 8:43 PM boB Stepp wrote: > > On Sat, Jul 14, 2018 at 8:23 PM Mats Wichmann wrote: > > > > take a look at pyenv. should make it fairly easy. > > > > https://github.com/pyenv/pyenv > > This does look interesting. On the linked page, after installing and > configuring pyenv, it says to install Python as follows giving a 2.7.8 > example: > > $ pyenv install 2.7.8 > > Where and how does it get its Python installation? After a lot of searching, I'm still not sure how pyenv is working its magic. On https://github.com/pyenv/pyenv/wiki it says: "pyenv will try its best to download and compile the wanted Python version, ..." This suggests that it is getting the source from somewhere (python.org/downloads ?) and then compiling it locally. Is this what it actually does? boB -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Wish to upgrade Python 3.6.5 to Python 3.6.6 for Linux Mint 19
On Sat, Jul 14, 2018 at 8:23 PM Mats Wichmann wrote: > > take a look at pyenv. should make it fairly easy. > > https://github.com/pyenv/pyenv This does look interesting. On the linked page, after installing and configuring pyenv, it says to install Python as follows giving a 2.7.8 example: $ pyenv install 2.7.8 Where and how does it get its Python installation? boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Wish to upgrade Python 3.6.5 to Python 3.6.6 for Linux Mint 19
On Sat, Jul 14, 2018 at 8:18 PM Jim wrote: > If you look you might find a PPA that has packaged it. I installed > python 3.6.5 (no help to you) on Mint 18 from here: > https://launchpad.net/~jonathonf/+archive/ubuntu/python-3.6'. That is an interesting thought. My only concern is how does one choose a "safe" PPA? With the recent security breaches of Gentoo and Arch Linux repositories, nothing seems safe nowadays, and PPAs seem dependent on trusting someone apart from the official Linux distribution. However, when I was doing my searching, this particular PPA came up more than once, so I imagine he is reliable. > Maybe you can find one that does 3.6.6 or ask Jonathon if he intends to > package 3.6.6. Whatever you do I would suggest you install it in a > virtual environment, especially if you are going to be experimenting > with a lot of libraries. If you use a virtual environment you don't have > to worry about breaking your system python. Your advice is very solid. Alas! I was hoping to delay getting intimate with virtual environments, but based on my own searches, your advice and Alan's it appears to me that I have three obvious choices: (1) Just stick with the current system Python 3 until an issue comes up that 3.6.6 fixes. (2) Wait on the system Python 3 to provide an update to Python 3.6.6. (3) Install into a virtual environment -- either compiling from source or the PPA route. Thanks, Jim! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Wish to upgrade Python 3.6.5 to Python 3.6.6 for Linux Mint 19
I have finally taken the plunge and abandoned Windows for Linux Mint 19. I had been doing a dual-boot, but I found I spent most of my time where I was comfortable -- Windows 7 -- and mostly avoided my Linux installation. So I took my pacifier away and went for it! Linux Mint 19 comes with Python 3.6.5 pre-installed. However, my son and I are working on a couple of things together, and decided to use the latest bugfix releases of Python 3.6 for them. I would not think that upgrading from 3.6.5 to 3.6.6 would break anything in my system Python 3. But after much searching I cannot find an _easy_ way to do this upgrade. I would rather delay the learning experience of compiling Python from source if I can. Is there any _easy_ way to upgrade the system Python 3.6.5 to 3.6.6 (Without wreaking system-wide havoc)? -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] learn python to build payment processor
On Wed, Jul 11, 2018 at 9:01 PM Mats Wichmann wrote: From: > (see https://www.python.org/dev/peps/pep-0020/) It says: "Abstract Long time Pythoneer Tim Peters succinctly channels the BDFL's guiding principles for Python's design into 20 aphorisms, only 19 of which have been written down." What is the unwritten twentieth aphorism? If this is a joke or pun, I'm missing it. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] egg timer
Greetings, Paula! On Sun, Jun 24, 2018 at 4:52 PM Paula Malimba wrote: > > Hello, > > I'm new to programming and am studying the book Begin to Code with Python. > I'm stuck in lesson 3, trying to make an egg timer. I keep having a syntax > error. > > Please help!!! Please pretend for a moment that you received your own email above. Read it carefully. If you were trying to help this person, "Paula", how would you answer the following questions? 1) Hmm. She is having a syntax error. This could be one of a large number of possible syntax errors, each having a different cause. Which syntax error might she be having? 2) She is doing lesson 3 from the book "Begin to Code with Python". I don't own that particular book. I wonder what that lesson is about and what specific problem(s) she is trying to solve? 3) How is she running her program? Is she running it directly from the Python terminal? From a ".py" file? 4) I wonder what version of Python she is running? Python 2.X or 3.X? This might make a difference in how I answer her. 5) And what operating system is she using? This could be a factor, too. Paula, I am *not* trying to be condescending! But your email as sent is so vague I (and everyone else) has no idea how to help you. As an example of the kind of information we need, I artificially generated a syntax error of my own. If I were asking for help I would probably say something like the following: Hi folks! I am working on an egg timer challenge from the book "Begin to Code with Python". In lesson 3 it asks me to query the user to enter how many minutes he/she wants his/her egg boiled. I wrote the following code in my Python interpreter: py3: time = input("Please tell me how many minutes you want your egg to boil?) , but I got the following error: File "", line 1 time = input("Please tell me how many minutes you want your egg to boil?) ^ SyntaxError: EOL while scanning string literal I am using Python 3.6.5 on Windows 7-64 bit. I was trying to get the amount of time in minutes the user wanted me to boil the egg in my "time" variable, but I got the above error. What am I doing wrong? Do you think you might be able to answer my question? Hope this helps us to help you, and we really do want to help! Cheers! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Nested use of replication operator on lists
The subtleties of the interactions between the concepts of references to objects, mutable objects, immutable objects, shallow copy of objects and deep copy of objects continue to surprise me! On Fri, May 25, 2018 at 1:27 AM, Steven D'Aprano <st...@pearwood.info> wrote: > On Thu, May 24, 2018 at 10:33:56PM -0500, boB Stepp wrote: > The result of list * 3 is always a list. What matters is the items > inside the list. > > What the * operator does is create a new list containing the entries of > the old list repeated. I was not properly appreciating that that these repeated objects were the *same identical* objects that were in the pre-replicated list. > > If the items are immutable, like integers, that is perfectly fine. > Copying an immutable object is a waste of time, and in fact the standard > copy function will usually refuse to do so: > > py> import copy > py> a, b = 1234567, [] # immutable int, mutable list > py> copy.copy(a) is a # is the copy the same object as the original? > True > py> copy.copy(b) is b # is the copy the same object as the original? > False > > (To be precise, it is not the copy() function that refuses to make a > copy. It the object itself: each object knows how to copy itself, and > immutable ones will typically return themselves because they know it > makes no difference.) It appears to me that a logical consequence of a particular object being immutable is that it also must be unique. > For integers, floats, strings and other immutable objects, this is > exactly what you want. There is no operation we can do to an immutable > operation to change its value, so there is no way to distinguish between > the same object twice or an object and a fresh copy. > > (Except for using the "is" operator, or the id() function.) I should have thought to use "is". I had seen "id()", but had not previously investigated its usage. Danny's answer inspired me to read up on id() tonight. Useful investigative tools! There is another subtlety that I am not certain I am truly understanding: py3: empty = [] py3: a = copy.copy(empty) py3: a is empty False py3: a = [empty] py3: b = copy.copy(a) py3: a is b False py3: a[0] is b[0] True py3: c = copy.deepcopy(a) py3: a is c False py3: a[0] is c[0] False Up to this point I am fine, but ... py3: e = a*5 py3: e [[], [], [], [], []] py3: all(x is empty for x in e) True OK, I was expecting this. py3: f = copy.deepcopy(e) py3: any(x is empty for x in f) False Still OK ... py3: all(x is f[0] for x in f) True But this I found mildly surprising. I guess I was thinking that f = copy.deepcopy(e) would be equivalent to manually entering "[]" five times inside an enclosing list: py3: f = [[], [], [], [], []] py3: f[0] is f[1] False py3: all(x is f[0] for x in f) False So it surprised me that the deep copy created the same reference for all members, just like in the original list. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Nested use of replication operator on lists
On Python-list Steve started a thread, "List replication operator" (https://mail.python.org/pipermail/python-list/2018-May/733513.html) and wrote the following: Python has a sequence replication operator: py> [1, 2]*3 [1, 2, 1, 2, 1, 2] Unfortunately, it is prone to a common "gotcha": py> x = [[]]*5 # make a multi-dimensional list py> x [[], [], [], [], []] py> x[0].append(1) py> x [[1], [1], [1], [1], [1]] The reason for this behaviour is that * does not copy the original list's items, it simply replicates the references to the items. So we end up with a new list containing five references to the same inner list. I am having trouble correlating the behavior of the one-dimensional case with the two-dimensional case. The result of [1, 2]*3 seems to be an actual list, not a replication of the references to the items in the original list, [1, 2]. Or if it is, then I do not know how to demonstrate it. Also the "replication operator" does not seem to be replicating anything list-wise if it is instead replicating references to the original list's members. I request explanation/clarification please. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help
On Tue, May 15, 2018 at 7:51 PM, Steven D'Apranowrote: > You also seem to be using Python 2. In Python 2, you should never use > the input() function. Instead, use raw_input() instead. What are you seeing that suggests the OP is using Python 2? I am missing what you are seeing/understanding. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help
Greetings! On Tue, May 15, 2018 at 2:49 PM, Sam Hoffmanwrote: > Traceback (most recent call last): > File "/Users/samhoffman/Documents/test.py", line 54, in > Battle() > File "/Users/samhoffman/Documents/test.py", line 41, in Battle > Move = input('What Will You Do? Fight or Run: ') > File "", line 1, in > NameError: name 'Run' is not defined The Python interpreter believes that Run is a variable to which no value has been assigned. > > import time > import random > #Pokemon Stats > Bulbasaur = {'N' : 'Bulby', > 'HP' : 20, > 'Level' : 5, > 'Atk' : 8, > 'Def' : 9, > 'Spd' : 6} > > > Rattata = {'N' : 'Rattata', >'HP' : 15, >'Level' : 3, >'Atk' : 5, >'Def' : 6, >'Spd' : 4} > > #Move damages > BM = {'Vinewhip' : 45, > 'Tackle' : 40, > 'Razorleaf' : 55} > > > RM = {'Tackle' : 40, > 'Quick Attack' : 40, > 'Bite' : 60} > > > #Damage is (2xLevel)/5)+2)xPower)xAtk/Def)+2)/50 > > > > #Battle Function > def Battle(): > print('Wild '+Rattata['N']+' Appeared!') > time.sleep(1) > print('Go, '+Bulbasaur['N']+'!') > time.sleep(1) > print(Bulbasaur['N']+ ' is out.') > while Bulbasaur['HP'] >= 1 and Rattata['HP'] >= 1: > Move = input('What Will You Do? Fight or Run: ') > if Move == Fight: > pass > elif Move == Run: # This appears to be the problem. Make Run into a > string, "Run" or 'Run'. > RC = random.randint(1,3) > if RC == 1 or 3: # This probably does not do what you think it > does! > print('You Didn\'t Get Away!') > else: > print('You Got Away!') > break > else: > print('Typo') > break > Battle() HTH! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Iteration issues
On Wed, May 9, 2018 at 6:27 PM, Roger Lea Schererwrote: > Hello, again. > > I want to count words in a text file. If a word repeats I want to increase > the count by 1; if the word is new to the dictionary, I want to add the > word to the dictionary. Everything works like I would like and expect, > except for it only adds the last word of each line to the dictionary. What > am I missing? > > import string > > file_name = 'oxford.txt' > wordset = {} > with open(file_name, 'r') as f: > for line in f: > sentence = line.strip() > sentence = sentence.strip(string.punctuation) > print(sentence) > sentence = sentence.lower() > word_list = sentence.strip() > word_list = word_list.split(' ') > > for i in range(len(word_list)): > word_list[i] = word_list[i].strip(string.punctuation) I was wondering if you might want to write a small function so that you can remove all punctuation symbols from each line in one fell swoop? Something like (in pseudocode): Iterate over string.punctuation. If a punctuation symbol is in your string: Replace that symbol with an empty string. That might make your code more direct and compact. boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Iteration issues
Greetings! On Wed, May 9, 2018 at 6:27 PM, Roger Lea Schererwrote: > Hello, again. > > I want to count words in a text file. If a word repeats I want to increase > the count by 1; if the word is new to the dictionary, I want to add the > word to the dictionary. Everything works like I would like and expect, > except for it only adds the last word of each line to the dictionary. What > am I missing? > > import string > > file_name = 'oxford.txt' > wordset = {} > with open(file_name, 'r') as f: > for line in f: > sentence = line.strip() A small quibble: Unless you get lucky, the identifier 'sentence' is unlikely to be an actual sentence. > sentence = sentence.strip(string.punctuation) This will only remove punctuation at the beginning or the end of the line. > print(sentence) > sentence = sentence.lower() > word_list = sentence.strip() Haven't you already done this above? > word_list = word_list.split(' ') > > for i in range(len(word_list)): It is better style and more direct to write this as for word in word_list: If you need the index of the word in the word_list (as you do below) then you can use enumerate: for index, word in enumerate(word_list): > word_list[i] = word_list[i].strip(string.punctuation) > print(word_list) > > if word_list[i] in wordset: > wordset[word_list[i]] += 1 > else: > wordset[word_list[i]] = 1 > print(wordset) And here we come to the answer to the actual question you asked. Look at your indentation. Your if/else construct is not within your for loop's scope/block, so you are only checking for the last value of i, which corresponds to the last word in word_list. So, as you have written your code: with ... for line in f: ... for i in range(len(word_list)): ... if word_list[i] = ... wordset[word_list[i]] += 1 else: wordset[word_list[i]] = 1 I used "..." to replace much of your code so you can see the needed indentation levels better. HTH! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to separate UI code from program logic?
On Mon, May 7, 2018 at 12:26 AM, boB Stepp <robertvst...@gmail.com> wrote: > def get_collatz_number(integer): > """Returns the Collatz sequence number corresponding to integer. integer > must be > 0, or the sequence will not converge to 1.""" > > if integer % 2 == 0: > return integer // 2 > else: > return 3 * integer + 1 > > def generate_collatz_sequence(seed): > """Creates a generator, which will yield a Collatz sequence starting from > seed. seed must be a positive integer, or the sequence will not converge > to > 1.""" > > collatz_number = seed > while True: > collatz_number = get_collatz_number(collatz_number) > yield collatz_number > if collatz_number == 1: > return > Questions and comments: After taking a break from this and coming at this afresh, I immediately saw an answer to this question: > 2) I spent a lot of effort trying to come up with a way to combine > the two functions, get_collatz_number() and > generate_collatz_sequence(), into something both more compact and more > readable, but I was unsuccessful. I suspect there is a better way. > Is there? And how would I do it? def generate_collatz_sequence(seed): """Creates a generator, which will yield a Collatz sequence starting from seed. seed must be a positive integer, or the sequence will not converge to 1.""" collatz_number = seed while True: if collatz_number % 2 == 0: collatz_number //= 2 else: collatz_number = 3 * collatz_number + 1 yield collatz_number if collatz_number == 1: return Judging from the lack of responses, I guess I must have been on track on the other questions. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to separate UI code from program logic?
On Sun, May 6, 2018 at 5:05 PM, Alan Gauld <alan.ga...@yahoo.co.uk> wrote: > On 6 May 2018, at 23:00, boB Stepp <robertvst...@gmail.com> wrote: >>My understanding of best practice here is that I should not have any >>print() calls inside my generate_collatz_sequence() function. I >>_could_ store the generated sequence in a list and return it, but that >>does not seem like good use of RAM if some user-supplied seed value >>led to kazillions of Collatz sequence numbers being generated. > > The clue is in that last word. > Write a generator function that yields the intermediate results. Ok. I've been reading up on generators and playing around with them today. And then, per Alan's hint, tried to separate all display code from my program logic code. What was originally meant to be a throw-away effort, has somehow mushroomed into something I hope resembles a finished product. The results I came up with are as follows: # #!/usr/bin/env python3 """This program will generate a Collatz sequence from a user-supplied positive integer. According to Wikipedia (https://en.wikipedia.org/wiki/Collatz_conjecture): "The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined as follows: start with any positive integer n. Then each term is obtained from the previous term as follows: if the previous term is even, the next term is one half the previous term. Otherwise, the next term is 3 times the previous term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1." """ def get_positive_integer(): """Get a positive integer from the user.""" while True: try: integer = int(input("Please enter a positive integer: ")) if integer > 0: return integer else: print("That was not a positive integer!") continue except ValueError: print("That was not an integer!") continue def display_collatz_numbers(seed, collatz_generator): """Display a Collatz sequence, one value per line, given the seed (Which will be the first number in the sequence.) and a generator which will yield the Collatz sequence.""" print("\nThe seed number: ", seed) for sequence_index, number in enumerate(collatz_generator): print("Sequence number", sequence_index + 1, ": ", number) def ask_to_continue(): choice = input("Do you wish to generate another Collatz sequence?").lower() return choice.startswith('y') def get_collatz_number(integer): """Returns the Collatz sequence number corresponding to integer. integer must be > 0, or the sequence will not converge to 1.""" if integer % 2 == 0: return integer // 2 else: return 3 * integer + 1 def generate_collatz_sequence(seed): """Creates a generator, which will yield a Collatz sequence starting from seed. seed must be a positive integer, or the sequence will not converge to 1.""" collatz_number = seed while True: collatz_number = get_collatz_number(collatz_number) yield collatz_number if collatz_number == 1: return def main(): """Run program.""" while True: seed = get_positive_integer() display_collatz_numbers(seed, generate_collatz_sequence(seed)) if ask_to_continue(): continue else: break if __name__ == '__main__': main() # Questions and comments: 1) I am open to a general critique on making this code better. 2) I spent a lot of effort trying to come up with a way to combine the two functions, get_collatz_number() and generate_collatz_sequence(), into something both more compact and more readable, but I was unsuccessful. I suspect there is a better way. Is there? And how would I do it? 3) Is this the correct way to separate display code from program logic code? Is there a better way to do this? 4) I think this is the first time I've actually tried to implement a generator function. Did I do a good Pythonic implementation of this? As always, thanks! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to separate UI code from program logic?
On Sun, May 6, 2018 at 5:05 PM, Alan Gauld <alan.ga...@yahoo.co.uk> wrote: > On 6 May 2018, at 23:00, boB Stepp <robertvst...@gmail.com> wrote: >>My understanding of best practice here is that I should not have any >>print() calls inside my generate_collatz_sequence() function. I >>_could_ store the generated sequence in a list and return it, but that >>does not seem like good use of RAM if some user-supplied seed value >>led to kazillions of Collatz sequence numbers being generated. > > The clue is in that last word. > Write a generator function that yields the intermediate results. Aha! Of course the book I am poking around in does not even cover generator functions ... But I will plow ahead as usual and implement your suggestion. Thanks, Alan! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Need help with a virtual environment mess
On Sun, May 6, 2018 at 11:05 AM, Jimwrote: > In a prior thread you guys helped me fix a problem with pip after I upgraded > an installed version of python 3.6 on my Mint 18 system. Pip would not run > in my python 3.6 virtual environment. The fix was to use synaptic to install > python3-distutils. I thought everything was ok until I tried to run a old > script from a different VE using python 3.5 which could not import tkinter. > > I have 4 versions of python on this system: > system Python2 = 2.7.12 (default) > system Python3 = 3.5.2 (default) > a VE called env = 3.5.2 > a Ve called env36 = 3.6.5 > > This is the error I get trying to import tkinter in env, I also get the same > error if I try to import it in system python3. > > jfb@jims-mint18 ~ $ source /home/jfb/EVs/env/bin/activate > (env) jfb@jims-mint18 ~ $ python > Python 3.5.2 (default, Nov 23 2017, 16:37:01) > [GCC 5.4.0 20160609] on linux > Type "help", "copyright", "credits" or "license" for more information. import tkinter as tk > Traceback (most recent call last): > File "/usr/lib/python3.5/tkinter/__init__.py", line 36, in > import _tkinter > ImportError: No module named '_tkinter' > > During handling of the above exception, another exception occurred: > > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python3.5/tkinter/__init__.py", line 38, in > raise ImportError(str(msg) + ', please install the python3-tk package') > ImportError: No module named '_tkinter', please install the python3-tk > package > > If I go to synaptic and install the python3-tk it installs version 3.6.5 of > the package and I can still not import tkinter in env with python 3.5.2, but > I can in env36 with python 3.6.5. > As I have not yet tried to play around with virtual environments, I may be about to do more harm than help, but I will plow ahead anyway! ~(:>)) My primitive understanding of installing Python versions that are different from the system Python version into a virtual environment, is that you have to install all dependencies you need from within that virtual environment you created. If I am correct about this then your error messages suggest you need to install the tkinter stuff from within that virtual environment using that virtual environment's pip. Hopefully I am too far off from the truth here, but in any event, I hope this helps you in your problem! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] How to separate UI code from program logic?
I was solving a programming problem in one of my books concerning the generation of a Collatz sequence (https://en.wikipedia.org/wiki/Collatz_conjecture), and started to wonder how I should separate my program's output from its logic. It seems like this should be obvious to me, but, unfortunately, it isn't. The core functions from my program are: # def collatz(integer): """Returns the Collatz sequence number corresponding to integer. integer must be > 0, or the sequence will not converge to 1.""" if integer % 2 == 0: return integer // 2 else: return 3 * integer + 1 def generate_collatz_sequence(seed): """Generates a Collatz sequence starting from seed. seed must be a positive integer, or the sequence will not coverge to 1.""" counter = 0 collatz_number = seed print("Collatz seed number: ", collatz_number) while True: counter += 1 collatz_number = collatz(collatz_number) print("Collatz number", counter, ": ", collatz_number) if collatz_number == 1: print("The Collatz sequence has once again converged to 1!") break # My understanding of best practice here is that I should not have any print() calls inside my generate_collatz_sequence() function. I _could_ store the generated sequence in a list and return it, but that does not seem like good use of RAM if some user-supplied seed value led to kazillions of Collatz sequence numbers being generated. As it stands there will be no theoretical RAM issues as the numbers are being generated and then outputted one at a time. OTOH, if I created some kind of display messages function, I don't see how I have gained anything as these calls to a display message function would just be taking the place of the print() calls. The end result would be the same -- display code interleaved with program logic code. What am I being dense about here? -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Extract main text from HTML document
On Sat, May 5, 2018 at 12:59 PM, Simon Connahwrote: > I was wondering if there was a way in which I could download a web > page and then just extract the main body of text without all of the > HTML. I do not have any experience with this, but I like to collect books. One of them [1] says on page 245: "Beautiful Soup is a module for extracting information from an HTML page (and is much better for this purpose than regular expressions)." I believe this topic has come up before on this list as well as the main Python list. You may want to check it out. It can be installed with pip. [1] "Automate the Boring Stuff with Python -- Practical Programming for Total Beginners" by Al Sweigart. HTH! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Pi approximation
I see I wrote the below a little too quickly! Don't forget to take the reciprocal when printing. You might want to modify my naming of variables to reflect this. And return the reciprocal, which actually gives the pi approximation in the function form. On Wed, Mar 28, 2018 at 9:08 PM, boB Stepp <robertvst...@gmail.com> wrote: > On Wed, Mar 28, 2018 at 2:09 PM, Roger Lea Scherer <rls...@gmail.com> wrote: >> In one of my lessons I am asked to compare approximations for pi. I got >> everything to work properly and my attempt is successful and matches >> Python's approximation up to 15 digits to the right of the decimal, but I >> suspect I can do this programmatically rather than the repetitious way I >> did. >> >> I tried "for i in range(10):"; then I tried "c += c" so it would be a sum. >> Those attempts did not work. I tried math.fsum and though the documentation >> says it is for iterables I could not get it to work as I desired. I >> received an error that said TypeError: 'float' object is not iterable >> >> I included all the code so I wouldn't neglect any you might need. Can you >> help again? > > You are using the formula in the Wikipedia article, right? Mimic in > Python what you are doing by manually. Do something like: > > pi_approx = 0.0 > for k in range(10): > pi_approx += your formula from the Wikipedia article > > print(pi_approx) > > You might even want to make a function out of the above so that you > can try iterating over different ending values for k: > > def calc_pi(loop_value): > pi_approx = 0.0 > for k in range(loop_value): > pi_approx += your formula > return pi_approx > > print(calc_pi(10)) > > You actually had all the pieces mentioned. You just need to put them > together, looping just like you would do if you were calculating by > hand. > > HTH! > > boB > >> >> # compare various approximations of pi >> import math >> import random >> >> # simplest estimate >> a = 22/7 >> print(a) >> >> # next simplest >> b = 355/113 >> print(b) >> >> # from wikipedia: >> # In 1910, the Indian mathematician Srinivasa Ramanujan found several >> rapidly converging infinite series >> c = (2*math.sqrt(2)/9801) * (((math.factorial(4*0))*(1103+26390*0)) / >> ((math.factorial(0)**4)*(396**(4*0 >> d = (2*math.sqrt(2)/9801) * (((math.factorial(4*1))*(1103+26390*1)) / >> ((math.factorial(1)**4)*(396**(4*1 >> e = (2*math.sqrt(2)/9801) * (((math.factorial(4*2))*(1103+26390*2)) / >> ((math.factorial(2)**4)*(396**(4*2 >> f = (2*math.sqrt(2)/9801) * (((math.factorial(4*3))*(1103+26390*3)) / >> ((math.factorial(3)**4)*(396**(4*3 >> g = (2*math.sqrt(2)/9801) * (((math.factorial(4*4))*(1103+26390*4)) / >> ((math.factorial(4)**4)*(396**(4*4 >> h = (2*math.sqrt(2)/9801) * (((math.factorial(4*5))*(1103+26390*5)) / >> ((math.factorial(5)**4)*(396**(4*5 >> i = (2*math.sqrt(2)/9801) * (((math.factorial(4*6))*(1103+26390*6)) / >> ((math.factorial(6)**4)*(396**(4*6 >> j = (2*math.sqrt(2)/9801) * (((math.factorial(4*7))*(1103+26390*7)) / >> ((math.factorial(7)**4)*(396**(4*7 >> k = (2*math.sqrt(2)/9801) * (((math.factorial(4*8))*(1103+26390*8)) / >> ((math.factorial(8)**4)*(396**(4*8 >> l = (2*math.sqrt(2)/9801) * (((math.factorial(4*9))*(1103+26390*9)) / >> ((math.factorial(9)**4)*(396**(4*9 >> m = c + d + e + f + g + h + i + j + k + l >> print(1/m) >> >> print(math.pi) -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Pi approximation
On Wed, Mar 28, 2018 at 2:09 PM, Roger Lea Schererwrote: > In one of my lessons I am asked to compare approximations for pi. I got > everything to work properly and my attempt is successful and matches > Python's approximation up to 15 digits to the right of the decimal, but I > suspect I can do this programmatically rather than the repetitious way I > did. > > I tried "for i in range(10):"; then I tried "c += c" so it would be a sum. > Those attempts did not work. I tried math.fsum and though the documentation > says it is for iterables I could not get it to work as I desired. I > received an error that said TypeError: 'float' object is not iterable > > I included all the code so I wouldn't neglect any you might need. Can you > help again? You are using the formula in the Wikipedia article, right? Mimic in Python what you are doing by manually. Do something like: pi_approx = 0.0 for k in range(10): pi_approx += your formula from the Wikipedia article print(pi_approx) You might even want to make a function out of the above so that you can try iterating over different ending values for k: def calc_pi(loop_value): pi_approx = 0.0 for k in range(loop_value): pi_approx += your formula return pi_approx print(calc_pi(10)) You actually had all the pieces mentioned. You just need to put them together, looping just like you would do if you were calculating by hand. HTH! boB > > # compare various approximations of pi > import math > import random > > # simplest estimate > a = 22/7 > print(a) > > # next simplest > b = 355/113 > print(b) > > # from wikipedia: > # In 1910, the Indian mathematician Srinivasa Ramanujan found several > rapidly converging infinite series > c = (2*math.sqrt(2)/9801) * (((math.factorial(4*0))*(1103+26390*0)) / > ((math.factorial(0)**4)*(396**(4*0 > d = (2*math.sqrt(2)/9801) * (((math.factorial(4*1))*(1103+26390*1)) / > ((math.factorial(1)**4)*(396**(4*1 > e = (2*math.sqrt(2)/9801) * (((math.factorial(4*2))*(1103+26390*2)) / > ((math.factorial(2)**4)*(396**(4*2 > f = (2*math.sqrt(2)/9801) * (((math.factorial(4*3))*(1103+26390*3)) / > ((math.factorial(3)**4)*(396**(4*3 > g = (2*math.sqrt(2)/9801) * (((math.factorial(4*4))*(1103+26390*4)) / > ((math.factorial(4)**4)*(396**(4*4 > h = (2*math.sqrt(2)/9801) * (((math.factorial(4*5))*(1103+26390*5)) / > ((math.factorial(5)**4)*(396**(4*5 > i = (2*math.sqrt(2)/9801) * (((math.factorial(4*6))*(1103+26390*6)) / > ((math.factorial(6)**4)*(396**(4*6 > j = (2*math.sqrt(2)/9801) * (((math.factorial(4*7))*(1103+26390*7)) / > ((math.factorial(7)**4)*(396**(4*7 > k = (2*math.sqrt(2)/9801) * (((math.factorial(4*8))*(1103+26390*8)) / > ((math.factorial(8)**4)*(396**(4*8 > l = (2*math.sqrt(2)/9801) * (((math.factorial(4*9))*(1103+26390*9)) / > ((math.factorial(9)**4)*(396**(4*9 > m = c + d + e + f + g + h + i + j + k + l > print(1/m) > > print(math.pi) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Pong using python
Greetings! On Mon, Feb 12, 2018 at 8:49 PM,wrote: > Tutor, > > Are you aware/familiar with DeVry University using python to educate > students using a PONG game? You should assume that we do not. But we probably can help you if you provide a specific, targeted question. Copy and paste a self-contained code example that demonstrates the problems you are having in a plain text email. Copy and paste any error tracebacks you received (in their entirety). Let us know which Python version you are using and your operating system type/version as well. Ask good questions and we will do our best to help (But we won't do your homework for you!). But if you instead ask vague questions you are unlikely to get a helpful response. Good luck and better thinking! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Does Python and its standard libraries use semantic versioning?
On Sat, Feb 10, 2018 at 5:34 PM, Alex Kleider <aklei...@sonic.net> wrote: > On 2018-02-10 01:07, Alan Gauld via Tutor wrote: >> >> On 10/02/18 05:44, boB Stepp wrote: >>> >>> I have been reading the interesting web page "Semantic Versioning > > > This link may be of interest to those following this thread: > http://nvie.com/posts/a-successful-git-branching-model/ Alex, I actually had just finished reading the page at your link, before I read the other on Semantic Versioning. For those interested, there is git-flow (At https://github.com/nvie/gitflow) to aid in the implementing of this type of release workflow. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Does Python and its standard libraries use semantic versioning?
I have been reading the interesting web page "Semantic Versioning 2.0.0" at https://semver.org/ I like how its use can supposedly make "dependency hell" a thing of the past. So I am wondering if Python and its standard libraries make use of semantic versioning as described in this article? But I suppose that for third party libraries anything goes? TIA! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Java equivalent of Python-Tutor?
On Wed, Feb 7, 2018 at 2:06 PM, Terry Carrollwrote: > > In my early days of using Python I benefited greatly from this Tutor list, > thanks to both Alan and Steven as well as as many contributors. I still check > in now and then and try to chime in to help now that I have a bit more > experience under my belt. > > I'm doing a few projects in Java now and would love to find a similar > resource that covers that language, and the Eclipse IDE. Some of my questions > are too newbie for a forum like stackoverflow (and most of the responses > there assume a non-newbie level of knowledge). > > Any suggestions? When I was dabbling with Java a few years ago, I found the Beginning Java Forum at JavaRanch helpful. It can be found at: https://coderanch.com/f/33/java -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Do _all_ Python builtin methods/functions return "None" IF ...
... they are not designed to explicitly return something else? The reason I ask is that I almost fell into the following trap: py3: a_lst = [0, 1, 2] py3: b_lst = a_lst.append(3) py3: a_lst, b_lst ([0, 1, 2, 3], None) Instead of "None" I was expecting "[0, 1, 2, 3]". Obviously I have a GCE (Gross Conceptual Error). I almost sent the above as my question, but then I realized (Finally!) that lst.append() performs an append operation on lst and returns None. Just like print() returns None. So my actual question is: For these types of methods/functions, is Python Both versions 2 and 3) consistent throughout and *always* returns None? TIA! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] When is and isn't "__file__" set?
I am actually interested in the answer to this question for Python versions 2.4, 2.6 and 3.x. At https://docs.python.org/3/reference/import.html?highlight=__file__#__file__ it says: __file__ is optional. If set, this attribute’s value must be a string. The import system may opt to leave __file__ unset if it has no semantic meaning (e.g. a module loaded from a database). If __file__ is set, it may also be appropriate to set the __cached__ attribute which is the path to any compiled version of the code (e.g. byte-compiled file). The file does not need to exist to set this attribute; the path can simply point to where the compiled file would exist (see PEP 3147). It is also appropriate to set __cached__ when __file__ is not set. However, that scenario is quite atypical. Ultimately, the loader is what makes use of __file__ and/or __cached__. So if a loader can load from a cached module but otherwise does not load from a file, that atypical scenario may be appropriate. I am still puzzling over things from the thread, "Why does os.path.realpath('test_main.py') give different results for unittest than for testing statement in interpreter?" The basic question I am trying to answer is how to determine the path to a particular module that is being run. For the experiments I have run thus far, the module attribute, "__file__", has so far reliably given me the absolute path to the module being run. But the documentation suggests that this attribute is optional. So what can I rely on here with "__file__"? The first sentence of the cited quote is not illuminating this sufficiently for me. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Testing
On Sun, Jan 7, 2018 at 5:38 PM, Steven D'Apranowrote: > I've tried emailing in response to the os.path.realpath thread twice, > and neither email has made it through. > > Alan, am I stuck in the moderator queue for some reason? This one made it through. My original answer to your post last night took so long to appear on https://mail.python.org/pipermail/tutor that I finally gave up and went to bed. But it was there when I awoke today! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Why does os.path.realpath('test_main.py') give different results for unittest than for testing statement in interpreter?
On Sun, Jan 7, 2018 at 8:32 AM, Alan Gauld via Tutor <tutor@python.org> wrote: > On 07/01/18 09:07, boB Stepp wrote: >> clarify this? What is the methodology that os.path.realpath(path) is >> actually following to yield a particular path name? And why does it >> not care if path refers to a real file or not? > > The os.path module is mostly a string manipulation toolkit. This is the critical piece that was eluding me. I assumed that the actual file system was being queried, checked and expanded as needed. > It checks that a string looks like a path and it de/constructs > paths from strings. But it does not pay muchy(any?) attention > to the filesystem. It doesn't care if the paths it deals > with are real paths or not, its purely manipulating the > strings according to the syntax rules for paths. I was assuming it was computing the actual path to the file given as its argument. Steve's comments make much more sense now as well as the "canonical" aspect. >> class TestOpenFileStrIntsToList(unittest.TestCase): >> """Tests for the function open_file_str_ints_to_list.""" >> >> def test_open_file_str_ints_to_list(self): >> """Ensure expected list of string integers is returned.""" >> >> path = os.path.dirname( >> os.path.realpath(__file__)) + '/test_data.dat' >> print('realpath =', os.path.realpath(__file__)) > > Yes, thats it although you could test using isfile() or > better still use a try/except around the open. > > Also you should strictly use os.path.join() to create the path Duly noted on os.path.join(). I have not gotten to thinking about the UI yet, and don't mind if a file not found error is generated here in the testing code as it will let me know I've screwed something up. This is strictly a play project to record my manual games of solitaire. I doubt it will be useful to anyone else. Once I get to coding the UI I might wrap this in a try/except if I feel I would gain any benefit from handling the exception. >> BTW, I am having trouble coming up with a good name for a string that >> looks like an integer that I plan on using int() later to convert the >> string to an integer. "String integer" is my best thought at this >> time. > > What's it for? Where did it come from? > type based names are rarely good, better to describe why/where. > > input_Id, read_Id, stored_Id etc > > Or substitute Ref, or Count or whatever for Id. > > Then the real int var name becomes the second part: > > Id = int(input_Id) > > or > > count = int(stored_count) The above has just now led me to a Homer Simpson "Doh!" moment. When I open the file and covert it to a list of "string" integers I currently have: with open(path) as infile: string_integers = [line.strip() for line in infile] and then run the list through another function to get an integer list. Why on earth didn't I just write: with open(path) as infile: total_scores = [int(line.strip()) for line in infile] which directly creates what I want directly? [Please don't answer this question! ~(:>)) ] -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Why does os.path.realpath('test_main.py') give different results for unittest than for testing statement in interpreter?
On Sun, Jan 7, 2018 at 4:51 AM, Albert-Jan Roskamwrote: > > On Jan 7, 2018 09:08, Steven D'Aprano wrote: >> realpath() returns the canonical path of the given filename. It doesn't >> try to locate some actual existing file. > > I always thought that os.path.realpath is the Python equivalent of Linux > realpath/readlink (http://man7.org/linux/man-pages/man3/realpath.3.html). And > that, thus, there's only a difference between input and output when the input > is a symlink (and maybe also when it's a hard link - in this case the > function actually also does something in Windows). But then, I don't really > know the meaning of the word "canonical", to tell you the truth (maybe #4 in > http://www.dictionary.com/browse/canonical) My hangup was mostly that I was assuming that an actually existing path to a real file was implied. Apparently that is not the case. So Alan's explanation has cleared that up for me (I think!). I agree with you that the 4th definition you cite: "4. Mathematics. (of an equation, coordinate, etc.) in simplest or standard form." is the most sensible definition in this context with Steve's caveats. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Why does os.path.realpath('test_main.py') give different results for unittest than for testing statement in interpreter?
On Sun, Jan 7, 2018 at 2:05 AM, Steven D'Aprano <st...@pearwood.info> wrote: > On Sun, Jan 07, 2018 at 12:49:59AM -0600, boB Stepp wrote: > >> Win7, Python 3.6.2 >> >> If I run a unit test with the following embedded: >> >> print('realpath =', os.path.realpath('test_main.py')) >> >> I get the following in my test output (Only relevant line is shown): >> >> Ensure expected list of string integers is returned. ... >> realpath = c:\Projects\solitaire_scorekeeper\test_main.py > > > realpath() returns the canonical path of the given filename. It doesn't > try to locate some actual existing file. The fact that there is a file > called "test_main.py" located here: > >> In actuality "test_main.py" is located at >> "c:\Projects\solitaire_scorekeeper\tests\test_main.py" > > is irrelevent. You asked for the "real" (canonical) path name to the > relative pathname "test_main.py". That means in the current directory, > which apparently is C:\Projects\solitaire_scorekeeper. Hence you get the > result C:\Projects\solitaire_scorekeeper\test_main.py even though the > "real file" is one directory further in. After some searching I have yet to locate a definition of "canonical path" that makes sense to me. The dictionary definition of canonical does not seem to be very helpful in understanding this. Can you clarify this? What is the methodology that os.path.realpath(path) is actually following to yield a particular path name? And why does it not care if path refers to a real file or not? What I *really* want to do is locate and open a file "test_data.dat" that is in the same directory as the file with the tests, "tests/test_main.py". I asked a related question a while back but I now suspect I did not fully get everything. I have recently been experimenting with the os and os.path modules and thought I had found the magic bullet with os.path.realpath(). Anyway, based on that earlier related question and your answer tonight I have modified my test class to the following: class TestOpenFileStrIntsToList(unittest.TestCase): """Tests for the function open_file_str_ints_to_list.""" def test_open_file_str_ints_to_list(self): """Ensure expected list of string integers is returned.""" path = os.path.dirname( os.path.realpath(__file__)) + '/test_data.dat' print('realpath =', os.path.realpath(__file__)) expected_list = ['-3', '-2', '-1', '0', '1', '2', '3'] self.assertEqual(open_file_str_ints_to_list(path), expected_list) The test_data file is just the expected_list values, one value per line in the file. The function being tested is: def open_file_str_ints_to_list(path): """Given a path to the file, open this file containing one string integer per line, and convert it to a list of string integers, which is then returned by this function.""" with open(path) as infile: string_integers = [line.strip() for line in infile] return string_integers BTW, I am having trouble coming up with a good name for a string that looks like an integer that I plan on using int() later to convert the string to an integer. "String integer" is my best thought at this time. Anyway, the print() statement in the test case is giving me the correct result. Is this way of determining the directory which test_main.py is running from bullet proof? -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Why does os.path.realpath('test_main.py') give different results for unittest than for testing statement in interpreter?
Win7, Python 3.6.2 If I run a unit test with the following embedded: print('realpath =', os.path.realpath('test_main.py')) I get the following in my test output (Only relevant line is shown): Ensure expected list of string integers is returned. ... realpath = c:\Projects\solitaire_scorekeeper\test_main.py In actuality "test_main.py" is located at "c:\Projects\solitaire_scorekeeper\tests\test_main.py" If I open the interpreter from the directory "c:\Projects\solitaire_scorekeeper\tests\" I get what I expect: py3: import os.path py3: os.path.realpath('test_main.py') 'c:\\Projects\\solitaire_scorekeeper\\tests\\test_main.py' Would someone enlighten me as to why the different results? TIA! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] How to handle passwords in programs that perform FTP processes?
Python 2.4, Solaris 10. I have several programs that must transfer files from our Solaris 10-based intranet to our Windows-based intranet. They each have their own shell script to perform these file transfers, each customized for each program. Today I wrote a Python 2 program using the ftplib module that will replace all of these shell script programs and provide a standard interface for doing these transfers. It also will serve as a method for me to backup my programs on the Solaris 10-based intranet to a location on the Windows side. Even though these networks are supposed to be secure intranets where those who need to know know the generic user name and password for the FTP server, I would like to be as secure as possible with this information. How do I go about doing this? I am limited to whatever is available on the Solaris 10 operating system and it must work with Python 2.4 and its available standard libraries. I cannot use any outside software. However, I am free to write all the software I might like, assuming I can find time to do so. What would you sage Pythonistas recommend for my situation? -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Is len(a_list) a computed value or a stored attribute of a_list?
I was wondering if len(a_list) is computed on the fly or is it a stored attribute of the a_list object? And is the answer the same for both Python 2 and 3? -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Finding written and video tutorials for Python [Was: IDLE]
I am renaming this thread as it has drifted off its original subject. On Sat, Dec 30, 2017 at 9:53 AM, nelson jon kanewrote: > Thanks. What do you mean when you say "find a written tutorial"? > > > > From: Tutor on behalf of > Leam Hall > Sent: Saturday, December 30, 2017 6:39 AM > To: tutor@python.org > Subject: Re: [Tutor] IDLE > > On 12/30/2017 04:07 AM, Alan Gauld via Tutor wrote: > >> Videos are good for getting a feel for things and >> understanding concepts but IMHO they are not good >> for details. > > This is how I learn coding languages. Watch a video series for a little > bit and then find a written tutorial to work through. Getting the "big > picture" quickly helps provide a context and then digging deeply into > the actual code really helps learning. What Alan and Leam are suggesting is to use a written, non-video tutorial as your main learning tool. If you truly wish to learn to program you must write code, run it, inevitably get errors, correct the errors, get more errors, correct those, etc., until you get a finished program that does what you desire. The struggle in doing this is where the real learning occurs. It is helpful starting out to have a resource that presents the information in a logical, organized way optimized for your learning. Whatever resource you use will illustrate a topic with actual code. You should type that code in yourself and try to run it. If it works you should play around with it yourself until you are certain you fully understand that code snippet and what each piece of it does. If it doesn't run then you should debug it until it does run and then play around with it for full understanding. This interactive process of reading/watching someone else's code and then trying it out yourself is more difficult to accomplish with a video. But with a book, a written webpage, etc., it is easy to do. Alan has a web resource: http://www.alan-g.me.uk/ that you could use as a written tutorial. Use version 3 for Python 3 as that is what is current. Other resources for people without previous programming experience are given on Python's official website at: https://wiki.python.org/moin/BeginnersGuide/NonProgrammers And of course you can search for others. Do whatever you find works best for how you learn, but whatever you do, make sure you write and debug code. This is where the real learning occurs. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Code
Welcome to Tutor! We won't do your homework for you, but will help you if you get stuck. Normally you would show us your current best coding effort and we would help you from there. On Tue, Dec 19, 2017 at 6:22 PM, Vinay Raowrote: > Hi, > > We need help coding the range formula, and we don’t really know how to do it. > This is the formula, R=(V2Sin2theangle)/(g). We are trying to solve for the > angle. To get you started, I might suggest the following outline of what to do: 1) Put your range formula in proper mathematical form. Assuming your email formatting did not get mangled, you have a little bit of cleanup effort to get the formula right. Example, V is squared not V2. 2) Use your knowledge of algebra and trigonometry to solve for the angle. 3) Express this solution in Python terms, using "*" for multiplication, "/" for division, etc. Use understandable variable names. You will probably want to use the math standard library. Attempt this and if you get into trouble copy and paste both your actual code you tried to run and any error tracebacks into a plain text email and we will endeavor to help you along. HTH! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Aggregation vs Composition
I own this book, too. I'll insert the portions of the text that I believe the OP is referring to. On Sun, Dec 10, 2017 at 3:01 AM, Alan Gauld via Tutorwrote: > On 10/12/17 05:07, jia yue Kee wrote: > >> in Dusty Philips's Python 3: Object-Oriented >> Programming book. > > Caveat: I've not read this book so can only > guess at what the author might be meaning. > >> Based on my reading, what I gathered was that Composition implies a >> relationship where the child cannot exist independent of the parent while >> Aggregation, on the other hand, implies a relationship where the child can >> exist independently of the parent. The author defines composition on page 17 as: "Composition is the act of collecting together several objects to compose a new one. Composition is usually a good choice when one object is part of another object." > Correct. But the key word here is "implies". > In some languages the differences can be directly > implemented in the language but in Python the > relationships are always just implied. The differences > do not really exist. (Unless you go to inordinate > lengths to hide and link the data, which is rarely, > if ever, justified.) > >> However, in one of the paragraph of the book, *Dusty mentioned that >> composition is aggregation* On page 18 the author goes on to use a chess set as an example aiming to use object-oriented design for a computer chess game. I _think_ the OP may be referring to this paragraph: "The chess set, then, is composed of a board and thirty-two pieces. The board is further comprised of sixty-four positions. You could argue that pieces are not part of the chess set because you could replace the pieces in a chess set with a different set of pieces. While this is unlikely or impossible in a computerized version of chess, it introduces us to *aggregation*. Aggregation is almost exactly like composition. The difference is that aggregate objects can exist independently. It would be impossible for a position to be associated with a different chess board, so we say the board is composed of positions. But the pieces, which might exist independently of the chess set, are said to be in an aggregate relationship with that set." He continues in the next paragraph: "Another way to differentiate between aggregation and composition is to think about the lifespan of the object. If the composite (outside) object controls when the related (inside) objects are created and destroyed, composition is most suitable. If the related object is created independently of the composite object, or can outlast that object, an aggregate relationship makes more sense. Also keep in mind that composition is aggregation; aggregation is simply a more general form of composition. Any composite relationship is also an aggregate relationship, but not vice versa." I think it is these last two sentences that are confusing the OP. Hope this provides more context to help the OP. boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: confused about Pypi
On Sun, Oct 29, 2017 at 3:05 AM, Mark Andersonwrote: > The text is > > C:\Users\marka> python -m pip install "pyglet" > 'python' is not recognized as an internal or external command, > operable program or batch file. I'm on Windows 7, but I have found when I have not bothered to set the path to the Python installation, that using the Python launcher as follows works: py -m pip install "pyglet" Perhaps it will work for you. BTW, are the quotes around pyglet needed? I don't recall ever having to use quotes to install via pip. HTH, boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] problem with program in python in easy steps
On Thu, Oct 26, 2017 at 3:02 PM, Chris Colemanwrote: > > i wrote these programs and saved them per instructions on page 128 and 129 > in the book "python in easy steps". > > class Person: > '''A base class to define Person properties.''' > def__init__(self,name): The above line should generate an error as there is no space between "def" and "__init__". > self.name = name > def speak( self,msg = '(Calling The Base Class)'): > print(self.name,msg) > > from Person import* > '''A derived class to define Man properties.''' > class Man(Person): > def speak(self,msg): > print(self.name,':\n\tHello!',msg) > > from Person import* > '''A derived class to define Hombre properties.''' > class Hombre(Person): > def speak(self,msg): > print(self.name,':\n\tHola!',msg) > > from Man import* > from Hombre import* > guy_1 = Man('Richard') > guy_2 = Hombre('Ricardo') > guy_1.speak('It\'s a beautiful evening.\n') > guy_2.speak('Es una tarde hermosa.\n') > Person.speak(guy_1) > Person.speak(guy_2) > > i ran the program override.py and get this error message: > > Traceback (most recent call last): > File "scripts/override.py", line 1, in > from Man import* > File "/home/chris/scripts/Man.py", line 2 > '''A derived class to define Man properties.''' > ^ > IndentationError: unexpected indent So, did you try removing the indentation in front of '''A derived class ... '''? And once you do, you will get the same error later on where you did the same thing. Recall that Python uses indentation to define its code blocks. -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor