Re: [Tutor] Object creation query

2019-08-09 Thread bob gailer

On 8/9/2019 7:39 AM, Alan Gauld via Tutor wrote:

On 09/08/2019 09:54, mhysnm1...@gmail.com wrote:


updates and insertions. I have multiple tables with the same structure with
differe

I agree 100% with Peter and Alan's responses.

--
Bob Gailer

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] instantiate and name a class from / with a string

2019-08-09 Thread bob gailer

On 8/9/2019 1:55 PM, ingo wrote:

With the available classes Root, Channel and SSE I build the following
(in CherryPy):

root = Root()
root.channel = Channel()

root.channel.weather = SSE('weather')
root.channel.energy = SSE('energy')
root.channel.mail = SSE('mail')
root.channel.rss = SSE('rss')
...

http://example.com/channel/weather/ will then become the emitter of the
weather event stream.

I'd like create the instances of SSE programmatically by pulling the
string 'weather', 'energy' etc. from a database.


Are you asking for help in obtaining a value from a database?

Or how to dynamically create instances assigned to root.channel attributes?

Assuming the latter:

name = # get from data base
setattr(root.channel, name, SSE(name))

--
Bob Gailer

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Difference between decorator and inheritance

2019-08-02 Thread bob gailer

And now for something completely different...

Decorators are not required to return a function!

I use them to create a dictionary that maps function names to the 
corresponding function object.


This is very useful when associating actions with user-entered commands. 
Example:


def collect(func=None, d={}):
    if not func: return d
    d[func.__name__] = func

@collect
def add(a,b):
    return a+b

# adds item to dictionary d (key = 'add', value = func)
# repeat for other user-command functions
# finally:
cmd_dict = collect() # returns the dictionary
cmd = input('enter a command>')
func = cmd_dict.get(cmd)

--
Bob Gailer

___
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?

2019-07-30 Thread boB Stepp
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?

2019-07-30 Thread boB Stepp
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?

2019-07-30 Thread boB Stepp
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?

2019-07-30 Thread boB Stepp
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


Re: [Tutor] Stylometry Help

2019-07-20 Thread Bob Gailer
On Jul 20, 2019 7:56 AM,  wrote:
>
> Hello together,
>
> I try to write a Python tool but after hours of trying , reading and
looking for help nothing an no one would help me. So this is my most
desperate call for help. I attached the project and my required files.

Unfortunately the tutor list does not forward attachments. If the files are
not too big just include them in the body of the email. Otherwise you'll
have to store them in the cloud and give us a link.

Be sure to reply all so we all get to see your problem.

Bob gailer
___
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?

2019-07-16 Thread boB Stepp
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] pointers or references to variables or sub-sets of variables query.

2019-07-08 Thread bob gailer

Data = [

   ['2019-01-19','Fred Flintstone',23],
['2019-02-01','Scooby doo', 99]
]

Warning 3: age is not a fundamental attribute; it is a computed value!

--
Bob Gailer

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python 3.7 Grids

2019-06-29 Thread boB Stepp
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] [Python-Help] Writing hello world

2019-06-29 Thread Bob Gailer
On Jun 28, 2019 9:26 AM, "Erastus muriithi" 
wrote:
>
> Iam a student..iam interested in learning python,,I don't know how to
study this python.kindly help me how to go about it..Thankyou

First make sure you have python installed on your computer. If you need
help with that let us know what kind of computer and operating system you
are using.

At the python. Org website you will find links to tutorials. Try some of
these out.

Direct future emails to tutor@python.org.
Always reply all so a copy goes back to the list.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python 3.7 Grids

2019-06-29 Thread Bob Gailer
On Jun 29, 2019 3:01 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.

Unfortunately this list does not forward attachments. Either give us a link
to the code or even better if it's not terribly complicated paste it into
the reply. be sure to reply all so everyone on the tutor list will see your
reply.

> There are no viruses.

That's kind of like a Salesman saying "trust me".

Bob Gailer
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python

2019-06-25 Thread Bob Gailer
On Jun 25, 2019 8:52 AM, "Shaon Debnath"  wrote:
>
> I just wanted to know all about map() function in python.

See https://www.geeksforgeeks.org/python-map-function/.

If after reading that you still have questions please come back and ask
them.

Bob Gailer
___
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

2019-05-27 Thread boB Stepp
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

2019-05-12 Thread boB Stepp
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

2019-05-12 Thread boB Stepp
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

2019-05-12 Thread boB Stepp
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

2019-05-08 Thread boB Stepp
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

2019-05-08 Thread boB Stepp
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


[Tutor] Syntac Error

2019-04-24 Thread Bob Griffin
Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on 
win32
Type "copyright", "credits" or "license()" for more information.
>>> print("Game Over")
Game Over
>>>

Sent from Mail for Windows 10


Each time I write the program in Python from the book Python Programming, Third 
Edition, for the absolute beginner. When I run the program and get a syntac 
error invalid syntac that highlights the first 1 in 3.1.1 above.

When I save the program and try to run it from the app on my screen it just 
blinks and goes back to the app on my desktop.

Suggestions please.


___
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

2019-04-19 Thread boB Stepp
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

2019-03-30 Thread boB Stepp
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] How to store scores of a race's players

2019-03-26 Thread Bob Gailer
Please do not use a mangled return email address. It causes us a lot of
pain when we fail to read your address to fix it and get the message
bounced back. The only reason I'm even bothering to resend it is because I
put a lot of work into it.:
> On
> Mar 26, 2019 6:55 AM, "^Bart"  wrote:
> >
> > Hello!
> >
> > I need to store scores of three players for more than a race, after
every race the user will read "Is the competition finished?", if the
competition if finished the user will see the winner who got higest score:
> >
> Thank you for reaching out to us for help as You Learn Python. A good
mailing list to use instead of the main python list is tutor@python.org.
I'm including that list in the reply addresses; please use that address in
the future and always reply all so a copy goes to that list.
>
> This looks like a homework assignment. Be advised we won't write code for
you but we will help you when you get stuck and provide some guidance. I'm
personally curious as to who wrote that specification, since it is not well
written. One of the questions that fails to address is what if two or more
players have the same high score?
>
> It's also a little hard to guide you since we don't know what you've
already learned. One of the fundamental concepts in computer programming is
that of a loop. Since the requirements indicate there will be more than one
race that requires a loop. The simplest python construction for a loop is a
while. Within that Loop you write the code once rather than rewriting it as
you have done. I hope that is enough to get you started. Please apply that
advice as best you can and come back with a revised program.
>
> > p1 = int (input ("Insert score of the first player: "))
> > p2 = int (input ("Insert score of the second player: "))
> > p3 = int (input ("Insert score of the third player: "))
> >
> > race = str (input ("Is the competition finished?"))
> >
> > totalp1 = 0
> > totalp2 = 0
> > totalp3 = 0
> >
> > winner = 0
> >
> > if p1 > p2 and p1 > p3:
> > winner = c1
> > elif p2 > p1 and p2 > p3:
> > winner = p2
> > else:
> > winner = p3
> >
> > if "yes" in race:
> > print("The winner is:",winner)
> > else:
> > p1 = int (input ("Insert score of the first player: "))
> > p2 = int (input ("Insert score of the second player: "))
> > p3 = int (input ("Insert score of the third player: "))
> >
> > race = str (input ("Is the competition finished?"))
> >
> > You read above just my toughts, is there someone who could help me to
understand how to solve it?
> >
> > Regards.
> > ^Bart
> > --
> > https://mail.python.org/mailman/listinfo/python-list
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to store scores of a race's players

2019-03-26 Thread Bob Gailer
On Mar 26, 2019 6:55 AM, "^Bart"  wrote:
>
> Hello!
>
> I need to store scores of three players for more than a race, after every
race the user will read "Is the competition finished?", if the competition
if finished the user will see the winner who got higest score:
>
Thank you for reaching out to us for help as You Learn Python. A good
mailing list to use instead of the main python list is tutor@python.org.
I'm including that list in the reply addresses; please use that address in
the future and always reply all so a copy goes to that list.

This looks like a homework assignment. Be advised we won't write code for
you but we will help you when you get stuck and provide some guidance. I'm
personally curious as to who wrote that specification, since it is not well
written. One of the questions that fails to address is what if two or more
players have the same high score?

It's also a little hard to guide you since we don't know what you've
already learned. One of the fundamental concepts in computer programming is
that of a loop. Since the requirements indicate there will be more than one
race that requires a loop. The simplest python construction for a loop is a
while. Within that Loop you write the code once rather than rewriting it as
you have done. I hope that is enough to get you started. Please apply that
advice as best you can and come back with a revised program.

> p1 = int (input ("Insert score of the first player: "))
> p2 = int (input ("Insert score of the second player: "))
> p3 = int (input ("Insert score of the third player: "))
>
> race = str (input ("Is the competition finished?"))
>
> totalp1 = 0
> totalp2 = 0
> totalp3 = 0
>
> winner = 0
>
> if p1 > p2 and p1 > p3:
> winner = c1
> elif p2 > p1 and p2 > p3:
> winner = p2
> else:
> winner = p3
>
> if "yes" in race:
> print("The winner is:",winner)
> else:
> p1 = int (input ("Insert score of the first player: "))
> p2 = int (input ("Insert score of the second player: "))
> p3 = int (input ("Insert score of the third player: "))
>
> race = str (input ("Is the competition finished?"))
>
> You read above just my toughts, is there someone who could help me to
understand how to solve it?
>
> Regards.
> ^Bart
> --
> https://mail.python.org/mailman/listinfo/python-list
___
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]

2019-03-24 Thread boB Stepp
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"?

2019-03-24 Thread boB Stepp
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]

2019-03-24 Thread boB Stepp
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"?

2019-03-24 Thread boB Stepp
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"?

2019-03-23 Thread boB Stepp
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

2019-03-23 Thread boB Stepp
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] How to create a structure from a Log file

2019-03-11 Thread Bob Gailer
On Mar 11, 2019 2:53 AM, "Asad"  wrote:
>
> Hi All ,
>
>I think this format would be easy in a row and table format
>
> Date
> Time
> Message
> 1/21/2019
> 10:13:14.237 CET
> Method Entry. workDir=/tmp frameworkHome=/u01/app/oracle/product/
12.2.0.1/dbhome_1

For me the easiest would be to create an HTML page and display it in the
browser. You could start out with the table tag and then write each segment
of the log file into the proper column and end with a closing table tag.

I hope that's sufficient cuz I'm dictating this into my cell phone and
don't particularly want to try to actually dictate HTML or type it on a
cell phone keyboard.

Excel is also a good idea and there are several python modules dedicated to
creating Excel files. A Google search would reveal those.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to create a structure from a Log file

2019-03-10 Thread Bob Gailer
Thank you for showing us a sample of the log file. That is half the battle.
Would you now reformat a couple of the lines so that we can see how you'd
like to see them.

It also may be the case that the advice given by others will be sufficient
to guide you
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to create a structure from a Log file

2019-03-09 Thread Bob Gailer
Would you give us more information? What is an example of a log file? How
would you like to see it presented? The more information you give us the
easier it is for us to help.

On Mar 9, 2019 11:20 AM, "Asad"  wrote:

Hi All ,

   I would like to know , how can I approach this problem to create
a easy structure from the logfile using python so I can review the logfiles
quite efficiently . Please share suggestion tip or already written codes.



Thanks,
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
___
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?

2019-03-02 Thread boB Stepp
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?

2019-03-02 Thread boB Stepp
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

2019-02-27 Thread boB Stepp
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?

2019-02-27 Thread boB Stepp
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?

2019-02-27 Thread boB Stepp
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)"

2019-02-24 Thread boB Stepp
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)"

2019-02-24 Thread boB Stepp
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)"

2019-02-24 Thread boB Stepp
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)"

2019-02-24 Thread boB Stepp
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)"

2019-02-23 Thread boB Stepp
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

2019-02-13 Thread boB Stepp
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

2019-02-10 Thread boB Stepp
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

2019-02-09 Thread boB Stepp
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

2019-01-13 Thread boB Stepp
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

2018-12-31 Thread boB Stepp
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

2018-12-20 Thread boB Stepp
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] Python

2018-12-20 Thread Bob Gailer
On Dec 20, 2018 12:17 PM, "Mary Sauerland"  wrote:
>
> Hi,
>
> I want to get rid of words that are less than three characters but I keep
getting errors. I tried multiple ways but keep getting errors.

Hi Mary welcome to the tutor list. We love to help. We are a few
volunteers. It is very difficult for us to be mind readers. So please give
us more information. Especially what the error is you are getting. I
presume it is what we call a trace back. It is important that you copy the
entire traceback and paste it into the email. It will also be very helpful
if you gave us a sample of the two text files and the output You're
Expecting.

>
> Here is my code:
>
> f1_name = "/Users/marysauerland/Documents/file1.txt"
> #the opinions
> f2_name = "/Users/marysauerland/Documents/file2.txt"
> #the constitution
>
>
> def read_words(words_file):
> return [word.upper() for line in open(words_file, 'r') for word in
line.split()]
>
>
> read_words(f1_name)
> #performs the function on the file
> set1 = set(read_words(f1_name))
> #makes each word into a set and removes duplicate words
> read_words(f2_name)
> set2 = set(read_words(f2_name))
>
> count_same_words = 0
>
> for word in set1:
> if word in set2:
> count_same_words += 1
> #comparing the set1 (set of unique words in the opinions) with set2 (set
of unique words in the constitution) and adding 1 for each matching word
found which is just counting the words
> print(count_same_words)
>
>
> Best,
>
> Mary
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Extract URL

2018-12-13 Thread Bob Gailer
On Dec 13, 2018 2:01 PM, "Sammy Lee"  wrote:
>
> I need help on the problem stated below.
>
>
> Given a URL, open the webpage and return the first anchor link url (a
href).
>
>
> def extract_url_link(url):

Same comments as my other two emails.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python function

2018-12-13 Thread Bob Gailer
On Dec 13, 2018 1:55 PM, "Sammy Lee"  wrote:
>
> How do I create a python function that opens a CSV file and determines
how many columns
> of data are in the file? The CSV files have been randomly generated from
https://www.mockaroo.com/
>
> def csv_column_count(openfile):

Same comments as I made in response to your other question. What part of
this do you need help with? do need to know how to read a file? do you need
to understand what a CSV file is? do you need to know how to parse a
character string?

The more specific you are the easier it is for us to help you.

Have you ever written a Python program? What has your course taught you so
far? Do you know how to write pseudocode?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Long Lines techniques

2018-12-13 Thread Bob Gailer
On Dec 13, 2018 1:51 PM, "Avi Gross"  wrote:
>
> Simple question:

Avi: when I see an email from you I tend to ignore it because it always
seems to lead to something that is long, time consuming and complex. Would
you consider finding ways to make your questions or comments a lot briefer?

I will be more inclined to read them if they are briefer.

You have correctly determined the conditions that will lead to continuation
lines without backslash. I think we tend to use whatever is convenient.

In your example of a list comprehension over multiple lines there is no
indentation. There is just a lot of white space. You might look at it this
way: the compiler sees a left bracket with no corresponding right bracket
on that line. So it assumes that there's more to the statement on the next
line, it ignores the newline and just continues. Indentation is only
significant if it starts at the beginning of a statement.

Hope this helps

Bob gailer
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Open webpage and save CSV

2018-12-13 Thread Bob Gailer
On Dec 13, 2018 1:51 PM, "Sammy Lee"  wrote:
>
> I need help on the problem below,

Could you be more specific? What kind of help do you need? Have you made
any attempt to write a program?

We are happy to help but we're not going to do all the work for you. So
tell us what you do know about the various aspects of this problem.

My personal guess is that this is a homework assignment. If that's the case
the class should have given you some of the information (ideally all the
information) you need to solve the problem.

Also please tell us what operating system you're using and what version of
python.

You will need the services of the urllib. request module to get the
contents of a web page.

So start with that.

> Given a URL, open the webpage and save the CSV to a given file path.
>
>
> def save_url_to_csv_file(url, savefile):

Bob Gailer
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I need help with my project

2018-11-28 Thread Bob Gailer
On Nov 28, 2018 3:43 AM, "Treyton Hendrix" <2hendri...@stu.bps-ok.org>
wrote:
>
> If the user selected a sandwich, french fries, and a beverage, reduce the
> total cost of the order by $1.00.
>
> This is what I have to do and I don't know where to start.

You start by learning how to ask effective questions. Example:

I am taking python 101 at Fubar University. I have been given the following
assignment:

Here you tell us the entire assignment not just one sentence from it.

Then you show us whatever attempt you have made to solve the problem. Have
you written any Python program? Show us the program. Tell us where you are
stuck.

We really like to help but we do not have any crystal balls to look into.
Help us understand your situation fully.

Bob Gailer
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] seeking beginners tutorial for async

2018-11-19 Thread Bob Gailer
> Can you be more specific what you're looking for?

For starters a minimal executable  program that uses the async keyword.

On the JavaScript side this is trivial and easily understood.

I did find in the python documentation a hello world program that uses
async IO. It helped me understand how to build an event Loop , start soon,
start later stop Loop, run forever and run until complete. That was very
helpful. But it did not introduce async.

I'd like to see  the trivial program built up step-by-step adding one new
feature at a time so that I can understand exactly what that feature does.

I am talking about python 3.6 and 3.7.

Thank you for asking for the clarification, I hope this helps.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] seeking beginners tutorial for async

2018-11-18 Thread bob gailer

I have yet to find a tutorial that helps me understand and apply async!

The ones I have found are either incomplete, or they wrap some other 
service, or they are immediately so complex that I have no hope of 
understanding them.


I did find a useful javascript tutorial at 
https://javascript.info/promise-basics, but trying to map it to python 
is very frustrating.


The python docs also do not help.

Can you point me to any resources that are actually useful to a beginner?

Bob Gailer

guru of many languages including Python ( up till now!)

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to print lines which contain matching words or strings

2018-11-18 Thread Bob Gailer
On Nov 18, 2018 1:19 PM, "Bob Gailer"  wrote:
>
> On Nov 18, 2018 12:14 PM, "Asad"  wrote:
> >
> > Hi All ,
> >
> >I have a set of words and strings :
> >
> > like :
> >
> > p = [A ,"B is good" ,123456 , "C "]
> >
> > I have a file in which I need to print only the lines which matches the
> > pattern in p
> >
> > thanks,

Terminology is very important. You say set then you show us a list.

You say words and strings, but your list contains a python identifier and a
number in addition to Strings.

You say pattern but don't Define what you mean by pattern. I could not
begin to guess what your definition of pattern is.

We also do not know what the term word means to you. You may say that is
obvious but it is not. So tell us your meaning of word.

To make the question meaningful I would suggest you show us sample of the
file indicating lines that meet the pattern and lines that don't.

Please realize that we are not here to write code for you, rather we like
to help you when we see you put in some effort. So I suggest you write a
Python program that attempts to do what you want, then tell us where the
program isn't doing what you want or where you are stuck will try to help.

Please respond in some way so that we know you have heard us.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to print lines which contain matching words or strings

2018-11-18 Thread Bob Gailer
On Nov 18, 2018 12:14 PM, "Asad"  wrote:
>
> Hi All ,
>
>I have a set of words and strings :
>
> like :
>
> p = [A ,"B is good" ,123456 , "C "]
>
> I have a file in which I need to print only the lines which matches the
> pattern in p
>
> thanks,

you are welcome, but I'm not sure what you're thanking us for. I don't see
any kind of request in your email.

There are various resources on how to ask effective questions. You might
try Googling that topic.

I have more that I will say later.

Bob Gailer
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Require Python assistance

2018-11-09 Thread Bob Gailer
On Nov 9, 2018 12:34 PM, "TCY via Tutor"  wrote:
>
>
>
>
> Dear
> May I know how to solve the cryptography with Python programming
language as below -
> (1) Implement Elgamal Method(2) Implement Elliptic Curve Cryptography
method(3) Implement Rabin Method(4) Implement RSA Method
> Find (a) Prime test (b) Inverse function

This list does not send attachments. If the file is not large just send it
as part of the email body.

As you can see the text above came thru as 1 long line. I presume  when you
sent it it looked like 4 lines. If that is the case you need to send the
email as plain text rather than some fancy formatted way.

> Please help me by provide your advice

Learn how to ask questions that are more precise and specific. "Solve the
cryptography" doesn't tell me anything. The more clearly you state your
objectives the easier it becomes for us to help you.

Google is your friend here. For example try searching Google for "Elliptic
Curve Cryptography python"
and suggestion so that I can improve my computing skills (please see the
attached file)

Bob Gailer
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Request for help with code

2018-11-06 Thread Bob Gailer
On Nov 6, 2018 4:51 PM, "Joseph Gulizia"  wrote:
>
> I'm using the bookazine  "The Python Book" First Edition on pages 13-14 it
> gives the code (listed further below).
>
> It asks for user to state a given number of integers (for example
4)...then
> user enters integers.  It doesn't stop seeking input after the number
> requested thereby creating an infinite loop.
>
> -
> CODE
> -
>
> # Python Book Page_13.py
> # Joe G.
>
> # several comment lines explain the code below it.
> # Re-typing is good practice
>
> # We're going to write a program that will ask the user to input an
> arbitrary
> # number of intergers, store them in a collection, and then demonstrate
how
> the
> # collection would be used in various control structures.
>
> # Used for the sys.exit function
> import sys
> # Requests number of intergers
> target_int=raw_input("How many intergers?")
> # By now, the variable target_int contains a string representtion of
> # whatever the user typed.  We need to try and convert that to an interger
> but
> # be ready to # deal with the error if it's not.  Otherwise the program
will
> # crash
> # Begin the error check
> try:
> target_int=int(target_int)
> except ValueError:
> sys.exit("You must enter an interger")
> # creates a collection (list) called ints
> ints=list()
> # keeps track of number of intergers
> count=0
> # Keep asking for an interger until we have the required number
> while count new_int=raw_input("Please enter interger{0}:".format(count+1))
> isint=False
> try:
> new_int=int(new_int)
> except:
> print("You must enter an interger")
> # Only carry on if we have an interger.  If not, we'll loop again
> # Notice below I use == which is different from =.  The single equals sign
> is an
> # assignment operator whereas the double equals sign is a comparison
> operator. I would
> # call it a married eguals signbut whenever single is mentioned I have
> to mention marriage.
>
> if isint==True:
> # Add the interger to the collection
> ints.append(new_int)
> # Increment the count by 1
> count+=1
> # print statement ("using a for loop")
> print("Using a for loop")
> for value in ints:
> print(str(value))
> # Or with a while loop:
> print("Using a while loop")
> # We already have the total above, but knowing the len function is very
> # useful.
> total = len(ints)
> count = 0
> while count < total:
>print(str(ints[count]))
>count +=1
>
> count = 0
> while count < total:
> print(str(ints[count]))
> count += 1
>
> ---
> END OF CODE
> ---
> Sample output:
>
> How many integers?3
> Please enter integer1:1
> Please enter integer1:2
> Please enter integer1:3
> Please enter integer1:a
> You must enter an integer
> Please enter integer1:4
> Please enter integer1:5
> Please enter integer1:6
> Please enter integer1:b
> You must enter an integer
> Please enter integer1:
> (Keeps Looping)
>
> Thanks in advance

Your code came through with all of the indentation removed. Please be sure
to send plain text. We could guess at the indentation but we might get it
wrong.

With the indentation corrected the code you supplied does not agree with
the execution. Note the difference between integer and interger.

You also did not make any request. Please in the future tell us what you
want from us.

The fact that the program keeps asking for integer 1 suggest that count is
not being incremented. This would also explain why the loop never ends.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] (no subject)

2018-10-27 Thread Bob Gailer
On Oct 27, 2018 7: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 here are the specs of the pattern and my code so far can you please
help

Thank you for asking for help. It would help us if you were more specific.
"Can't get it to work" doesn't tell us much.

Does the program run or do you get an error?

If you get an error, also known as a traceback, copy the entire traceback
and paste it into your reply.

Otherwise show us your input and output. Tell us where it differs from what
you expected. Again use copy and paste to show your results.
>
> • 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()
>
>
> please help me
> thank you
> kind regards
> Tarantulam
>
>
> Sent from Mail for Windows 10
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] (no subject)

2018-10-27 Thread boB Stepp
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] Python Help

2018-10-26 Thread Bob Gailer
On Oct 26, 2018 1:20 PM, "Adam Eyring"  wrote:
>
> Try this cleaned up version with colons in the right places, dollar signs
removed, and other corrections:

Does it do what you want?

> beefmeals=int(input("Enter number of beef meals: "))
> shitmeals=int(input("Enter number of vegan meals: "))
> party = beefmeals + shitmeals
> print("Total meals", party)
> a = 0
> b = 0
> c = 0

There is no need for three variables here. You only need one to represent
room cost. If you make that change then you will also not need to
initialize the room cost variable. Makes the code simpler to maintain and
read and understand.

> if party <= 50:
>
> a=75
> print("Room cost $75")

If you use one variable for room cost then you can use just one print just
above the room tax line.

> elif party <= 150:
>
> b=150
> print("Room cost $150")
> else:
> c=250
> print("Room cost $250")
> roomtax = party * 0.065
> print("Room tx", roomtax)
> print("Beef Meals", beefmeals)
> beef = (beefmeals * 15.95)
> print("Beef cost", beef)
> print("Vegan Meals", shitmeals)
> shit = (shitmeals * 10.95)
> print("Vegan cost", shit)
> cost=(beef + shit)
> grat= cost * 0.18
> print("Gratuity", grat)
> GT = print("Grand total", grat + beef + shit + a + b + c)

The print function always returns None. Therefore the effect of this
statement is to assign None to GT. Also note that you don't use GT later on.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Help

2018-10-26 Thread Bob Gailer
On Oct 26, 2018 6:11 AM, "Ben Placella"  wrote:
>
> I need to write code that runs a  cost calculating program with many
> different variables and I honestly don't understand it

Could you be more specific? What exactly don't you understand, or even
better what do you understand?

my code is:

How could you have written so much code without understanding it?

> beefmeals=int(input("Enter number of beef meals: "))
> shitmeals=int(input("Enter number of vegan meals: "))
> party=beefmeals+shitmeals
> print(party)
> if party<=50

Something is missing from that last statement. Can you tell what it is? Do
you know how to find out? Hint use help.

Hint 2 it is also missing from the elif and else statements.

> a=75
> print("Room cost $75")
> elif party <=150
> b=150
> print("Room cost $150")
> else
> c=250
> print("Room cost $250")
> roomtax=party*0.065
> print(roomtax)
> print("Beef Meals", beefmeals)
> $beef=(beefmeals*15.95)
> print($beef)
> print("Beef cost", $$beef)
> print("Vegan Meals", shitmeals)
> $shit=(shitmeals*10.95)
> print($shit)
> cost=($beef+$shit)
> grat=cost*0.18)
> print(grat)
> GT=(grat+$beef+$shit+(a,b,c))

There is a convention in Python that and all uppercase name is a constant.
This is not a requirement.

> print(GT)
>
> This is what the output is supposed to be:

I don't see any output here. Alan''s responses may help you figure that out.
___
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?

2018-10-22 Thread boB Stepp
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?

2018-10-22 Thread boB Stepp
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?

2018-10-22 Thread boB Stepp
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?

2018-10-21 Thread boB Stepp
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?

2018-10-21 Thread boB Stepp
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?

2018-10-20 Thread boB Stepp
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?

2018-10-20 Thread boB Stepp
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?

2018-10-20 Thread boB Stepp
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?

2018-10-20 Thread boB Stepp
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] python game error

2018-10-14 Thread bob gailer

More comments on code:
 guess = raw_input("[pod #]> ")
    if int(guess) != good_pod:
If user enters something that will not convert to integer an exception 
will be raised. For example

>>> int('a')
Traceback (most recent call last):
  File "", line 1, in 
ValueError: invalid literal for int() with base 10: 'a'

Either use try - except
- or
    good_pod = str(randint(1,5))
    guess = raw_input("[pod #]> ")
    if guess != good_pod:
- or if you import choice from random
    good_pod = choice('12345')

Migrating to a database (separating data from logic). Why?
- it keeps the code simple.
- makes adding / editing scenes easier.

Given a database (game.db) with 2 tables:
            table            columns
    scene_entry        scene, text, prompt
    scene_action       scene, action, text, next_scene

Example:
 CentralCorridor, The Gothons of Planet Percal #25 have invaded 
..., Do you shoot!, dodge!, or tell a joke?
 CentralCorridor, shoot!, Quick on the draw you yank out your 
, Death
 CentralCorridor, dodge!, Like a world class boxer you dodge 
, Death
 CentralCorridor, tell a joke!, Lucky for you they made 
you,, Laser_weapon_armory


The generic structure of a game program:
    next_scene = 'CentralCorridor'
    while next_scene != 'Finished':
        get text, prompt from scene_entry
        print entry text
        prompt user for action
        get text, next_scene from scene_action
        print text

A simple python game program utilizing the game database follows. You 
would first create c:/games/game.db
using a tool like SQLite Studio, or request a copy from me. It is up to 
you to fill in the rest of the various table rows.
What's missing? Code to handle the code and good_pod guesses. That will 
come later.


-- program --
import sqlite3 as sq

def sel(cols, rest, vals=(,)):
    # construct, execute a sql select statement from the arguments
    # get and return one row (there should be at most one)
    sql = "select " + cols + " from " + rest + ";"
    curs = conn.execute(sql, vals)
    x = curs.fetchone()
    if x: return x
    raise ValueError(sql, vals)

def game(next_scene):
    while next_scene != 'finished':
    text, prompt = sel("text, prompt", "scene_entry where scene = 
?", (next_scene,))

    print(text)
    action = input(prompt + '>') # tell a joke!
    text, next_scene = sel("text, next_scene", "scene_action where 
scene = ? and action= ?", (next_scene, action))

    print(text)

conn = sq.connect("c:/games/game.db")
game('CentralCorridor')
-- end program --


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python game error

2018-10-14 Thread bob gailer

On 10/14/2018 1:42 PM, Mats Wichmann wrote:

Hint here: don't use 'map' as your own variable name, since it's a
built-in function.
Absolutely, I am always warning others about this gotcha. In this case 
map is local to add_to_map so it does not affect then global namespace.


The reason I used it here was because the OP was using map (actually 
Map). Duh!


Bob
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python game error

2018-10-14 Thread bob gailer

More comments:

 User Friendly? 
I hope this game is not intended for actual use. No one will be able to 
guess the correct actions in a reasonable time. or 3 digit random code 
given 10 tries for any one code. I for one would give up pretty quickly.


The original colossal cave game is an excellent example of a 
user-friendly text adventure game. If you are using a Windows computer 
you can get a version from the Microsoft Store


It
- gives explicit directions
- keeps responses to a few words most chosen from a limited list or 
names of visible objects.


 Python coding "trick"1  
when I build a map I omit the () after the class e.g. 'death' = Death, 
... and apply them to the item retrieved from the map.


use a decorator to build the map dictionary:

# the decorator function:
def add_to_map(cls, map={}): # map is initialized to a {} when function 
is "compiled"

    if cls:
        map[cls.__name__] = cls # add entry to dictionary
        return cls
    else: return map

# apply decorator to class definitions
# this will add 'Death': 
@add_to_map
class Death(Scene):
    class_definition

 # ditto for all other classes based on Scene - then

class Map:
    scenes  = add_to_map() # note when map is called with no arguments 
it returns the dictionary


 Python coding "trick" 2 
instead of:     print(Death.quips[randint(0, len(self.quips)-1)])
try:                 print(random.choice(Death.quips)

 Python coding "trick" 3 
action = raw_input('>').title() # to make user input agree with class names

 Python coding "trick" 4 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python game error

2018-10-14 Thread bob gailer

On 10/13/2018 4:25 AM, Mariam Haji wrote:
...
Your problem intrigued me enough to spend some time "fixing" your 
program so it will compile with no errors and run at least the initial 
case where I entered "shoot!"


Here are the problems I found: (line numbers refer to your original code)
- spelling error  return 'laser_weapon_armoury' - fixed
- line 122 there is no if preceding the elif - I added one
- line 160 returns 'finished'. There is no corresponding entry in Map.scenes
   - I added one and a corresponding class Finished.
- the logic for allowing 10 guesses of the code is flawed. It only 
allows 2 guesses.

  I will leave it up to you to figure out why.

In addition I
- used """ for all multi  line prints; a personal preference - it makes 
entry and reading easier.

- updated code so it will run under python 3. This involves:
  - changing print statements to print function calls
  - assigning input to raw_input for version 3
- added raise to Map.next_scene to handle undefined scenes

Try it out.

> how do I create a keyword to exit the game mid way?

You don't create keywords. To support mid-game exiting I added an abort 
method to Finished. Use:

Finished.abort('reason')

-- program --
from sys import exit, version
from random import randint
if versison[0] == '3':
    raw_input = input

class Scene(object):
    def enter(self):
    print("This scene is not yet configured. Subclass it and 
implement enter().")

    exit(1)

class Engine(object):

    def __init__(self, scene_map):
    self.scene_map = scene_map

    def play(self):
    current_scene = self.scene_map.opening_scene()
    while True:
    print("\n")
    next_scene_name = current_scene.enter()
    current_scene = self.scene_map.next_scene(next_scene_name)

class Death(Scene):

    quips = [
"You died. You Kinda suck at this.",
"Your mum would be proud if she were smarter.",
"Such a looser.",
"I have a small puppy that's better at this."
]

    def enter(self):
    print(Death.quips[randint(0, len(self.quips)-1)])
    exit(1)

class CentralCorridor(Scene):

    def enter(self):
    print("""The Gothons of Planet Percal #25 have invaded your 
ship and destroyed

Your entire crew, you are the only surviving memeber and your last
Mission is to get the neutron destruct a bomb from the weapons Armory
Put it in the bridge and blow the ship up after getting into an
escape pod

You're running down the central corridor to the Weapons Armory when
a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clow costume
flowing around his hate filled body. He's blocking the door to the
Armoury and about to pull a weapon to blast you.
Do you shoot!, dodge!, or tell a joke? enter below.""")
    action = raw_input("> ")
    if action == "shoot!":
    print("""Quick on the draw you yank out your blaster and 
fire it at the Gothon.

His clown costume is flowing and moving around his body, which throws
off your aim. Your laser hits his costume but misses him entirely. This
completely ruins his brand new costume his mother bought him, which
makes him fly into a rage and blast ou repeatedly in the face until
you are dead. Then he eats you""")
    return 'death'
    elif action == "dodge!":
    print("""Like a world class boxer you dodge, weave, slip 
and slide right

as the Gothon's blaster cranks a laser past your head
In the middle of your artful dodge your foot slips and you
bang your head on the metal wall and you pass out
You wake up shortly after, only to die as the Gothon stomps on
your head and eats you""")
    return 'death'
    elif action == "tell a joke":
    print("""Lucky for you they made you learn Gothon insults 
in the academy

you tell the one Gothon joke you know
Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq 
gur ubhfr.

The Gothon stops, tries not to laugh, he busts out laughing and can't move.
While he is laughing you run up and shoot him square in the head
putting him down, then jump through the Weapon Armory door.""")
    return 'laser_weapon_armory'
    else:
    print("DOES NOT COMPUTE!")
    return 'central_corridor'

class LaserWeaponArmory(Scene):

    def enter(self):
    print("""You do a drive roll into the weapon Armory, crouch and 
scan the room

for more Gothons that might be hiding. It's dead quiet, too quiet
You stand up and run to the far side of the room and find the
neutron bomb in it's container. There's a keypad lock on the box
Wrong 10 times then the lock closes forever and you can't
get the bomb. The code is 3 digits""")
    code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
    guess = raw_input("[keypad]> ")
    guesses = 0
    while guess != code and guesses < 10:
    print("BZZZEE!")
    guesses += 1
    guess = raw_input("[keypad]> ")
    if guess == 

Re: [Tutor] python game error

2018-10-13 Thread Bob Gailer
suggestions:
1-Use triple-quoted strings:
  print """take the
short-cut!""'

2 - make the program much simpler to start with. The usual approach to
developing programs like this is to start simple get the simple things
working right then add more complicated scene descriptions.

Even better: separate data from logic. Create a sqlite database in which
you store the information about the various scenes. Then write a program
that does nothing but access the various database elements. This will
result in much much easier to read and maintain code, and much much easier
to read and maintain the description of the scenes. I realize this may
sound like a big chunk but it is well worth the effort to learn how to do
it.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Advanced python recommendations

2018-10-10 Thread boB Stepp
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

2018-10-09 Thread boB Stepp
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


Re: [Tutor] Python programming help!

2018-09-23 Thread Bob Gailer
On Sep 23, 2018 3:33 AM, "V E G E T A L" 
wrote:
>
> Hello folks! So, I'm pretty much a noob still experimenting with basic
> commands. I wanted to make a code that checks if the value of one variable
> is less, equal or greater than the other. Pretty simple right? But then,

> this problem emerged.

What problem? I don't see any problem here. If you provided an attachment
this email list does not forward attachments.

The proper way is to copy and paste directly into the body of the email.

If you did not attempt to show us the problem, why? You certainly can't
expect us to read your mind.

I would really love some help, since I'm stuck and
> can't figure out what I've done wrong.
>
> PS: I'm using Anaconda and JupyterNotebook.
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
___
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?

2018-08-29 Thread boB Stepp
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

2018-08-28 Thread boB Stepp
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?

2018-08-27 Thread boB Stepp
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?

2018-08-26 Thread boB Stepp
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?

2018-08-26 Thread boB Stepp
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?

2018-08-26 Thread boB Stepp
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

2018-08-08 Thread boB Stepp
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

2018-08-08 Thread boB Stepp
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

2018-07-27 Thread boB Stepp
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

2018-07-26 Thread boB Stepp
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

2018-07-15 Thread boB Stepp
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

2018-07-15 Thread boB Stepp
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

2018-07-15 Thread boB Stepp
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

2018-07-15 Thread boB Stepp
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

2018-07-14 Thread boB Stepp
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

2018-07-14 Thread boB Stepp
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

2018-07-14 Thread boB Stepp
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


  1   2   3   4   5   6   7   8   9   10   >