I think I found 2 undocumented string format codes.

2011-08-24 Thread Bill
My google-fu has failed me in finding info on %h and %l string
formatting codes.

>>> '%h' %'hello'
exceptions.ValueError: incomplete format

>>> '%l' %'hello'
exceptions.ValueError: incomplete format

Does anyone know what doing a "complete format" means?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: CodeAcademy Python Tip Calculator

2017-09-10 Thread Bill

Cai Gengyang wrote:

So, I’m on section (3. The Tip) …

Instructions

1.
Set the variable tip to decimal value of 15% on line 5.

This was my input:
You’re almost there! Assign the tip variable on line 5.
meal = 44.50
tax = 6.75 / 100
tip = 15.0

But, when I tried to run the program, I don’t get any output at all. Nada, 
nothing zilch. Nothing happens, how come ?


Not a big enough tip?  You must be running the program as a script if no 
output is being printed to the screen.

--
https://mail.python.org/mailman/listinfo/python-list


Re: version of Python to install Windows 7 professional 64 bit, intel core i5

2017-09-11 Thread Bill

Zubair Shaikh wrote:

  What version of Python to install Windows 7 professional 64 bit, intel core i5



You're joking, right?  What is your budget?
--
https://mail.python.org/mailman/listinfo/python-list


Re: The Incredible Growth of Python (stackoverflow.blog)

2017-09-13 Thread Bill

Paul Rubin wrote:

Ben Finney  writes:

I've never seen one.

who has told you... they are working on a Python 3 code base.

Just because they've told me about it doesn't mean I saw it personally.
The ones I've seen, including new ones, are Python 2.

Some people here use Py3 but I haven't heard (or don't remember) enough
about what they're working on, to know if those are py3 codebases of any
size.  If they say yes, I'll take their word for it, but this is a
self-selected group of course.


That simply isn't true, unless you think it more likely everyone who
discusses their Python 3 code base is lying.

People discuss Python language issues here a lot, but don't discuss as
much about code bases.

I know when I install a new OS (currently Debian 9 which was released
a month or so ago) and type "python" on the command line, I get Py2.


Try typing python3.  It's in some distributions of Linux.
--
https://mail.python.org/mailman/listinfo/python-list


Re: the core values of the Python "platform"

2017-09-14 Thread Bill

Steven D'Aprano wrote:

On Wed, 13 Sep 2017 09:08:41 -0400, Darin Gordon wrote:


Bryan Cantrill gave an interesting talk recently at a Node conference
about "platform values" [1].

For those of us who don't have the time or inclination to watch a video,
or who are unable to, could you summarise these platform values?



The talk lead me to think about what the
core values of the Python "platform" are and I thought it would be good
to ask this question of the community. What would you consider the top
(<= 5) core values?


In no particular order:

- The Zen of Python ("import this" at the interactive interpreter).

- "We're all adults here." We tend to be more relaxed about theoretical
errors, and push some of the responsibility for defensive programming
onto the caller, not just the callee. If the caller breaks my function's
contract by providing bad arguments, or messes with my class' internals,
they deserve whatever bad things happen.

- "We're all adults here." The flip side of that is that if I choose to
mess with your private methods or functions, you shouldn't take
extraordinary steps to try to prevent me. I'm an adult, and if I've got
good reason to call your private method (say, I'm debugging, or I'm
simply exploring the capabilities at the interactive interpreter) then I
should be allowed. If I want to shoot myself in the foot, it isn't your
responsibility to prevent me.

- All else being equal, it is better to ask forgiveness than permission.
In general, we prefer try...except and catching exceptions than to look
before you leap. It is often faster, but more importantly, it avoids
"Time Of Check To Time Of Use" bugs.

- Python is in one sense a pure Object Oriented language (all values,
even integers, are objects)


Even classes are objects.



  but in another sense Python is a multiparadigm
language. Not everything needs to be a class. Top-level functions are
often better. We can, and do, write code using four of the big five
programming paradigms: procedural, OOP, functional, imperative. And mix
and match them within a single code base.

(Only deductive/logic programming has little support in Python.)


And if I may be allowed a sixth:

- Not every two line function needs to be a built-in.





--
https://mail.python.org/mailman/listinfo/python-list


Re: String to Dictionary conversion in python

2017-09-14 Thread Bill

santosh.yelamar...@gmail.com wrote:

Hi,

Can anyone help me in the below issue.

I need to convert string to dictionary

string = " 'msisdn': '7382432382', 'action': 'select', 'sessionId': '123', 
'recipient': '7382432382', 'language': 'english'"

Can anyone help me with the code


I'm new to Python too, but it looks like you need to "split" it about 
the commas. Right?

--
https://mail.python.org/mailman/listinfo/python-list


Re: [Tutor] beginning to code

2017-09-19 Thread Bill

Rick Johnson wrote:

I think for most languages an intuitive syntax is not
important -- C is such a language, Lisp is such a language,
Perl is such a language, and there are many more -- but
for Python, intuitiveness is very important.

I guess it depends on what you mean by "important" ("important to the 
compiler", is a legitimate concern, for instance). From an intuition 
perspective, C++ allowing you to separate the interface of a class from 
it's implementation, I would say that C++ has it all over Python from 
the point of view of "intuitiveness".   It's much easier to tell what's 
going on, at a glance, in a C++ program. I am much newer to Python, but 
I have provided at least one concrete feature supporting my opinion. By 
the way, I am not talking about "toy" programs.

--
https://mail.python.org/mailman/listinfo/python-list


Re: How do I check all variables returned buy the functions exists

2017-09-20 Thread Bill

Robin Becker wrote:

On 16/09/2017 01:58, Steve D'Aprano wrote:



If you want to test for None specifically:

if any(v is None for v in values):
 print "at least one value was None"


...

for some reason that seems slow on my machine when compared with

if None in values:
   .


This does not seem particularly surprising.  "None in values" is known 
as soon as None is found.
In "any(v is None for v in values)",  "any" probably isn't called until 
its argument is (fully) known.  Of course the results would depend on 
the implementation.  It would be interesting to compare the results if 
you used the optimize option (it's either -o or -O).


Bill



C:\usr\share\robin\pythonDoc>python -m timeit -s"values=(1,2,None)" 
"any(v is None for v in values)"

100 loops, best of 3: 0.62 usec per loop

C:\usr\share\robin\pythonDoc>python -m timeit 
-s"values=(None,2,None)" "any(v is None for v in values)"

100 loops, best of 3: 0.504 usec per loop

C:\usr\share\robin\pythonDoc>python -m timeit 
-s"values=(None,2,None)" "None in values"

1000 loops, best of 3: 0.0309 usec per loop

C:\usr\share\robin\pythonDoc>python -m timeit -s"values=(1,2,None)" 
"None in values"

1000 loops, best of 3: 0.097 usec per loop


it also seems a bit less obvious


--
https://mail.python.org/mailman/listinfo/python-list


Re: How do I check all variables returned buy the functions exists

2017-09-20 Thread Bill

Steve D'Aprano wrote:



In "any(v is None for v in values)",  "any" probably isn't called until
its argument is (fully) known.

No, its a generator expression, so it provides the values one at a time, as
needed.


Okay, thank you for setting me straight.  I'm only about 2 weeks down 
this road so far!  :  )

--
https://mail.python.org/mailman/listinfo/python-list


Re: Fwd: Issues with python commands in windows powershell

2017-09-20 Thread Bill

Joey Steward wrote:

-- Forwarded message --
From: Joey Steward 
Date: Tue, Sep 19, 2017 at 10:30 PM
Subject: Issues with python commands in windows powershell
To: python-list@python.org


Hello,

I've been having issues using basic python commands in windows powershell.


Did you try the same ones in an environment besides powershell?


--
https://mail.python.org/mailman/listinfo/python-list


Re: errors with json.loads

2017-09-20 Thread Bill

Interesting problem, John.

I have probably even less experience with json than you do, so I'm 
taking this as an opportunity to learn with you.


Suggestions:

1. Try your example with Python 2 rather than Python 3.
2. Take your file and make it into a string literal in your program, and 
try calling json.loads with that as an argument.


Share with us what happens!

Good luck,
Bill


john polo wrote:

Greetings,

I am using IPython 6.1.0 with Python 3.6.2 on a Windows 7 machine. I 
am not a programmer. I am using a book called Python Data Analytics to 
try to learn some of Python. I am at a section for reading and writing 
JSON data. The example JSON file is:



Listing 5-13.  books.json
[{"writer": "Mark Ross",
 "nationality": "USA",
 "books": [
 {"title": "XML Cookbook", "price": 23.56},
 {"title": "Python Fundamentals", "price": 50.70},
 {"title": "The NumPy library", "price": 12.30}
 ]
},
{"writer": "Barbara Bracket",
 "nationality": "UK",
 "books": [
 {"title": "Java Enterprise", "price": 28.60},
 {"title": "HTML5", "price": 31.35},
 {"title": "Python for Dummies", "price": 28.00}
 ]
}]

and the example code for reading the file is:

>>> file = open('books.json','r')
>>> text = file.read()
>>> text = json.loads(text)

When I use those 3 lines, I get the following:

JSONDecodeError   Traceback (most recent call 
last)

 in ()
> 1 text = json.loads(text)

c:\users\..\python\python36\lib\json\__init__.py in loads(s, encoding, 
cls, object_hook, parse_float, parse_int, parse_constant, 
object_pairs_hook, **kw)

352 parse_int is None and parse_float is None and
353 parse_constant is None and object_pairs_hook is 
None and not kw):

--> 354 return _default_decoder.decode(s)
355 if cls is None:
356 cls = JSONDecoder

c:\users\..\python\python36\lib\json\decoder.py in decode(self, s, _w)
337
338 """
--> 339 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
340 end = _w(s, end).end()
341 if end != len(s):

c:\users\..\python\python36\lib\json\decoder.py in raw_decode(self, s, 
idx)

353 """
354 try:
--> 355 obj, end = self.scan_once(s, idx)
356 except StopIteration as err:
357 raise JSONDecodeError("Expecting value", s, 
err.value) from None


JSONDecodeError: Expecting ':' delimiter: line 5 column 50 (char 161)

?json.loads says that the method is for deserializing "s", with "s" 
being a string, bytes, or bytearray.


In [24]: type(text)
Out[24]: str

So "text" seems to be a string. Why does json.loads return an error?


John



--
https://mail.python.org/mailman/listinfo/python-list


Re: errors with json.loads

2017-09-20 Thread Bill

john polo wrote:

Greetings,

I am using IPython 6.1.0 with Python 3.6.2 on a Windows 7 machine. I 
am not a programmer. I am using a book called Python Data Analytics to 
try to learn some of Python. I am at a section for reading and writing 
JSON data. The example JSON file is:



Listing 5-13.  books.json
[{"writer": "Mark Ross",
 "nationality": "USA",
 "books": [
 {"title": "XML Cookbook", "price": 23.56},
 {"title": "Python Fundamentals", "price": 50.70},
 {"title": "The NumPy library", "price": 12.30}
 ]
},
{"writer": "Barbara Bracket",
 "nationality": "UK",
 "books": [
 {"title": "Java Enterprise", "price": 28.60},
 {"title": "HTML5", "price": 31.35},
 {"title": "Python for Dummies", "price": 28.00}
 ]
}]

and the example code for reading the file is:

>>> file = open('books.json','r')
>>> text = file.read()
>>> text = json.loads(text)


Hmm... are you sure you want "text" on the left hand side.  I'm not sure 
whether this is okay or not.  It looks suspicious (but, like I said, I'm 
a Python newbie).


--
https://mail.python.org/mailman/listinfo/python-list


Re: errors with json.loads

2017-09-20 Thread Bill

Stefan Ram wrote:

Dennis Lee Bieber  writes:

After removing all the \xa0 bytes
and trying to decode it I get...


Apparenty an \xa0 byte corresponds to a "non-breaking space". What sort 
of white space characters are allowed in a json file ( tabs and 
newlines?)?  Just curious.


Bill


   I did the same here, before I read your post.
   I got the same results, but did not post them.

   Someone has posted programs with \xA0 (NBSP IIRC)
   at the start of lines of the soure here before, in:

From: Christopher Reimer 
Newsgroups: comp.lang.python
Subject: Setting property for current class from property in an different 
class...
Date: Wed, 6 Sep 2017 19:24:40 -0700
Message-ID: 

   , and when I removed them, I was able to execute the
   source from his post from 2017-Sep-06 without errors.

   So I was feeling to lazy to bother this time.



--
https://mail.python.org/mailman/listinfo/python-list


Re: errors with json.loads

2017-09-20 Thread Bill

Ned Batchelder wrote:


On 9/20/17 8:22 PM, Bill wrote:
Apparenty an \xa0 byte corresponds to a "non-breaking space". What 
sort of white space characters are allowed in a json file ( tabs and 
newlines?)?  Just curious. 


These things can be looked up.  From RFC 7159 
(https://tools.ietf.org/html/rfc7159):




Thank you.  So what is most likely the root cause of the original 
poster's problem (assuming he typed out the text with a text editor)?

--
https://mail.python.org/mailman/listinfo/python-list


Re: [Tutor] beginning to code

2017-09-21 Thread Bill

Stefan Ram wrote:

bartc  writes:

On 20/09/2017 02:31, Bill wrote:

it's implementation, I would say that C++ has it all over Python from
the point of view of "intuitiveness".  It's much easier to tell what's
going on, at a glance, in a C++ program.

You're being serious, aren't you?

   For one example, this is a part of a C++ program:

template< typename C >C T( void ( C::* )() );

   . It defines a template T, that can be used in a
   class as follows:

struct example { void f(); typedef decltype( T( &f )) S; };

   . The type »S« now has a certain property, that can
   be useful sometimes. What is this property (asking Bill)?

I'll reveal that I'm not Bjarne Stroustrup.  decltype was introduced in 
C++11, which I haven't explored, and I have never written any code that 
resembles your template.  But it appears that an object of type S may 
behave like a function, which in this case would invoke Example.f().  As 
has already been pointed out, one can write "obfuscating code" in any 
language, with little effort.  I strive to write code which is easily 
understandable--and I document it. I don't wish to debate whether I 
could make more of a mess in Python, or not.


--
https://mail.python.org/mailman/listinfo/python-list


Re: [Tutor] beginning to code

2017-09-21 Thread Bill

Stefan Ram wrote:

Bill  writes:

Stefan Ram wrote:

bartc  writes:

On 20/09/2017 02:31, Bill wrote:

it's implementation, I would say that C++ has it all over Python from
the point of view of "intuitiveness".  It's much easier to tell what's
going on, at a glance, in a C++ program.

You're being serious, aren't you?

For one example, this is a part of a C++ program:
template< typename C >C T( void ( C::* )() );
. It defines a template T, that can be used in a
class as follows:
struct example { void f(); typedef decltype( T( &f )) S; };
. The type »S« now has a certain property, that can
be useful sometimes. What is this property (asking Bill)?As

has already been pointed out, one can write "obfuscating code" in any
language, with little effort.  I strive to write code which is easily
understandable--and I document it. I don't wish to debate whether I
could make more of a mess in Python, or not.

   From the point of view of a C++ programmer,
Oh, we "all look the same", huh?  I know that we've only just met, but I 
will caution that you are coming across as something of a "know-it-all".


Bill





the above
   is not obfuscated, but it is readable and simple C++.
   It is of course not readable for readers who do not know
   C++. Just as Python's »string[::-1]« appears "obfuscated"
   to readers who don't know Python.

   It was the answer to the question "How can I express the
   class I'm in in, when I can't write that classes name
   literally? So, »S« is »example«.

   It works like this: The type of »&f« is »void ( example::*
   )()«. So, the function-declaration template »T« infers »C«
   to be »example«, and the type of »T( &f )« is »example«,
   which then is transferred to the name »S« using typedef.

   This is obvious for C++ programmers, but it takes a lot
   of time to become a C++ programmer, maybe more than it
   takes to become a Python programmer.



--
https://mail.python.org/mailman/listinfo/python-list


Re: [Tutor] beginning to code

2017-09-21 Thread Bill

Stefan Ram wrote:

Just as Python's »string[::-1]« appears "obfuscated"
   to readers who don't know Python.


I understand string[::-1] after only studying python for a day or two 
(I've only been studying it for 2 weeks at this point).  A student could 
study C++ for a semester or more and not encounter templates until they 
studied data structures.  So in short, I don't believe that the example 
you chose from Python and the one you chose from C++, were at similar 
levels (not even close).




   It was the answer to the question "How can I express the
   class I'm in in, when I can't write that classes name
   literally? So, »S« is »example«.

   It works like this: The type of »&f« is »void ( example::*
   )()«. So, the function-declaration template »T« infers »C«
   to be »example«, and the type of »T( &f )« is »example«,
   which then is transferred to the name »S« using typedef.

   This is obvious for C++ programmers, but it takes a lot
   of time to become a C++ programmer, maybe more than it
   takes to become a Python programmer.



--
https://mail.python.org/mailman/listinfo/python-list


Re: [Tutor] beginning to code

2017-09-21 Thread Bill

Stefan Ram wrote:

Bill  writes:

I understand string[::-1] after only studying python for a day or two
(I've only been studying it for 2 weeks at this point).  A student could
study C++ for a semester or more and not encounter templates until they
studied data structures.  So in short, I don't believe that the example
you chose from Python and the one you chose from C++, were at similar
levels (not even close).

   I was responding to your assertion:

|It's much easier to tell what's going on, at a glance, in a
|C++ program.

   and I showed a simple counterexample.

But it was *not* a simple counterexample.

   And above, now, it seems that you /agree/ that one can learn
   Python in a short time, but needs a lot longer to learn C++.
Learning to develop code, in either language, involves much more than 
"learning C++" or "learning Python".  I have been reading Beazley's 
"Essential Reference", and I would say that Python is definitely a 
bigger, and more complicated language than C++.  In some aspects it has 
simpler syntax.  But consider all of the ways that you can pass 
arguments to a function, for instance. There are definitely alot more 
options than in C/C++. I like the way that both of these languages 
(unlike Java) allow you to stick with the procedural paradigm if you 
wish to (which I think is a natural way for a true beginner to start).  
From my perspective, Python's simplicity lies in the fact that an 
entire program does not have to be recompiled if a module is changed. 
Since I was programming in C (and Fortran) before you were born, it's 
syntax does not generally pose a hindrance to me.





   BTW: templates have little to do with data structures. One can
   show resonable examples for function templates that do not use
   any data structure:
You are sounding like a "know-it-all" again.  I am familiar with such 
examples.  One could code in C++ for a long time without a definitive 
need for templates.  It just depends on the application. By trade, I am 
more of a mathematician than a programmer but sometimes my needs and/or 
interests overlap.





template< typename T >
T maximum( T const a, T const b ){ return a > b ? a : b; }

   . The corresponding Python def would be (untested):

def maximum( a, b ): return a if a > b else b

   , that is, because Python is not statically typed, one does
   not need a template for a corresponding definition in Python.



--
https://mail.python.org/mailman/listinfo/python-list


Re: [Tutor] beginning to code

2017-09-21 Thread Bill

Stefan Ram wrote:

Bill  writes:

"Essential Reference", and I would say that Python is definitely a
bigger, and more complicated language than C++.  In some aspects it has
simpler syntax.  But consider all of the ways that you can pass
arguments to a function, for instance. There are definitely alot more
options than in C/C++. I like the way that both of these languages

   In C++, you can pass:


I used the word *arguments*, not parameters.  FWIW, *const* seems to 
correspond to immutable, pretty well.  I find Python to be more more 
like Java, with regard to "passing objects by reference".





 - by value (with a const or non-const parameter)
   (where the value can be a pointer or a non-pointer
   or a pointer-to-member or a unique_ptr or a shared_ptr)
 - by reference
 - by const reference
 - by rvalue reference
 - by universal reference
 - by name (in macros)
 - you can overload functions with the same name
   but different numbers of parameter or different
   types for their parameters
 - you can write templates for functions with ranges of types
   for a parameter
 - default values can be declared for parameters

   In Python, you pass

 - by value

   The section 6.3.4 on calls "in The Python Language
   Reference, Release 3.6.0" encompasses 1½ pages.


You are sounding like a "know-it-all" again.  I am familiar with such
examples.  One could code in C++ for a long time without a definitive
need for templates.

   Ok, so if we exclude from C++ everything that you have not
   learned yet, than, what is left over, is "much easier" for
   you to read "at a glance". It seems that you want C++ to be
   adjusted to your knowledge of it and your assertions about
   it. I think that one should instead adjust one's assertions
   to the reality.

The Python Language Reference, Release 3.6.0 146 pages
latest ISO-C++ draft (without the library part)  464 pages


Bear in mind that you don't have to know every feature of a language to 
make good use of it, unless, perhaps, that is your job.  I don't believe 
reading the latest "ISO-C++ draft" would be a good use of my time; it 
sounds like a document geared more to compiler designers. I don't even 
try to memorize . If I need a function, I search for it.


There is a reason that C++, Java and Python all coexist. It might be 
helpful for you to try to appreciate that.


Regards,
Bill

--
https://mail.python.org/mailman/listinfo/python-list


Re: [Tutor] beginning to code

2017-09-22 Thread Bill

Steve D'Aprano wrote:

On Fri, 22 Sep 2017 02:57 pm, Bill wrote:


I find Python to be more more
like Java, with regard to "passing objects by reference".

Which is not a surprise, since both Python and Java use the same value passing
style: pass by object reference, or pass by sharing if you prefer.

Java people don't call it that. They call it pass by value, and categorically
deny that it is pass by reference. (They're right about the second point.)


I figure that, internally, an address, a pointer, is being passed by 
value to implement pass by reference.  Why do you say "they are right" 
above? Are you saying it's not pass by reference?


What really screws the terminology up is that it's not parameters that 
are being passed, it's arguments! %-)





It also the exact same passing style as used by Swift, except Swift calls it
pass by reference, and denies it is pass by value. (They're right about the
second point.)





--
https://mail.python.org/mailman/listinfo/python-list


Re: [Tutor] beginning to code

2017-09-22 Thread Bill

Stefan Ram wrote:

Bill  writes:

Stefan Ram wrote:

bartc  writes:

On 20/09/2017 02:31, Bill wrote:

it's implementation, I would say that C++ has it all over Python from
the point of view of "intuitiveness".  It's much easier to tell what's
going on, at a glance, in a C++ program.

You're being serious, aren't you?

For one example, this is a part of a C++ program:
template< typename C >C T( void ( C::* )() );
. It defines a template T, that can be used in a
class as follows:
struct example { void f(); typedef decltype( T( &f )) S; };
. The type »S« now has a certain property, that can
be useful sometimes. What is this property (asking Bill)?As

has already been pointed out, one can write "obfuscating code" in any
language, with little effort.  I strive to write code which is easily
understandable--and I document it. I don't wish to debate whether I
could make more of a mess in Python, or not.

   From the point of view of a C++ programmer, the above
   is not obfuscated, but it is readable and simple C++.
   It is of course not readable for readers who do not know
   C++. Just as Python's »string[::-1]« appears "obfuscated"
   to readers who don't know Python.

   It was the answer to the question "How can I express the
   class I'm in in, when I can't write that classes name
   literally?


I would try to use virtual cast in place of the *&%, I mean code, you 
wrote.  "Clever code" is a losing game--just look at your explanation 
below.  Simple==Good.




So, »S« is »example«.

   It works like this: The type of »&f« is »void ( example::*
   )()«. So, the function-declaration template »T« infers »C«
   to be »example«, and the type of »T( &f )« is »example«,
   which then is transferred to the name »S« using typedef.

   This is obvious for C++ programmers, but it takes a lot
   of time to become a C++ programmer, maybe more than it
   takes to become a Python programmer.



--
https://mail.python.org/mailman/listinfo/python-list


Re: [Tutor] beginning to code

2017-09-22 Thread Bill

Bill wrote:

Stefan Ram wrote:

Bill  writes:

Stefan Ram wrote:

bartc  writes:

On 20/09/2017 02:31, Bill wrote:
it's implementation, I would say that C++ has it all over Python 
from
the point of view of "intuitiveness".  It's much easier to tell 
what's

going on, at a glance, in a C++ program.

You're being serious, aren't you?

For one example, this is a part of a C++ program:
template< typename C >C T( void ( C::* )() );
. It defines a template T, that can be used in a
class as follows:
struct example { void f(); typedef decltype( T( &f )) S; };
. The type »S« now has a certain property, that can
be useful sometimes. What is this property (asking Bill)?As

has already been pointed out, one can write "obfuscating code" in any
language, with little effort.  I strive to write code which is easily
understandable--and I document it. I don't wish to debate whether I
could make more of a mess in Python, or not.

   From the point of view of a C++ programmer, the above
   is not obfuscated, but it is readable and simple C++.
   It is of course not readable for readers who do not know
   C++. Just as Python's »string[::-1]« appears "obfuscated"
   to readers who don't know Python.

   It was the answer to the question "How can I express the
   class I'm in in, when I can't write that classes name
   literally?


I would try to use virtual cast in place of the *&%, I mean code, you 
wrote.


Sorry, I mean dynamic_cast().

"Clever code" is a losing game--just look at your explanation below.  
Simple==Good.




So, »S« is »example«.

   It works like this: The type of »&f« is »void ( example::*
   )()«. So, the function-declaration template »T« infers »C«
   to be »example«, and the type of »T( &f )« is »example«,
   which then is transferred to the name »S« using typedef.

   This is obvious for C++ programmers, but it takes a lot
   of time to become a C++ programmer, maybe more than it
   takes to become a Python programmer.





--
https://mail.python.org/mailman/listinfo/python-list


Re: [Tutor] beginning to code

2017-09-22 Thread Bill

Marko Rauhamaa wrote:

Bill :


I figure that, internally, an address, a pointer, is being passed by
value to implement pass by reference. Why do you say "they are right"
above? Are you saying it's not pass by reference?


Thank you for your examples.  I studied them carefully (and I'm not 
through with them yet).
I just wanted to mention that my comment was made in the context that 
Python is implemented by an interpreter written in C.   I realize that 
this may not always be the case.  However, I haven't heard anyone 
mention a Python interpreter written in Python yet.

"Pass by reference" could be "pass by reference to object" (Python,
Java, JavaScript, Lisp) or "pass by reference to memory slot" (available
to Pascal and C++).

Memory slots (or lvalues, as they are known in C) are not first class
objects in Python, which makes "pass by reference to memory slot" a bit
tricky in Python. Python *could* add memory slots to its sanctioned
collection of object types, and it *could* add special syntax to express
a memory slot reference and dereference ("&" and "*" in C).

However, Python doesn't need any language changes to implement memory
slots. A memory slot could be defined as any object that implements
"get()" and "set(value)" methods:

C: &x

Python:
   class Xref:
   def get(self): return x
   def set(self, value): nonlocal x; x = value
   ref_x = Xref()


C: &x->y[3]

Python:
   class XY3ref:
   def get(self): return x.y[3]
   def set(self, value): x.y[3] = value
   ref_xy3 = XY3ref()

The examples could be simplified:

   ref_x = slot_ref(locals(), "x")
   ref_xy3 = slot_ref(x.y, 3)

by defining:

def slot_ref(dict_or_array, key_or_index):
class SlotRef:
def get(self): return dict_or_array[key_or_index]
def set(self, value): dict_or_array[key_or_index] = value
return SlotRef()


Marko


--
https://mail.python.org/mailman/listinfo/python-list


Re: [Tutor] beginning to code

2017-09-22 Thread Bill

Mark Lawrence wrote:

On 22/09/2017 08:01, Bill wrote:

Steve D'Aprano wrote:

On Fri, 22 Sep 2017 02:57 pm, Bill wrote:


I find Python to be more more
like Java, with regard to "passing objects by reference".
Which is not a surprise, since both Python and Java use the same 
value passing

style: pass by object reference, or pass by sharing if you prefer.

Java people don't call it that. They call it pass by value, and 
categorically
deny that it is pass by reference. (They're right about the second 
point.)


I figure that, internally, an address, a pointer, is being passed by 
value to implement pass by reference.  Why do you say "they are 
right" above? Are you saying it's not pass by reference?




Please see 
http://jeffknupp.com/blog/2012/11/13/is-python-callbyvalue-or-callbyreference-neither/ 
and http://effbot.org/zone/call-by-object.htm





I would would agree with the description provided for the C++ example 
provided


string some_guy = "fred";
 is replaced by
char* some_guy="fred";

To see that this is correct, note the some_guy may subsequently be 
assigned to a character string much longer then "fred".  An additional 
note: A character string literal, like "cat", never occurs more than 
once in compiled C++ program unit.  This also shows that the provided 
description can't be completely correct. One last thing,


string some_guy = "fred"

is really the same thing as

string some_guy("fred");

and both equivalently call the string constructor.

The data type of "fred" is const char*, not (class) string.
--
https://mail.python.org/mailman/listinfo/python-list


Re: [Tutor] beginning to code

2017-09-22 Thread Bill

Bill wrote:

Mark Lawrence wrote:

On 22/09/2017 08:01, Bill wrote:

Steve D'Aprano wrote:

On Fri, 22 Sep 2017 02:57 pm, Bill wrote:


I find Python to be more more
like Java, with regard to "passing objects by reference".
Which is not a surprise, since both Python and Java use the same 
value passing

style: pass by object reference, or pass by sharing if you prefer.

Java people don't call it that. They call it pass by value, and 
categorically
deny that it is pass by reference. (They're right about the second 
point.)


I figure that, internally, an address, a pointer, is being passed by 
value to implement pass by reference.  Why do you say "they are 
right" above? Are you saying it's not pass by reference?




Please see 
http://jeffknupp.com/blog/2012/11/13/is-python-callbyvalue-or-callbyreference-neither/ 
and http://effbot.org/zone/call-by-object.htm





I would would agree with the description provided for the C++ example 
provided


string some_guy = "fred";
 is replaced by
char* some_guy="fred";


On second thought, so that the description is correct (matches the 
semantics), replace it by


char some_guy[10]="fred";

But then you need to use std::strcpy to reassign some_guy
to "george".








To see that this is correct, note the some_guy may subsequently be 
assigned to a character string much longer then "fred".  An additional 
note: A character string literal, like "cat", never occurs more than 
once in compiled C++ program unit.  This also shows that the provided 
description can't be completely correct. One last thing,


string some_guy = "fred"

is really the same thing as

string some_guy("fred");

and both equivalently call the string constructor.

The data type of "fred" is const char*, not (class) string.


--
https://mail.python.org/mailman/listinfo/python-list


Re: Python Boolean Logic

2017-09-22 Thread Bill

Cai Gengyang wrote:

Hey guys, I'm testing this on CodeAcademy, but I cant get the program to output 
a result even after pressing the run button. Just wanted to check if my logic 
is correct. Thanks alot
Your answers appear correct, but you could write Python statements to 
test them (or any you encounter in the future). For instance,


if (20 - 10)  > 15 :
print("true")
else:
print("false");

Or,

s='(20 - 10)  > 15'
b=(20 - 10)  > 15
print(s, " is ", ("true" if b else "false") );  ## inside parentheses 
may be removed.


I am new to Python.  Maybe someone here is familiar with an elegant way 
to get the the value of b directly from the string s?  Hmm... It appears 
that eval() would work (see "Python: Essential Reference", p. 115).  I 
just read about that for the first time last night! I may try that, for 
practice,  after I post this.


Bill



# Assign True or False as appropriate on the lines below!

# (20 - 10) > 15
bool_one = False# We did this one for you!

# (10 + 17) == 3**16
# Remember that ** can be read as 'to the power of'. 3**16 is about 43 million.
bool_two = False

# 1**2 <= -1
bool_three = False

# 40 * 4 >= -4
bool_four = True

# 100 != 10**2
bool_five = False


--
https://mail.python.org/mailman/listinfo/python-list


Re: Python Boolean Logic

2017-09-22 Thread Bill

Bill wrote:

Cai Gengyang wrote:
Hey guys, I'm testing this on CodeAcademy, but I cant get the program 
to output a result even after pressing the run button. Just wanted to 
check if my logic is correct. Thanks alot
Your answers appear correct, but you could write Python statements to 
test them (or any you encounter in the future). For instance,


if (20 - 10)  > 15 :
print("true")
else:
print("false");

Or,

s='(20 - 10)  > 15'
b=(20 - 10)  > 15
print(s, " is ", ("true" if b else "false") );  ## inside parentheses 
may be removed.


I am new to Python.  Maybe someone here is familiar with an elegant 
way to get the the value of b directly from the string s? Hmm... It 
appears that eval() would work (see "Python: Essential Reference", p. 
115).  I just read about that for the first time last night! I may try 
that, for practice,  after I post this.



Update: Yes,
b=(20 - 10)  > 15
may be replaced by eval(s).

We can write:

print(s, " is ", ("true" if eval(s)  else "false") )







# Assign True or False as appropriate on the lines below!

# (20 - 10) > 15
bool_one = False# We did this one for you!

# (10 + 17) == 3**16
# Remember that ** can be read as 'to the power of'. 3**16 is about 
43 million.

bool_two = False

# 1**2 <= -1
bool_three = False

# 40 * 4 >= -4
bool_four = True

# 100 != 10**2
bool_five = False




--
https://mail.python.org/mailman/listinfo/python-list


Re: Python Boolean Logic

2017-09-23 Thread Bill

Steve D'Aprano wrote:

On Sat, 23 Sep 2017 03:01 pm, Bill wrote:


s='(20 - 10)  > 15'
b=(20 - 10)  > 15
print(s, " is ", ("true" if b else "false") );  ## inside parentheses
may be removed.

I am new to Python.  Maybe someone here is familiar with an elegant way
to get the the value of b directly from the string s?  Hmm... It appears
that eval() would work


Indeed it will, but don't get into the habit of using eval willy-nilly. While it
is absolutely fine to use it with data you provide yourself, it is a HUGE
security risk to eval strings that came from an untrusted user.


eval("__import__('os').system('echo """rm-rf /"""')")


Thank you. Studying that was a nice little lesson in itself!   I 
recognize that this technique can be used for 'good' as well as 'evil'!  : )


Bill

--
https://mail.python.org/mailman/listinfo/python-list


Re: search and replace first amount of strings instances with one thing and a second amount of instances with another thing-

2017-09-23 Thread Bill

validationma...@gmail.com wrote:

i have a code in python to search and replace what i need though is to replace 
the first say 10 instances of the number 1 with 2 and the second 10 instances 
with the number 3. anybody knows how to do that?
Do you mean the (integer) number 1 or the character '1'? For instance, 
if the first line of the file is:

"There were 100 cats in the yard."
Do you want to change this to
"There were 200 cats in the yard."?
Remember that string objects are "immutable" so your code probably 
wouldn't work exactly like that.





fin = open(r'F:\1\xxx.txt')
fout = open(r'F:\1\xxx2.txt', "wt")
for line in fin:
 fout.write( line.replace('1', '2') )
fin.close()
fout.close()


--
https://mail.python.org/mailman/listinfo/python-list


Re: search and replace first amount of strings instances with one thing and a second amount of instances with another thing-

2017-09-23 Thread Bill

Bill wrote:

validationma...@gmail.com wrote:
i have a code in python to search and replace what i need though is 
to replace the first say 10 instances of the number 1 with 2 and the 
second 10 instances with the number 3. anybody knows how to do that?
Do you mean the (integer) number 1 or the character '1'? For instance, 
if the first line of the file is:

"There were 100 cats in the yard."
Do you want to change this to
"There were 200 cats in the yard."?
Remember that string objects are "immutable" so your code probably 
wouldn't work exactly like that.


I now realize that my last line does not apply. I suggest you start by 
just thinking about changing the first ten ones to twos.  Once you do 
that, you should have little trouble finishing the job. Being a Python 
newbie myself, your example helped motivate me to try my own example.  I 
used "type" to learn the data type of line (in your example), about 
which I was curious. My first concern was that is might only be 
"interable" object, but I learned that more is true.







fin = open(r'F:\1\xxx.txt')
fout = open(r'F:\1\xxx2.txt', "wt")
for line in fin:
 fout.write( line.replace('1', '2') )
fin.close()
fout.close()




--
https://mail.python.org/mailman/listinfo/python-list


Re: Python Boolean Logic

2017-09-23 Thread Bill

Chris Warrick wrote:


This outputs "False is false", because you used the variable in your
expression. You can just do this:


print("s is", s)

This will print "s is False".

Ah, good point!   But I do like "self-documenting" output (so I don't 
mind seeing s)---if you had 5 or more statements a in a row like that, 
you would "miss" seeing the string s!   : )


Bill

--
https://mail.python.org/mailman/listinfo/python-list


Re: [Tutor] beginning to code

2017-09-23 Thread Bill

Stephan Houben wrote:

Op 2017-09-23, Rick Johnson schreef :

These pissing contests over how values are passed in Python
are totally irrelevant. What does it matter? Nothing will be
gained or lost by arguing over which is true, or not. Unless
the distinction is preventing you from doing something that
you'd like to do, or unless you want to argue that one
"value passing method" would bring X, Y or Z benefits over
the other, what does it matter?

Amen.



All one has to do, I think, is consider (1) that passing objects by 
"making copies" of them, would be prohibitively expensive and consider 
that something else has to happen as an alternative, and (2) understand 
that in Python, objects don't have names, they have references (which 
have names).  The rest could be "implementation dependent" (no?)   To be 
amusing, how did the chicken pass an egg to 
the_other_side_of_the_road(e)?  Could the egg get crushed (stay tuned)?


--
https://mail.python.org/mailman/listinfo/python-list


Re: [Tutor] beginning to code

2017-09-23 Thread Bill

Chris Angelico wrote:

On Sun, Sep 24, 2017 at 8:18 AM, Bill  wrote:

Stephan Houben wrote:

Op 2017-09-23, Rick Johnson schreef :

These pissing contests over how values are passed in Python
are totally irrelevant. What does it matter? Nothing will be
gained or lost by arguing over which is true, or not. Unless
the distinction is preventing you from doing something that
you'd like to do, or unless you want to argue that one
"value passing method" would bring X, Y or Z benefits over
the other, what does it matter?

Amen.


All one has to do, I think, is consider (1) that passing objects by "making
copies" of them, would be prohibitively expensive and consider that
something else has to happen as an alternative, and (2) understand that in
Python, objects don't have names, they have references (which have names).
The rest could be "implementation dependent" (no?)   To be amusing, how did
the chicken pass an egg to the_other_side_of_the_road(e)?  Could the egg get
crushed (stay tuned)?

Actually they don't "have" references in any real sense of possession.
I agree (I was a bit hasty in my choice of words); but if they didn't 
"have" these references, it would be difficult, though not impossible, 
to refer to them.   Also keep in mind that the garbage collector keeps 
track, generally, of how many there are for each object!   So from the 
gc's point of view, objects (definitely) "have" references.  Next, 
what will Egg.__del__() do? : )





An object "has" things like its type, its attributes, etc etc; if you
have a reference to an object, you can query it for its type. But you
can't ask an object if there's a reference to it over here or there.
(Yes, I know that sys.getrefcount exists in CPython, but this isn't
part of the language's definition. Also, even that is just a counter -
you can't find specific references.) An object may have a reference to
other objects (eg a list's contents), but it's a one-way thing -
there's no way to find all the references to this object.

So more accurate would be to say that objects don't have names, but
names refer to objects. When you assign to a simple name, you cause
that name to refer to the object you gave it.

ChrisA


--
https://mail.python.org/mailman/listinfo/python-list


Re: [Tutor] beginning to code

2017-09-23 Thread Bill

Steve D'Aprano wrote:

On Sun, 24 Sep 2017 08:18 am, Bill wrote:


All one has to do, I think, is consider (1) that passing objects by
"making copies" of them, would be prohibitively expensive


Swift passes certain values (but not others!) by value and makes a copy. That
includes many potentially large data types including strings, dictionaries and
arrays, but using copy-on-write so the data isn't physically copied until you
actually mutate it. From the Swift documentation:


 The description above refers to the “copying” of strings, arrays,
 and dictionaries. The behavior you see in your code will always
 be as if a copy took place. However, Swift only performs an actual
 copy behind the scenes when it is absolutely necessary to do so.
 Swift manages all value copying to ensure optimal performance, and
 you should not avoid assignment to try to preempt this optimization.

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ClassesAndStructures.html


So I maintain that one could design a language similar to Python except that
objects are assigned and passed by value, making copies only when actually
needed using copy-on-write. Swift is *almost* that language: the difference is
that Swift distinguishes between "structs" that are copied, and "objects" which
are not.



and consider
that something else has to happen as an alternative, and (2) understand
that in Python, objects don't have names, they have references (which
have names).  The rest could be "implementation dependent" (no?)

No.

There are many different alternatives for "something else", and while some of
them may be behave the same in some circumstances, they do not behave the same
in all circumstances. Any interpreter calling itself Python would be expected
to match the behaviour of the reference implementation, CPython.

For example, if I made "Pass-By-Reference Python" where all argument passing was
done by reference, my language would differ from real Python:


function(x, y)  # allowed
function(namespace.x, module.y)  # allowed
function(x + 1, 2)  # FORBIDDEN: can't pass expressions or constants


This would be okay as long as x + 1 evaluates to an object, no?




Obviously that's not Python!

On the other hand, "Pass-By-Name Python" would allow passing expressions and
constants, but will differ in other ways.

Assignment by reference would mean that name binding was an *alias* operation:


module.y = 1
x = module.y  # x is an alias for the name "module.y"
x = 2  # binds 2 to module.y
assert module.y == 2






--
https://mail.python.org/mailman/listinfo/python-list


Re: Call by binding [was Re: [Tutor] beginning to code]

2017-09-25 Thread Bill

Chris Angelico wrote:

On Tue, Sep 26, 2017 at 5:35 AM, Marko Rauhamaa  wrote:

Chris Angelico :


On Tue, Sep 26, 2017 at 12:26 AM, Marko Rauhamaa  wrote:
Sorry, that was my bad in the terminology. But where do you get that
all Python expressions evaluate to pointers?

What do they evaluate to if not pointers? Anton's "identities" would
work, too. "Address" would do, as well. I have previously proposed the
term "leash." Call it "link" or "handle" or "arrow" if you want to.

The term used isn't important. What's important is to understand that
each expression and subexpression produces and operates on pointers.

They evaluate to objects. Not to pointers to objects. Not to
references to objects. To objects. Expressions evaluate to actual
objects, and when you assign "name = value", you bind the name to the
object that value evaluates to.

ChrisA


And when you pass a reference r to a function, a copy of the reference 
is passed. So even if you reassign *that* copy of r to refer to another 
object, upon return, r still still refers to whatever it did 
originally.  ::: case closed :::, I think.

--
https://mail.python.org/mailman/listinfo/python-list


Re: Call by binding [was Re: [Tutor] beginning to code]

2017-09-25 Thread Bill

Tim Golden wrote:

On 25/09/2017 20:40, Marko Rauhamaa wrote:

Rhodri James :

On 25/09/17 15:26, Marko Rauhamaa wrote:

That's not what I said. I said all expressions *evaluate to* pointers.


This may well be true in particular implementations, but it is an
implementation detail so Chris' point still stands.  Another
implementation could evaluate expressions to indices (as BCPL used to
treat its globals), pieces of string or cheese, who knows?


Those are all pointers.

A pointer is something that points to a data object.


(Slight sigh). Can I step in as a list owner and ask the people who 
are so very fond of debating this topic again and again: please let it 
drop.


Threads such as this can remain interesting when the discussion 
generates a better understanding of the subject matter as the 
contributors are forced to articulate their positions leading to some 
kind of convergence of understanding.


However, even if this were the only iteration of this debate, it would 
be clear by now that there's no chance of a simple "I see what you 
mean" moment. And this is far from the only iteration, even in the 
past few months.


I feel for your need to demonstrate the validity of your respective 
positions. But it has moved on from being an enlightening debate and 
into the realms of mere tedium.


Thanks.

TJG


Perhaps it would be better to amass examples and let them speak for 
themselves?

--
https://mail.python.org/mailman/listinfo/python-list


Re: Aliasing [was Re: [Tutor] beginning to code]

2017-09-26 Thread Bill

Steve D'Aprano wrote:

On Wed, 27 Sep 2017 02:03 am, Stefan Ram wrote:


Steve D'Aprano  writes:

On Tue, 26 Sep 2017 03:26 am, Antoon Pardon wrote:

at that moment, but it still needed correction. If the assignment is
an alias operator then after the statements

Here's some C++ code that demonstrates it. Apologies in advance if it isn't
the most idiomatic C++ code.

   In C++, assignments and initializations are different
   concepts.


int& b = a;  // reference variable or alias

   This is an initialization, not an assignment.

A pedantic difference that makes no difference to my argument.

I see that you ignored the later assignment:

b = 2;

which also assigned to a. *That** is the fundamental point: b is certainly an
alias for a, and assigning to b assigns to a.

That's how aliases work in C++. That's how var parameters in Pascal work, and
out parameters in Ada. That is what it means to say that "b is an alias to a".

b is another name for the *variable* a, not just whatever value a happens to
hold now.

I say that assignment in Python is NOT an aliasing operation. Antoon claims I'm
wrong, and his evidence is:

a = []
b = a  # Antoon says this is an alias operation
b.append(1)
assert a == [1]


But that's not enough for the variable b to be an alias for the variable a.

Antoon is correct that a and b are two different names for the same list, but
the two variables are not aliases to each other because assignments to b do not
affect a, and vice versa.

A good test for aliasing is to take the source code and mechanically replace
every occurrence of the alias (in the same scope of course) with the original,
or vice versa, and see whether the meaning of the code changes.

In C++, apart from the initial binding:

 int& b = a;

("initialisation") you could now randomly swap a for b or b for a and the
meaning of the code will not change.

But in Python, if we try the same trick, the code *does* change:

a = 1
b = a
b = 2

*is not* the same as:

a = 1
b = a
a = 2


(1) In Pascal, Ada, C++ etc using a reference variable (or var parameter, or
whatever terminology they use) makes the two names aliases to EACH OTHER, not
to the value they are bound to.

(2) In Python, Javascript, Ruby etc assignment can give you two names for the
same object, but the names do not alias each other.

The critical distinction here is whether the names refer to each other:

a <---> b

or whether they merely refer to the same value:

a ---> [ value ] <--- b


Python uses the second model. Var parameters in Pascal and references in C++ use
the first. Since the term "aliasing" is well-established for the first, using
it in Python *without making the difference clear* is wrong.




That is a very nice argument!  : )
--
https://mail.python.org/mailman/listinfo/python-list


Spacing conventions

2017-09-27 Thread Bill
Ever since I download the MyCharm IDE a few days ago, I've been noticing 
all sort of "spacing  conventions (from PEP) that are suggested.  How do 
folks regard these in general?


For instance,  the conventions suggest that

if x>y :
 pass

should be written
if x > y:
pass

Personally, I like seeing a space before the colon (:).   And then in

my_list = [ i for i in range(0, 10) ]
it complains about my extra space inside of the brackets.

If you are teaching beginning students, do you expect them to try to 
follow these sorts of conventions?  Is it perfectly fine to let "taste" 
guide you (I'm just trying to get a feel for the philosophy here)?   I 
also notice "break" and exception handling is used much more in Python 
than in C++, for instance.  I was taught "break" and "continue" led to 
"unstructured code"--but that was a while back.  I can still see their 
use  causing potential trouble in (really-long) real-world code.


Bill



--
https://mail.python.org/mailman/listinfo/python-list


Re: Spacing conventions

2017-09-27 Thread Bill
Thank you for all of the feedback provided!  It was just what I was 
looking for.  : )

I'm going to go back and read some of the links more carefully.

Bill
--
https://mail.python.org/mailman/listinfo/python-list


Re: Spacing conventions

2017-09-27 Thread Bill

Steve D'Aprano wrote:


Similarly for break and continue.


I can still see their
use  causing potential trouble in (really-long) real-world code.

How so?

Besides, if your code is "really long", you probably should factorise it into
smaller, meaningful chunks.



I worked in maintenance programming.  You got the hand you were dealt!  
And you weren't allowed to "improve" the code unless the customer 
contracted you to do so.  I maintained for-loops (containing 
for-loops)... hundreds of lines long.   Would you be searching for break or

continue?  : )






--
https://mail.python.org/mailman/listinfo/python-list


Re: Beginners and experts (Batchelder blog post)

2017-09-28 Thread Bill

Paul Moore wrote:

On 27 September 2017 at 17:41, leam hall  wrote:

Hehe...I've been trying to figure out how to phrase a question. Knowing I'm
not the only one who gets frustrated really helps.

I'm trying to learn to be a programmer. I can look at a book and read basic
code in a few languages but it would be unfair to hire myself out as a
programmer. I'm just not yet worth what it costs to pay my bills.

You're already ahead of the game in wanting to be useful, rather than
just knowing the jargon :-) However, I've always found that the
biggest asset a programmer can have is the simple willingness to
learn.


I basically agree with what has been posted. I just wanted to mention a 
couple things that separates beginners and non-beginners. One is "how 
long it takes to identify and fix an error"--even a syntax error. And 
that is a skill which is acquired with some practice, maybe more "some" 
than anyone likes. Another critical skill is the ability to write good 
documentation--from program requirements, on down. Another is to know 
what is means to "test". Another is to have some familiarity with the 
UML.  Skills in 3 of these 4 area might be assisted by reading about 
software engineering.  So after you have those skills, then, perhaps, 
you can think about "interviewing"--of course a degree will help.  As 
always, your mileage may vary...  It IS True that you don't have to wait 
until you "know everything"--most of use will never get there.

--
https://mail.python.org/mailman/listinfo/python-list


Re: Beginners and experts (Batchelder blog post)

2017-09-28 Thread Bill

Chris Angelico wrote:

On Fri, Sep 29, 2017 at 5:45 AM, Bill  wrote:

Paul Moore wrote:

On 27 September 2017 at 17:41, leam hall  wrote:

Hehe...I've been trying to figure out how to phrase a question. Knowing
I'm
not the only one who gets frustrated really helps.

I'm trying to learn to be a programmer. I can look at a book and read
basic
code in a few languages but it would be unfair to hire myself out as a
programmer. I'm just not yet worth what it costs to pay my bills.

You're already ahead of the game in wanting to be useful, rather than
just knowing the jargon :-) However, I've always found that the
biggest asset a programmer can have is the simple willingness to
learn.


I basically agree with what has been posted. I just wanted to mention a
couple things that separates beginners and non-beginners. One is "how long
it takes to identify and fix an error"--even a syntax error. And that is a
skill which is acquired with some practice, maybe more "some" than anyone
likes.

Be careful with this one. For anything other than trivial errors (and
even for some trivial errors), finding the bug is basically searching
through a problem space of all things that could potentially cause
this symptom. A novice could accidentally stumble onto the right
solution to a tricky bug, or an expert could search a thousand other
things and only get to the true cause after a long time.


 some "expert"!   ; )




So while
you're partly correct in saying "how long", you can't just put someone
on the clock and say "if you find the bug in less than five minutes,
you're hired". Ultimately, the only person who can truly evaluate a
programmer's skill is another programmer, usually by watching the
candidate go through this sort of debugging work. But yeah, broadly
speaking, an experienced programmer can usually debug something more
quickly than a novice can. On average.

ChrisA


--
https://mail.python.org/mailman/listinfo/python-list


Re: Beginners and experts (Batchelder blog post)

2017-09-28 Thread Bill

Chris Angelico wrote:

On Fri, Sep 29, 2017 at 6:59 AM, Bill  wrote:

Chris Angelico wrote:

Be careful with this one. For anything other than trivial errors (and
even for some trivial errors), finding the bug is basically searching
through a problem space of all things that could potentially cause
this symptom. A novice could accidentally stumble onto the right
solution to a tricky bug, or an expert could search a thousand other
things and only get to the true cause after a long time.

  some "expert"!   ; )


Yep. Pick anyone on this list that you believe is an expert, and ask
him/her for a story of a long debug session that ended up finding a
tiny problem. I can pretty much guarantee that every expert programmer
will have multiple such experiences, and it's just a matter of
remembering one with enough detail to share the story.

ChrisA
I won't claim to be any sort of "expert".  But one memorable problem, 
for me, was ultimately accounted for by the "inherent problem" of the 
floating point variables x0 and xo coexisting in the same module.  It's 
sort of funny if you think about it just right. FWIW, my job was to fix 
the problem, I didn't create it!


Bill

--
https://mail.python.org/mailman/listinfo/python-list


Re: Spacing conventions

2017-09-28 Thread Bill

Steve D'Aprano wrote:

On Thu, 28 Sep 2017 03:56 pm, Bill wrote:


I worked in maintenance programming.  You got the hand you were dealt!
And you weren't allowed to "improve" the code unless the customer
contracted you to do so.

How do you tell the difference between a bug fix and an code improvement, if the
behaviour of the program remains the same?


They ran the Unix command "diff" to double-check that nothing 
unaccounted for got added to the source code as they did new builds.
The "rule" was you could "fix" the code if you were already there, in 
the immediate vicinity. In retrospect, this certainly helped to keep 
"human error" from sneaking in.




I maintained for-loops (containing
for-loops)... hundreds of lines long.   Would you be searching for break or
continue?  : )

It depends on whether it was relevant to the bug or not.

I've never felt the urge to search for some arbitrary keyword when debugging.
Why search for break or continue? How do you know the bug has anything to do
with one of them?

I would start with narrowing down where the bug occurs. Hopefully the stacktrace
or error gives a line number. Then work backwards from there.

I certainly wouldn't say "Oh, the code crashed on line 587. I'll do a quick
search for the closest break statement and start working from there."

What do you do?





--
https://mail.python.org/mailman/listinfo/python-list


Re: Beginners and experts (Batchelder blog post)

2017-09-29 Thread Bill

Steve D'Aprano wrote:


(say). Reading error messages is a skill that must be learned, even in Python.
Let alone (say) gcc error messages, which are baroque to an extreme. The other
day I was getting an error like:

/tmp/ccchKJVU.o: In function `__static_initialization_and_destruction_0(int,
int)':
foo.cpp:(.text+0x7c): undefined reference to `std::ios_base::Init::Init()'
foo.cpp:(.text+0x91): undefined reference to `std::ios_base::Init::~Init()'
collect2: error: ld returned 1 exit status




Yes, that's the sort of character-building that I was referring to (that 
a beginner needs to learn!)They have to learn that if it "breaks", 
then there must be a simpler way to break it!  Hopefully one which will 
satisfy Log_2 (n).: )


--
https://mail.python.org/mailman/listinfo/python-list


Re: Refactoring

2017-09-29 Thread Bill

Stefan Ram wrote:


   The customer pays for the solution. The software
   manufacturer does the refactoring for it's own sake,
   because when it's a longer running project, the
   refactorings will pay for themself.



The customer owns the source code (at least where I was).  YMMV
--
https://mail.python.org/mailman/listinfo/python-list


Re: Beginners and experts (Batchelder blog post)

2017-09-29 Thread Bill

Chris Angelico wrote:

On Sat, Sep 30, 2017 at 2:42 AM, Steve D'Aprano
 wrote:

Oh, and I'd like to make a (moderate) defense of a kind of "bug fixing by random
perturbation". Obviously making unrelated, arbitrary changes to code is bad.
But making non-arbitrary but not fully understood changes to relevant code
sections can be useful in (at least) two scenarios.

(1) I know there's a bug in a specific chunk of code, but I'm having trouble
working out where. When everything else fails, if I perturb the code a bit
(reorder lines, calculate things in a different order, rename variables, etc)
it may change the nature of the bug enough for me to understand what's
happening.

That's not *random* or *arbitrary* changes, but they are changes not directed at
any specific outcome other than "make the code a bit different, and see if the
error changes". I'd like to say it is the debugging technique of last resort,
except its perhaps not quite as *last* resort as I'd like, especially in code
I'm not familiar with.

Its an experiment, but not really "carefully designed".


I'll write for the possible benefit of any beginners who may be 
reading.  I guess by definition, if one still has a "bug" it's because 
one doesn't quite understand what the code is doing. And I would say you 
should lose your license if you "fix something", and don't understand 
why it works (within reason of course--some mystery's of library 
functions should probably remain so forever). So ADT (Any Damn Thing--I 
just made that up that acronym) you can do to understand your code 
better is fair game! : )In fact, in my experience, the sooner you 
start getting a little bit angry, the sooner you'll get to the heart of 
matter.  Usually, what looks like a long route, isn't, in the end.  
Don't be afraid to write *really descriptive* output statements, and do 
so even though you "don't need to". Besides for making you more 
productive, it will help soothe you : )   Beginners almost never need 
to...  I think that getting out of the beginner phase requires 
developing a certain amount of humility.  Just wait 5 or 10 years, any 
look back, and see if what I've written isn't more true than false.


The only part I am unsure of is whether you are supposed to get a little 
big angry or not (YMMV).  I find 2 cups of coffee about right. That is, 
2 before and 2 after lunch. Of course, that does not include "meetings".

--
https://mail.python.org/mailman/listinfo/python-list


newb question about @property

2017-09-30 Thread Bill
I spent a few hours experimenting with @property. To my mind it seems 
like it would be preferable to just define (override) instance methods 
__get__(), __set__(), and possibly __del__(), as desired, as I could 
easily provide them with "ideal" customization. Am I overlooking something?


Bill
--
https://mail.python.org/mailman/listinfo/python-list


Re: newb question about @property

2017-09-30 Thread Bill

Ned Batchelder wrote:

On 9/30/17 5:47 PM, Bill wrote:
I spent a few hours experimenting with @property. To my mind it seems 
like it would be preferable to just define (override) instance 
methods __get__(), __set__(), and possibly __del__(), as desired, as 
I could easily provide them with "ideal" customization. Am I 
overlooking something?




It would be easier to comment if you showed the two options. One with 
@property, and one with __get__ etc.


A downside to __get__ is that you need to create a class with those 
methods, and then instantiate that class as an attribute in your real 
class, whereas @property can be used without a lot of rigamarole.


--Ned.


I am basically mimmicking what I see at (the very bottom of) this page:

https://www.programiz.com/python-programming/property

Thanks,
Bill


--
https://mail.python.org/mailman/listinfo/python-list


Re: newb question about @property

2017-09-30 Thread Bill

Steve D'Aprano wrote:

On Sun, 1 Oct 2017 08:47 am, Bill wrote:


I spent a few hours experimenting with @property. To my mind it seems
like it would be preferable to just define (override) instance methods
__get__(), __set__(), and possibly __del__(), as desired, as I could
easily provide them with "ideal" customization. Am I overlooking something?

Probably.


You and Ned are both right.  Up until a few minutes ago, I wasn't 
thinking about a class having more than 1 attribute that I wanted to 
change.  And now I realize that __get__ doesn't really make sense in 
that context (in the back of my mind was the notion that @property 
defined __get__, __set__ and __del__) and I allowed that to obscure my 
vision.   I was on the verge of giving up anything to do with computers, 
forever.  : )


BTW, your example (below) is very nice!  I may have seen something 
similar before, but I am starting to appreciate it better now.  I think 
all of this would have made a bit more sense (to me), if instead of just 
"@property", the syntax was "@property.getter".  Now I am forced to ask 
the question, why did they use the underscore (on temperature) in the 
example on the bottom of this page? Is one forced to introduce new 
identifiers in order to define a setter?


https://www.programiz.com/python-programming/property

Thanks!
-Bill



This is a particularly simple example, with only getters. How would you write it
by overriding __get__?


class Circle(object):
 def __init__(self, centre, radius):
 self.centre = centre
 self.radius = radius

 @property
 def diameter(self):
 return 2*self.radius

 @property
 def area(self):
 return pi*self.radius**2

 @property
 def circumference(self):
 return pi*self.diameter





--
https://mail.python.org/mailman/listinfo/python-list


Re: newb question about @property

2017-09-30 Thread Bill

Ned Batchelder wrote:

On 9/30/17 7:18 PM, Bill wrote:

Ned Batchelder wrote:

On 9/30/17 5:47 PM, Bill wrote:
I spent a few hours experimenting with @property. To my mind it 
seems like it would be preferable to just define (override) 
instance methods __get__(), __set__(), and possibly __del__(), as 
desired, as I could easily provide them with "ideal" customization. 
Am I overlooking something?




It would be easier to comment if you showed the two options. One 
with @property, and one with __get__ etc.


A downside to __get__ is that you need to create a class with those 
methods, and then instantiate that class as an attribute in your 
real class, whereas @property can be used without a lot of rigamarole.


--Ned.


I am basically mimmicking what I see at (the very bottom of) this page:

https://www.programiz.com/python-programming/property


Can you show us the code you are using it to mimic that?

--Ned.


Here it is, Ned. It's my first attempt at using classes in Python.
I still have to learn how to incorporate datetime appropriately!  :)

import datetime


# object oriented example class Employee(object):
''' This class will abstract an employee. Class date members name, a 
string birthday, a date object address, a string position It also has a 
static data member for the number of employees. ''' num_employees =0 # class data item @classmethod def get_num_employees(cls):

return Employee.num_employees

def __init__(self, name, birthdate, address, position):
Employee.num_employees +=1 self.name = name
self.birthdate = birthdate
self.address = address
self.position = position

@property def address(self):
print("**Hi from address-getter**")
return self._address

@address.setter def address(self, value):
print("*Hi, from address setter()!")
self._address = value


def __del__(self):

print("*** Hi, from __del__()")
##Employee.num_employees -= 1 def __str__(self):
return 'Name: {}, Born: {} \nAddress: {} \nPosition: {} \n'.\
format(self.name,self.birthdate,self.address,self.position)

class SalesPerson(Employee):
def __init__(self, name, bdate, addr):
super().__init__(name, bdate, addr,"Salesperson")


def main():
emp1 = Employee("Sam","4/30/1970","212 Elm","Programmer")
emp2 = SalesPerson("Gene","5/1/79","414 Maple")
## Note: learn to use datetime.date--> str print(emp1)
print(emp2)
emp1.address ="230 Main Street" # call setter? print(emp1)
del(emp1)
print("Number of employees", Employee.get_num_employees())
   




print('*'*30)
main()#call main()

--
https://mail.python.org/mailman/listinfo/python-list


Re: newb question about @property

2017-09-30 Thread Bill

Steve D'Aprano wrote:

Circle
didn't use any setters, but I could have let you set the diameter, which in
turn would set the radius:

circle.radius = 2
assert circle.diameter == 4
circle.diameter == 2  # requires a setter
assert circle.radius == 1

Getting that to work is left as an exercise :-)


I may start that exercise in a few minutes!



But most commonly, computed attributes need to store some data aside, somewhere.
You could use a global variable, or write it to a file, or stick it in a list.
All of these things have obvious problems, so the most sensible approach it to
stick the data in a private attribute.

The interpreter doesn't enforce notions of private/public when it comes to
Python classes, but there's a very strong convention that anything starting
with a single underscore is private.



[1] Technically, the interpreter knows nothing about properties. What it cares
about is *descriptors*. Properties are just one kind of descriptor, as are
methods. But I'm intentionally not talking about the gory details of
descriptors. Feel free to ask if you care, but honestly, you don't need to care
unless you are writing your own descriptor class.


Thank you, and everyone else who has contributed to this thread, for 
helping me.  Each contribution I read helped me to get further ahead!


I watched an example on YouTube where someone wrote a simple descriptor 
("@Time_it) to output the amount of time that it took ordinary functions 
to complete.To be honest, I AM interested in descriptors. I may 
reexamine whether David Beazley has more to say about them in his book  
"Python: Essential Reference", which I have been reading. Obviously, I 
still have some gaps in my understanding after my first reading.


If you were going to show non-Python users, say science undergraduates 
and faculty, that Python is an interesting tool (in 45 minutes), would 
one delve into descriptors? I am thinking maybe. Here is what I am 
thinking at this moment: trivial applications (probably), list 
comprehensions (definitely), generators (maybe briefly).   Whatever I 
would discuss, I think ending with descriptors could be a strong finish. 
But I'm certainly not merely interested for the sake of my talk, I 
obtain some satisfaction in learning how things work.  If you can 
suggest any references for descriptors which you think are good, I would 
be interested.


Thanks,
Bill

--
https://mail.python.org/mailman/listinfo/python-list


Re: newb question about @property

2017-10-01 Thread Bill

Steve D'Aprano wrote:


[1] Technically, the interpreter knows nothing about properties. What it cares
about is *descriptors*. Properties are just one kind of descriptor, as are
methods. But I'm intentionally not talking about the gory details of
descriptors. Feel free to ask if you care, but honestly, you don't need to care
unless you are writing your own descriptor class.

I found the following page to be a very easily accessible discussion 
about descriptors (it represents the state of my knowledge about 
descriptors).   You got more?  : )


https://www.programiz.com/python-programming/decorator


--
https://mail.python.org/mailman/listinfo/python-list


Re: newb question about @property

2017-10-01 Thread Bill

Steve D'Aprano wrote:

On Sun, 1 Oct 2017 05:46 pm, Bill wrote:


If you were going to show non-Python users, say science undergraduates
and faculty, that Python is an interesting tool (in 45 minutes), would
one delve into descriptors?

Hell no :-)
Oops, I see I used the word "descriptor", where I meant "decorator" (at 
least newb is still in the subject line).   I don't even know what a 
descriptor is yet--I know a bit more about meta-classes! %-) So, on your 
list, I'm basically up to the leading edge of (5), writing decorators. 
But my previous programming experience helped me to blast through (1) to 
(4).  Going forward, it appears the walkway will be a little steeper.  I 
do appreciate your list as it improves my perspective.


From the point of view of getting others to be interested, I'm not sure 
*classes* and object oriented design/thinking do it.  I think they are 
more of an acquired taste... Functions, on the other hand, are easy to 
like, I think--especially in Python.





I think there's a hierarchy of difficulty/complexity/mind-bogglingness in
Python. From least complex to most:

- Using Python in an imperative fashion, as in simple scripts.

- Writing your own functions.

- Writing your own classes.

- Writing generators.

- Using decorators, including property.

- Writing your own decorators.

- Writing your own descriptors.

- Writing your own metaclasses (a.k.a. "the killer joke").

I wouldn't touch the last three in a beginner's class, not unless they already
had a significant amount of programming experience.




I am thinking maybe. Here is what I am
thinking at this moment: trivial applications (probably), list
comprehensions (definitely), generators (maybe briefly). Whatever I
would discuss, I think ending with descriptors could be a strong finish.

That depends on whether your aim is to confuse them or not :-)

I don't think the descriptor protocol is something you'll be able to explain in
five or ten minutes. *Using* descriptors like property, sure, that's fine.



But I'm certainly not merely interested for the sake of my talk, I
obtain some satisfaction in learning how things work.  If you can
suggest any references for descriptors which you think are good, I would
be interested.

The definitive explanation of descriptors is here:

https://docs.python.org/3/howto/descriptor.html


Thanks!

Bill






--
https://mail.python.org/mailman/listinfo/python-list


Re: newb question about @property

2017-10-01 Thread Bill

Stephan Houben wrote:

Op 2017-10-01, Bill schreef :

I watched an example on YouTube where someone wrote a simple descriptor
("@Time_it) to output the amount of time that it took ordinary functions
to complete.To be honest, I AM interested in descriptors.

Are you sure you are not confusing deSCRIPTtors and deCORAtors here?


Yet, you are absolutely correct!  Thank you for clarifying! From your 
description, I can see that it was *decorators*, which drew my 
interest.  It appears that *property* is perhaps both a decorator and a 
descriptor, at least when used as in the examples we have been 
discussing.  According to the language grammar, which all newbys like me 
should have handy (remember my ADT acronym from another thread?), 
decorators can be applied to a classdef, a funcdef, or a async_funcdef 
(the latter I assume is a "callback" function definition).   Surely the 
difference in syntax between funcdef and async_funcdef will be revealed 
to me by looking closer at the grammar! : )


Bill



@Time_it

is decorator syntax.

Despite the similarity in the words, there are totally different things.

Descriptors are objects with __get__, and optionally __set__ and
__delete__ methods (i.e. they implement the descriptor protocols).

Decorators aren't really an official type, but loosely speaking these
are any functions which can be applied meaningfully with a single
function or class as argument. Some very mundane functions can be
(ab)used as decorators.

In [1]: @repr
...: def hello():
...: pass
...:

In [2]: hello
Out[2]: ''

Stephan


--
https://mail.python.org/mailman/listinfo/python-list


Re: newb question about @property

2017-10-01 Thread Bill

Steve D'Aprano wrote:

The definitive explanation of descriptors is here:
https://docs.python.org/3/howto/descriptor.html


Thank you!  It is next on my list.   Then I'll try that Circle problem 
you mentioned as an exercise last night!  I don't expect run into any 
difficulties.  : )


--
https://mail.python.org/mailman/listinfo/python-list


Re: newb question about @property

2017-10-02 Thread Bill

Steve D'Aprano wrote:
Circle didn't use any setters, but I could have let you set the 
diameter, which in

turn would set the radius:

circle.radius = 2
assert circle.diameter == 4
circle.diameter == 2  # requires a setter
assert circle.radius == 1

Getting that to work is left as an exercise :-)

It WAS a good exercise!!  I was concerned about "infinite recursion" 
between my two property setters..  Thanks!   Next?  :)


Bill


import math


class Circle(object):
""" Define a circle class with radius and diameter""" def __init__(self, 
radius):
self.radius = radius
self.diameter =2*radius

@property def radius(self):
return self._radius

@radius.setter def radius(self, value):
self._radius = value
self._diameter=2*value

@property def diameter(self):
return self._diameter

@diameter.setter def diameter(self, value):
self._diameter = value
self._radius = value /2 @property def area(self):
return math.pi *self.radius **2 @property def circumference(self):
return 2 * math.pi *self.radius

## Start here ## circle = Circle(1 / math.pi)
print("Area = {:.2f}".format(circle.area))
print("Circumference = {:.2f}".format(circle.circumference))

circle.radius =2 assert circle.diameter ==4 print("Area = 
{:.2f}".format(circle.area))
print("Circumference = {:.2f}".format(circle.circumference))

circle.diameter =2 # requires a setter assert circle.radius ==1 print("Area = 
{:.2f}".format(circle.area))
print("Circumference = {:.2f}".format(circle.circumference))



--
https://mail.python.org/mailman/listinfo/python-list


Re: newb question about @property

2017-10-02 Thread Bill

Chris Angelico wrote:

On Tue, Oct 3, 2017 at 6:23 AM, Larry Hudson via Python-list
 wrote:

On 10/01/2017 03:52 PM, Bill wrote:

Steve D'Aprano wrote:

The definitive explanation of descriptors is here:
https://docs.python.org/3/howto/descriptor.html


Thank you!  It is next on my list.   Then I'll try that Circle problem you
mentioned as an exercise last night!  I don't expect run into any
difficulties.  : )


Except perhaps for your sense of time...  "I'll try" implies the future,
"last night" is the past.:-)   :-)

(Couldn't resist...)

Yes, but "you mentioned" implies the past. I think you have an
operator precedence issue. Kappa

ChrisA



Reading the "definitive explanation of descriptors" took me longer than 
expected..  I am as overly optimistic as any programming person..   ;)


Can you inspire me with a good decorator problem (standard homework 
exercise-level will be fine)?  Otherwise  I will go create one which 
will prints a row of asterisks before and after the call to the original 
function (which I think I should do). But maybe you have something more 
interesting? Or maybe you can refer me to a good source of Python 
problems, so I can bug you less?


Bill
--
https://mail.python.org/mailman/listinfo/python-list


Re: newb question about @property

2017-10-02 Thread Bill

Steve D'Aprano wrote:

There's no need to set the radius and the diameter, as one is completely derived

from the other


Good point; I'm glad I submitted my code for grading.  Sort of a "trick 
question" to ask me to add diameter and then take off points because I 
used it!  ; )


Bill




and the transformation is cheap enough to perform on the fly as
needed.

Consider what happens if, due to a bug or an accident, you end up with a Circle
instance that says the radius is 5 and the diameter is 20. They can't *both* be
right, and


--
https://mail.python.org/mailman/listinfo/python-list


Re: newb question about @property

2017-10-02 Thread Bill

Chris Angelico wrote:

Decorators are fairly straight-forward if you understand higher-order
functions.  

ChrisA



I was just minding my own business, and thought to write my first 
decorator for a simple *recursive* function f.  The decorator WORKS if f 
does not make a call to itself.Otherwise, f seems to have 
"difficulty" calling itself (I get a typerror, f(n) has value 
"NoneType").   What is the explanation for this?  Does f have a new name 
because it has a decorator on it now?


Note: I am not using functools.wraps since I don't yet understand the 
reason I might do that yet (first things first... ).


Thanks!

Bill
--
https://mail.python.org/mailman/listinfo/python-list


Re: newb question about @property

2017-10-02 Thread Bill

Bill wrote:

Chris Angelico wrote:

Decorators are fairly straight-forward if you understand higher-order
functions.  

ChrisA



I was just minding my own business, and thought to write my first 
decorator for a simple *recursive* function f.  The decorator WORKS if 
f does not make a call to itself 
(it really wasn't). 


Using the (PyCharm) debugger, I determined that my inner function that 
was calling my wrapped (Fibonacci sequence) function but wasn't 
returning anything to the invoking environment. I fixed it for the sake 
of a good, if costly, lesson.  Not much of a wrapper, but it "works".  A 
version which merely prints a tab before the function call, instead of a 
row of asterisks produces output which is more interesting to look at.


def wrap(func):
def inner(*args, **kwargs):
print('*'*20)
a= func(*args, **kwargs)
print(a)
print('*'*20)
return a
return inner


Bill

--
https://mail.python.org/mailman/listinfo/python-list


Re: newb question about @property

2017-10-03 Thread Bill

Steve D'Aprano wrote:

On Tue, 3 Oct 2017 06:51 am, Bill wrote:


Can you inspire me with a good decorator problem (standard homework
exercise-level will be fine)?


Here is a nice even dozen problems for you. Please ask for clarification if any
are unclear.


Thank you for sharing the problems on decorators!   I just finished 
reading Bruce Eckels' note on decorators (as well as some of the 
comments left by readers), which you shared a link to, and found the 
whole discussion very informative. If I was to point to two details, the 
analogy of decorator's with macros is helpful to bear in mind, as is the 
remark that "@Wrapper(def f..)" reassigns f to the composition. With the 
latter unstated, the matter can cause confusion!   %-)


Bill





(1) Write a decorator which simply prints a descriptive message and the name of
the decorated function once, when the function is first decorated.

E.g. if you write:

@decorate
def spam(x):
 return x + 1  # for example

print(spam(1))
print(spam(2))


Python should print:

Decorating function spam.
2
3


Note: "spam" must not be hard-coded, it must be taken from the function being
decorated. (Hint: all functions have their name available as func.__name__.)


(2) Modify the decorator from (1) so that calling the wrapped function also
print a descriptive message such as "Calling function spam". The expected
output will be:

Decorating function spam.
Calling function spam.
2
Calling function spam.
3


(3) Write a decorator that checks that the decorated function's first argument
is a non-empty string, raising an appropriate exception if it is not, and lets
through any other arguments unchanged.


(4) Same as above, except the first argument is automatically stripped of
leading and trailing whitespace and forced to uppercase.


(5) Write a decorator which injects the argument 10 into the list of arguments
received by the wrapped function. E.g. if you write:

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

@inject
def sub(a, b):
 return a - b

print(add(5), sub(5))

Python should print "15 5". (And *not* "15 -5".)


(6) [ADVANCED] Modify the decorator in (5) so that it takes an argument telling
it what value to inject into the list of arguments:

@inject(99)
def sub(a, b):
 return a - b

print(sub(5))

will now print "94".


(7) Write a decorator which checks the decorated function's two arguments are
given smallest first, swapping them around if needed.


(8) Write a decorator which prints the name of the wrapped function, its
arguments, and the time, each time the wrapped function is called.


(9) [ADVANCED] Modify the decorator from (8) to take an argument specifying the
path to a file, and use the logging module to log the details to that file
instead of printing them.


(10) Write a decorator which adds an "cache" attribute initialised to an empty
dictionary to the decorated function.


(11) Write a decorator which wraps a class (not function!), and adds a "help"
method to the class which prints a message as shown below. For example:

@addhelp
class Spam:
 pass

@addhelp
class Eggs:
 pass

x = Spam()
x.help()
y = Eggs()
y.help()

will print:

See http://example.com/Spam
See http://example.com/Eggs

(Hint: classes also have a __name__ attribute.)


(12) [ADVANCED] Write a decorator which wraps a class, and applies the decorator
from (10) above to each non-dunder¹ method in the class. That is, after:

@addcaches
class MyClass:
 def foo(self):
 pass
 def bar(self):
 pass

print(MyClass.foo.cache, MyClass.bar.cache)

should print "{} {}".



¹ Remember that dunder methods are those that start with two leading and
trailing underscores: "Double UNDERscore" methods.


* * *


Bruce Eckel has an excellent introduction to Python decorators, from way back
when they were first introduced in 2008. His introduction is notable because:

- he points out explicitly that Python decorators are not the same as
   the Decorator design pattern (I thought they were!);

- he recommends using a class as the decorator, and building the extra
   functionality in object oriented fashion, rather than functional
   programming fashion (this may give an easier introduction to those
   who aren't familiar with functional idioms);

- and he correctly predicted that the introduction of the @ syntactic
   sugar would have a big impact on the way people think about Python
   code.


http://www.artima.com/weblogs/viewpost.jsp?thread=240808

Feel free to read his post before trying the problems I set.





--
https://mail.python.org/mailman/listinfo/python-list


Re: The "loop and a half"

2017-10-03 Thread Bill

Stefan Ram wrote:

   Is this the best way to write a "loop and a half" in Python?


Is your goal brevity or clarity, or something else (for instance, what 
does the code written by the other members of your "team" look 
like--woudn't it be nice if it matched)?


Bill



x = 1
while x:
 x = int( input( "Number (enter 0 to terminate)? " ))
 if x:
 print( f'Square = { x**2 }' )

   In a C-like language, one could write:

while x = int( input( "Number (enter 0 to terminate)? " ))
 print( f'Square = { x**2 }' )

   .



--
https://mail.python.org/mailman/listinfo/python-list


Re: Python community "welcoming" feedback

2017-10-04 Thread Bill

Leam Hall wrote:
A while back I pointed out some challenges for the Python community's 
intake of new coders. Mostly focusing on IRC and the Python e-mail list.


What is the Python e-mail list?

Thanks,
Bill




Several people have stepped up their "welcome" game and I've been very 
impressed with the way things are going.


Great job!

Leam


--
https://mail.python.org/mailman/listinfo/python-list


Re: Creating a Dictionary

2017-10-04 Thread Bill

Stefan Ram wrote:

   One might wish to implement a small language with these commands:

Explain why. What is the advantage?




F - move forward
B - move backward
L - larger stepsize
S - smaller stepsize

   . One could start with the following pseudocode for a dictionary:

{ 'F': lambda: myturtle.forward( s ),
   'B': lambda: myturtle.backward( s ),
   'L': lambda: global s; s *= 2,
   'S': lambda: global s; s /= 2 }

   . But lambda-expressions cannot contain statements.

   In real Python one could write something like (untested):

def f():
 myturtle.forward( s )

def b():
 myturtle.backward( s )

def l():
 global siz
 size *= 2

def s():
 global siz
 size /= 2

{ 'F': f,
   'B': b,
   'L': l,
   'S': s }

   . Is this more readable or less readable?

   Any other suggestions?



--
https://mail.python.org/mailman/listinfo/python-list


Re: Introducing the "for" loop

2017-10-05 Thread Bill

Stefan Ram wrote:

"ROGER GRAYDON CHRISTMAN"  writes:

On Wed, Oct 4, 2017 22:42 Stefan Ram (r...@zedat.fu-berlin.de) wrote:
Steve D'Aprano  writes:

So, "bottom-up" in this case means: iterators should be
taught before for-loops.
Why?

The easy answer here is to not use the range in the first for loop.

   I never intended to use »range«. But I also will not use lists.

   Very early in the course, I teach numeric and string literals:

1, 2.3, 'abc'

   then come operators, functions and »if«, »while« and »try«.
   But neither »range« nor lists have been shown so far.


As long as I have two teachers here, which textbooks are you using? I am 
hoping to teach a college course in Python next fall.


Thanks,
Bill





   The basic course may already and there after about 12 - 18 hours.
   (This time includes many exercises in the classroom.)

   But if I have time to introduce »for«, I'll do it as follows
   at this point in the course:

   

   We want to walk through (traverse) a string
   character-by-character:

   To do this we need a walker. A walker can be
   obtained using »iter«:

|>>> walker = iter( 'abc' )

   Now, we can get character after character from the walker
   using »next« (transcript simplified):

|>>> next( walker )
|'a'
|>>> next( walker )
|'b'
|>>> next( walker )
|'c'
|>>> next( walker )
|StopIteration

   We can use »while« to automate this:

def example():
 walker = iter( 'abc' )
 try:
 while True:
 print( next( walker ))
 except StopIteration:
 pass

   A walker also is known as an /iterator/.

   An object, one can get an iterator from
   is called an /iterable object/.

   Strings are iterable objects.

   This for-loop does just what our previous
   while-loop did:

def example():
 for ch in 'abc':
 print( ch )

   It gets an iterator from »'abc'« and then does the suite
   repeatedly with »ch« being the result of a each »next«
   call until StopIteration.

   

   No »range«, no list.

   (Yes, »print('\n'.join('abc'))« can do the same and will
   be shown later in the course if there is still time.)



--
https://mail.python.org/mailman/listinfo/python-list


Re: Lies in education [was Re: The "loop and a half"]

2017-10-05 Thread Bill

Marko Rauhamaa wrote:

That's good advice, but it's not all that dangerous to express off-topic
statements in this newsgroup.



It may not be "dangerous", but I find it a little annoying.  I wasn't 
going to say anything, but now you are bringing it up explicitly.



--
https://mail.python.org/mailman/listinfo/python-list


Re: why does memory consumption keep growing?

2017-10-05 Thread Bill

Fetchinson . wrote:

Hi folks,

I have a rather simple program which cycles through a bunch of files,
does some operation on them, and then quits. There are 500 files
involved and each operation takes about 5-10 MB of memory. As you'll
see I tried to make every attempt at removing everything at the end of
each cycle so that memory consumption doesn't grow as the for loop
progresses, but it still does.

import os

for f in os.listdir( '.' ):

 x = [ ]

 for ( i, line ) in enumerate( open( f ) ):

 import mystuff
 x.append( mystuff.expensive_stuff( line ) )
 del mystuff

 import mystuff
 mystuff.some_more_expensive_stuff( x )
 del mystuff
 del x


What can be the reason? I understand that mystuff might be leaky, but
if I delete it, doesn't that mean that whatever memory was allocated
is freed? Similary x is deleted so that can't possibly make the memory
consumption go up.

Any hint would be much appreciated,
Daniel



Try calling the garbage collector explicitly.

--
https://mail.python.org/mailman/listinfo/python-list


Re: Lies in education [was Re: The "loop and a half"]

2017-10-10 Thread Bill

Rhodri James wrote:

On 09/10/17 20:06, Stefan Ram wrote:

r...@zedat.fu-berlin.de (Stefan Ram) writes:

Steve D'Aprano  writes:
At various stages of education, we teach many lies-to-children, 
including:

Many of those lies can be perfectly true in some sense.
I pick some examples:


   Another noun phrase with "lie" is "white lie".

   In his book about programming, Bjarne Stroustrup writes:

|We try hard to avoid "white lies"; that is, we refrain from
|oversimplified explanations that are clear and easy to
|understand, but not true in the context of real languages and
|real problems.


That would go a long way to explaining why I tried and failed to learn 
C++ three times from Stroustrup's books.


He is surely one of the best authors in computer science (at least based 
upon "The C++ Programming Language", 3rd ed.).  He indicates that he 
assumes that the reader has some experience developing serious 
software.  Beazley's, "Python: Essential Reference" is one of the best 
books I've seen since. It doesn't have the same depth, but it (too) 
provides articulate answers, head-on. Both books have 5-star rankings on 
Amazon.com. That doesn't mean that either of them is right for 
everybody. Come back to Stroustrup's book "after" you learn C++ 
somewhere else, and maybe you'll enjoy it more.


Bill

--
https://mail.python.org/mailman/listinfo/python-list


Re: Lies in education [was Re: The "loop and a half"]

2017-10-10 Thread Bill

Steve D'Aprano wrote:

On Tue, 10 Oct 2017 06:06 am, Stefan Ram wrote:


In his book about programming, Bjarne Stroustrup writes:

|We try hard to avoid "white lies"; that is, we refrain from
|oversimplified explanations that are clear and easy to
|understand, but not true in the context of real languages and
|real problems.


Bjarne Stroustrup is famous for designing one of the most heavyweight,
baraque, hard-to-understand, difficult-to-use programming languages in common
use. While C++ has many excellent features, and is constrained by the need to
be compatible with C, I don't think many people believe that it is a
well-designed language.



It is a well-designed language.  It is and was carefully thought out. 
One could argue that there are perhaps "too many ways" to do a given 
thing in Python (one could say it's features are "not orthogonal"). I'm 
sure you are familiar with where the language drew its name.   I'm not 
here to "cast stones", I like Python. I just think that you shouldn't 
cast stones at C/C++.  People started programming in C in the late 70's, 
and before that some were programming in B ("B Programming Language"), 
if I recall correctly. Python generally runs "further ways from the 
hardware" than these other languages, and in some sense, it still would, 
*even if* you were able to statically compile it to machine language. To 
me if feels like Python runs like an application.   I don't wish to 
debate this as I have other needs this week. But I felt compelled to try 
to explain why maybe you shouldn't be casting stones at C/C++.


One thing you didn't bring up at all, is that the audiences for the 
languages appears to be different. You still need folks who can encode 
data structures and write device drivers, from scratch.  And "woe" if 
you need performance, such as applications involving AI.


Cheers,
Bill


But even if it were the best language in the world, and Stroustrup the
greatest language designer in the history of computing, what makes you think
that he knows anything about teaching?




--
https://mail.python.org/mailman/listinfo/python-list


Re: Lies in education [was Re: The "loop and a half"]

2017-10-10 Thread Bill

Dennis Lee Bieber wrote:

On Tue, 10 Oct 2017 20:48:26 -0400, Bill 
declaimed the following:


cast stones at C/C++.  People started programming in C in the late 70's,
and before that some were programming in B ("B Programming Language"),

Preceded by BCPL (which leads to the joke that the language that
supplants C will be named P)


PL-I has already been taken.  That is a pretty free-wheeling language 
compared to Fortran, where, IIRC, you had to start in the 7th column. 
Oops, hand me another punch card... :)


--
https://mail.python.org/mailman/listinfo/python-list


Re: Lies in education [was Re: The "loop and a half"]

2017-10-11 Thread Bill

Grant Edwards wrote:

On 2017-10-11, Bill  wrote:



[...] I'm not here to "cast stones", I like Python. I just think
that you shouldn't cast stones at C/C++.

Not while PHP exists.  There aren't enough stones in the world...



PHP seems (seemed?) popular for laying out web pages.  Are their vastly 
superior options? I'm a little naive in this matter, thus my question.

--
https://mail.python.org/mailman/listinfo/python-list


Re: Lies in education [was Re: The "loop and a half"]

2017-10-11 Thread Bill

Mikhail V wrote:

[...] I'm not here to "cast stones", I like Python. I just think
that you shouldn't cast stones at C/C++.

Not while PHP exists.  There aren't enough stones in the world...


PHP seems (seemed?) popular for laying out web pages.  Are their vastly
superior options?

Python? Superior syntax for sure


I believe that.  What accounts for the popularity of PHP then?
--
https://mail.python.org/mailman/listinfo/python-list


Re: Lies in education [was Re: The "loop and a half"]

2017-10-11 Thread Bill

Grant Edwards wrote:

On 2017-10-11, Bill  wrote:

Grant Edwards wrote:

On 2017-10-11, Bill  wrote:



[...] I'm not here to "cast stones", I like Python. I just think
that you shouldn't cast stones at C/C++.

Not while PHP exists.  There aren't enough stones in the world...


PHP seems (seemed?) popular for laying out web pages.

It's not really used for "laying out" web pages.  Thats what HTML and
CSS do.  PHP is for server-side generation of dynamic content and
handling of submitted forms and uploaded data.


Thank you. I DO appreciate learning about the correct terminology.


--
https://mail.python.org/mailman/listinfo/python-list


Re: Lies in education [was Re: The "loop and a half"]

2017-10-12 Thread Bill

Marko Rauhamaa wrote:

Grant Edwards :


I like [const qualifiers] in C because it allows the linker to place
them in ROM with the code. It also _sometimes_ provides useful
diagnostics when you pass a pointer to something which shouldn't be
modified to something that is going to try to modify it.

Unfortunately, "const" is so tacky in practice that the language and the
standard libraries have rendered it useless.

One example is the surprising fact that string literals in C are "char
*" and not "const char *".


If not, you couldn't pass a string literal to a function having prototype
void f(char *s);
Of course, if f tries to modify *s, there will be a run time error as 
character string literals are stored in a "special place", and are not 
mutable. This improves performance.



--
https://mail.python.org/mailman/listinfo/python-list


Re: I used list, def. why li += [100,200] , and li = li + [100,200] is different

2017-10-23 Thread Bill

Rob Gaddi wrote:

On 10/23/2017 09:29 AM, 임현준 wrote:

I am a Korean student, and I am a beginner in English and Python.;(

I can't understand about this def

If I want to print

[1,2,3,4,5]
[1,2,3,4,5,100,200]

I will make code like this, and I can understand code.


def modify(li):
  li += [100,200]

list = [1,2,3,4,5]
print(list)
modify(list)
print(list)


BUT, when I make code like this.

I will make code like this, and I can understand code.


def modify(li):
  li = li + [100,200]

list = [1,2,3,4,5]
print(list)
modify(list)
print(list)



python print

[1,2,3,4,5]
[1,2,3,4,5]

why 'li+= [100,200]'and 'li = li + [100,200]' 's print is different
please help me



Lists are mutable, they can be changed.  Your call to += is equivalent 
to a call to li.extend([100, 200]), which changes the single existing 
object pointed to by the "li" reference.  The second time, however, 
you take the existing value that "li" refers to [1,2,3,4,5], create a 
new object that is ([1,2,3,4,5] + [100,200]), and reassign the local 
reference "li" to point to that new object.  Then your function ends, 
"li" goes out of scope, nothing points to that newly created object 
and it gets lost.





The problem and both solutions are great!  Thanks for posting!

Bill
--
https://mail.python.org/mailman/listinfo/python-list


Re: Let's talk about debuggers!

2017-10-25 Thread Bill

Fabien wrote:

On 10/25/2017 03:07 PM, Thomas Jollans wrote:

What options are there for Python (that work)?


PyCharm's debugger is fine (also available in the community edition)

+1



Cheers,

Fabien


--
https://mail.python.org/mailman/listinfo/python-list


Re: Getting started with python

2017-10-30 Thread Bill

subhendu.pand...@gmail.com wrote:

Hi,

Could you please help me with the below if possible:


Possible and reasonable are two different things.  Why don't you try 
some web searches and try to answer some of your own questions.  I offer 
this advice as a Python newbe myself.


Bill




1. Best site to go ahead for python.
2. How python is different from other languages and future scope of it.
3. Tasks that are getting done using python in present.
4. Link where I can be able to get python videos, ebooks from basics to expert 
level free.

Thanks
Subhendu


--
https://mail.python.org/mailman/listinfo/python-list


Re: Easiest way to access C module in Python

2017-11-06 Thread Bill

John Pote wrote:

Hi all,
I have successfully used Python to perform unit and integration tests 
in the past and I'd like to do the same for some C modules I'm working 
with at work. There seem to be a number of ways of doing this but 
being busy at work and home I looking for the approach with the least 
learning curve.


I don't want to add the C modules into the CPython build itself as 
I've never done this and at work it's a real pain getting admin rights 
to do this, and when you do it lasts just 24 hours. The C modules are 
likely to change frequently as bugs are found and features added.


The other option I'm considering is to use sockets and write a C 
wrapper round the C modules I want to test. This has the advantage for 
me that I know about sockets from Python & C points of view and I get 
complete control of the C compile process. This may be important as 
the C modules come from an embedded project and I don't want to change 
them in any way.


Are there any other approachs to this problem?
I'll be using Python 3.5 (work) and 3.6 (home).
Feedback appriciated.



Install Oracle's "Virtual Box" software on your computer.  It's free. 
Then install a version of Linux on it (or something else, if you 
prefer).  Whatever you do, if you don't like it, you can replace your 
installation in a matter of minutes.

--
https://mail.python.org/mailman/listinfo/python-list


Re: Python homework

2017-12-06 Thread Bill
I think carelessness in choosing variable names may be at the root of 
the problem.



nick.martin...@aol.com wrote:

I have a question on my homework. My homework is to write a program in which 
the computer simulates the rolling of a die 50
times and then prints
(i). the most frequent side of the die
(ii). the average die value of all rolls.
I wrote the program so it says the most frequent number out of all the rolls for example 
(12,4,6,14,10,4) and will print out "14" instead of 4 like I need.
This is what I have so far:
import random

def rollDie(number):
 rolls = [0] * 6
 for i in range(0, number):
 roll=int(random.randint(1,6))
 rolls[roll - 1] += 1
 return rolls

if __name__ == "__main__":
 result = rollDie(50)
 print (result)
 print(max(result))


--
https://mail.python.org/mailman/listinfo/python-list


Re: Processing Game Help

2017-12-10 Thread Bill

Lauren Porter wrote:

Hello all! I've been trying to create a game in Python Processing where a 
spaceship moves horizontally in order to miss a collision with an asteroid. I'm 
having difficulty making it so that the game quits when an asteroid hits the 
spaceship, could anybody help? Here is my code.


The code looks rather "naked" with any sort of documentation.
Do you want to ask us to figure out how it is supposed to work in order 
to help you?
My debugging suggestion is "print, print, print!" so you can follow what 
your code is doing.
I find that the sooner I start doing that, the sooner my debugging 
session is over.  Good luck!


Bill


As you can see, I tried using globals in order use variables from previous 
classes, but nothing has worked. For this specific approach, no error message 
popped up, but nothing happened either. Thanks so much!

COLORS = {"black":"#00", "white":"#FF",
   "red":"#FF", "green":"#00FF00",
   "blue":"#D1F5FF", "yellow":"#00",
   "orange":"#FFA500", "hendrixorange":"#F58025",
   "purple":"#9B30FF", "gray":"#808080", "lightgray": "#CACACA",
   "darkgray":"#A9A9A9"}
import random
asteroid = []
spaceship = []
stars = []
justPressed = False
aX = 0
aY = 0
x = 0
y = 0

def setup():
 global aX, aY, X, Y
 size(640, 480)
 for s in range(1):
 X = 320
 Y = 440
 spaceship.append(Space(X, Y, COLORS["orange"]))
 for a in range(4):
 aX = random.randint(0, 640)
 aY = 0
 asteroid.append(Asteroid(aX, aY, COLORS["orange"]))
 for d in range(100):
 randX = random.randint(0, 640)
 randY = random.randint(0, 480)
 stars.append(Star(randX, randY, COLORS["orange"]))



class Space:
 def __init__(self, x, y, color):
 self.x = x
 self.y = y
 self.color = color

 def spaceship(self):
 fill(COLORS["blue"])
 stroke(COLORS["white"])
 ellipse(self.x, self.y, 75, 75) #body
 fill(COLORS["green"])
 fill(COLORS["gray"])
 stroke(COLORS["green"])
 ellipse(self.x, self.y + 20, 120, 35)
 stroke(COLORS["orange"])
 fill(COLORS["purple"])
 ellipse(self.x, self.y + 20, 10, 10)
 ellipse(self.x + 30, self.y + 20, 10, 10)
 ellipse(self.x - 30, self.y + 20, 10, 10)
 
 def move(self, dx, dy):

 self.x += dx
 self.y += dy

class Asteroid:
 def __init__(self, x, y, color):
 self.x = x
 self.y = y
 self.color = color
 
 def update(self):

 self.velx = 0
 self.vely = random.randint(1, 5)
 self.x += self.velx
 self.y += self.vely
 if self.y > 480:
 self.y = 0
 self.x = random.randint(1,640)
 
 def asteroid(self):

 fill(COLORS["lightgray"])
 stroke(COLORS["white"])
 ellipse(self.x, self.y, 50, 50)
 fill(COLORS["gray"])
 ellipse(self.x +15, self.y + 6, 15, 15)
 ellipse(self.x -12, self.y + 7, 10, 10)
 ellipse(self.x + 5, self.y - 13, 11, 11)
 ellipse(self.x - 12, self.y - 9, 7, 7)
 ellipse(self.x + 2, self.y + 18, 7, 7)
 
class Star:

 def __init__(self, x, y, color):
 self.x = x
 self.y = y
 self.color = color

 def star(self):
 fill(COLORS["white"])
 ellipse(self.x, self.y, 3, 3)


def draw():
 global justPressed
 background(COLORS["black"])
 for f in stars:
 f.star()
 for f in spaceship:
 f.spaceship()
 if f.x < 60:
 f.move(3, 0)
 elif f.x > 580:
 f.move(-3, 0)
 elif justPressed :
 if key == 'd':
 f.move(3, 0)
 elif key == 'a':
 f.move(-3, 0)
 for f in asteroid:
 f.asteroid()
 f.update()
 #collision detection 'for' loop
 distance = sqrt(((aX - X)**2) + ((aY - Y)**2))
 for f in asteroid:
 if distance < 62.5:
 background(COLORS["red"])
 
 
def keyTyped():

 global justPressed
 justPressed = True
 print("typed", key)
 
def keyPressed():

 global justPressed
 justPressed = True
 print("pressed", key)



--
https://mail.python.org/mailman/listinfo/python-list


Re: Python Learning

2017-12-15 Thread Bill

Varun R wrote:

Hi All,

I'm new to programming, can anyone guide me, how to start learning python 
programming language,...plz suggest some books also.

Thanks all


Are you sure you want to learn Python first?
Python does enough things "behind the scene"
that it makes me question the wisdom of that.
Other points of view are welcome, of course.
Learning the primitives of C++ first, may make for an easier transition.
Surely this has been discussed before?
--
https://mail.python.org/mailman/listinfo/python-list


Re: Python Learning

2017-12-15 Thread Bill

Chris Angelico wrote:

On Sat, Dec 16, 2017 at 8:51 AM, Bill  wrote:

Varun R wrote:

Hi All,

I'm new to programming, can anyone guide me, how to start learning python
programming language,...plz suggest some books also.

Thanks all


Are you sure you want to learn Python first?
Python does enough things "behind the scene"
that it makes me question the wisdom of that.
Other points of view are welcome, of course.
Learning the primitives of C++ first, may make for an easier transition.
Surely this has been discussed before?

On the contrary, that makes Python an *excellent* first language. We
don't force people to learn about the chemistry of petrochemical
combustion before letting them learn how to drive a car; we don't make
people understand TCP/IP networking before they're allowed to type
something into Google. And if you DO want people to start off with a
lower-level language, why C++? Why not machine code (or at least
assembly code), since that's what the CPU actually executes?


Most decent introductions to C++ discuss machine language (it helps make 
sense of compilation).
As you indirectly suggest, learning is something of a circular process, 
so it really doesn't make that much difference where one starts, just 
"Do It!".  :  )


--
https://mail.python.org/mailman/listinfo/python-list


Re: Python Learning

2017-12-16 Thread Bill

Rustom Mody (Rustom Mody) wrote:

On Saturday, December 16, 2017 at 9:45:17 AM UTC+5:30, Bill wrote:

Chris Angelico wrote:

On Sat, Dec 16, 2017 at 8:51 AM, Bill wrote:

Varun R wrote:

Hi All,

I'm new to programming, can anyone guide me, how to start learning python
programming language,...plz suggest some books also.

Thanks all

Are you sure you want to learn Python first?
Python does enough things "behind the scene"
that it makes me question the wisdom of that.
Other points of view are welcome, of course.
Learning the primitives of C++ first, may make for an easier transition.
Surely this has been discussed before?

On the contrary, that makes Python an *excellent* first language. We
don't force people to learn about the chemistry of petrochemical
combustion before letting them learn how to drive a car; we don't make
people understand TCP/IP networking before they're allowed to type
something into Google. And if you DO want people to start off with a
lower-level language, why C++? Why not machine code (or at least
assembly code), since that's what the CPU actually executes?

Most decent introductions to C++ discuss machine language (it helps make
sense of compilation).
As you indirectly suggest, learning is something of a circular process,
so it really doesn't make that much difference where one starts, just
"Do It!".  :  )

Reallyâ¿?
https://en.wikipedia.org/wiki/Principles_of_learning#Primacy



You would give precedence to something written on a wikipedia page over 
your experience?
In our current context, we are talking about self-learning where one is 
one's own teacher. To my mind, if one gets that part right, one doesn't 
need to worry about the other types. I learned a great deal from BYTE 
magazine and before that Popular Electronics. Computer technology is so 
ubiquitous today, that the interested person one need only grab hold of 
something and start learning. YouTube for instance, offers a plethora of 
places to "begin".  I tell students, that if they have the math behind 
them, then the doors of science will be open to them. In my experience, 
if they do not have the basic (~pre-calc) math behind them, then 
learning from a textbook on a programming language, say,  may be a bit 
beyond them.

--
https://mail.python.org/mailman/listinfo/python-list


Re: Python Learning

2017-12-16 Thread Bill

Gregory Ewing wrote:

Bill wrote:
In my experience, if they do not have the basic (~pre-calc) math 
behind them, then learning from a textbook on a programming language, 
say,  may be a bit beyond them.


Very little mathematical *knowledge* is needed to get started
with programming. You can do a lot of useful things in Python
without even using any arithmetic.

What does seem to correlate is that if you're the sort of
person who finds maths interesting and fun to play with, you're
also likely to take to programming easily. The same kind of
logical thought processes are involved.



I think we are talking about the same people.
But in college, the prerequisite of "at least co-enrolled in pre-calc", 
turned out to be the right one (based upon quite a lot of teaching 
experience).

--
https://mail.python.org/mailman/listinfo/python-list


Re: Python Learning

2017-12-17 Thread Bill

Rustom Mody wrote:

In response to


Rustom Mody wrote:

On Saturday, December 16, 2017 at 9:45:17 AM UTC+5:30, Bill wrote:

so it really doesn't make that much difference where one starts, just
"Do It!".  :  )

Really ¿?
https://en.wikipedia.org/wiki/Principles_of_learning#Primacy


On Sunday, December 17, 2017 Bill wrote:

You would give precedence to something written on a wikipedia page over
your experience?

Bill also wrote:

…in college, the prerequisite of "at least co-enrolled in pre-calc",
turned out to be the right one (based upon quite a lot of teaching
experience).

So… I dont understand where you are coming from:
Is there such a thing as a “learning curve” or not?


The point is that it takes a certain amount of what is referred to as 
"mathematical maturity" (not mathematical knowledge) to digest a book 
concerning computer programming. In my years of teaching experience, 
students who came to college without the equivalent of "college algebra" 
were under-prepared for what was expected of them. This is not just an 
opinion, it's a fact. Of course, you could argue that a student who 
arrives at college needing to take college algebra is of a certain 
category. In your words, they are not yet ready to face any sort of 
(steep) learning curve.


Bill
--
https://mail.python.org/mailman/listinfo/python-list


Re: Python Learning

2017-12-17 Thread Bill

Larry Martell wrote:

So, your experience is that the style of learning you offer is

unsuitable to anyone who doesn't have some background in algebra.
That's fine. For your course, you set the prereqs. But that's not the
only way for someone to get into coding. You do NOT have to go to
college before you start creating software. That is also not an
opinion; it's a fact backed by a number of proven instances (myself
included).


You might benefit by a course in logic.  I never said that was the only 
way to learn. I learned (BASIC) in 8th grade too.



I started coding when I was 16, in 1975. I wrote a downhill skiing
game in basic, which I had taught to myself. I went to collage when I
was 17, and I had taught myself FORTRAN and I tested out of the class.


--
https://mail.python.org/mailman/listinfo/python-list


Re: Python Learning

2017-12-17 Thread Bill

Gregory Ewing wrote:

Bill wrote:
In my years of teaching experience, students who came to college 
without the equivalent of "college algebra" were under-prepared for 
what was expected of them.


This could be simply because it weeds out people who aren't
good at the required style of thinking. 


I think that's absolutely true.  If someone gets out of high school and 
doesn't understand college algebra (~8th grade math), they come into a 
programming class with an inherent disadvantage. They "can't understand" 
the book, just like they "couldn't" understand their math book.





If that's true,
anything that exercises mathematical thinking should have
the same effect. There just doesn't happen to be anything
else in the mainstream education curriculum that does that.



--
https://mail.python.org/mailman/listinfo/python-list


Re: Python Learning

2017-12-17 Thread Bill

Chris Angelico wrote:

On Mon, Dec 18, 2017 at 6:51 AM, Bill  wrote:

The point is that it takes a certain amount of what is referred to as
"mathematical maturity" (not mathematical knowledge) to digest a book
concerning computer programming.

Emphasis on *a book*.


In my years of teaching experience,
students who came to college without the equivalent of "college algebra"
were under-prepared for what was expected of them. This is not just an
opinion, it's a fact.

So, your experience is that the style of learning you offer is
unsuitable to anyone who doesn't have some background in algebra. That's fine. 
For your course, you set the prereqs.


I never said that they needed any knowledge of algebra.  But if they 
don't understand the logic behind an inequality, for instance, then may 
run into some trouble.

--
https://mail.python.org/mailman/listinfo/python-list


Re: Python Learning

2017-12-17 Thread Bill

Chris Angelico wrote:

On Mon, Dec 18, 2017 at 11:31 AM, Bill  wrote:

Larry Martell wrote:

So, your experience is that the style of learning you offer is

unsuitable to anyone who doesn't have some background in algebra.
That's fine. For your course, you set the prereqs. But that's not the
only way for someone to get into coding. You do NOT have to go to
college before you start creating software. That is also not an
opinion; it's a fact backed by a number of proven instances (myself
included).


You might benefit by a course in logic.  I never said that was the only way
to learn. I learned (BASIC) in 8th grade too.


You said earlier:


In my years of teaching experience, students who came to college without
the equivalent of "college algebra" were under-prepared for what was
expected of them. This is not just an opinion, it's a fact.

If you want to qualify that by saying that coming to college is not
the only way to learn programming, you'd better say so, because
otherwise, the tone of what you're saying says that students NEED
algebra prior to learning a programming language.


I tried pretty hard not to say that. I said they needed some 
"mathematical sophistication"--not actual mathematics.  My error was 
using that expression among an audience not so familiar with that 
terminology. That said, I think I would have a hard time explaining 
polymorphism and vtables to a student who had not grasped the 
distributive property of multiplication over addition.

You can try, and let me know how it goes for you... I've been there.

Bill




Logic isn't the problem here. Clarity of language is. Watch your
implications if you don't want to be misunderstood.

ChrisA


--
https://mail.python.org/mailman/listinfo/python-list


Re: Python Learning

2017-12-17 Thread Bill

Chris Angelico wrote:


I don't know about vtables as needing to be in ANY programming course.
They're part of a "let's dive into the internals of C++" course. You
certainly don't need them to understand how things work in Python,
because they don't exist; and I'm doubtful that you need to explain
them even to C++ programmers.


I guess "need to" is a relative thing. You can drive a car without know 
how one works. You can use functions with little knowledge of a run-time 
stack. You can avoid recursion if you are scared of it. And you can 
totally avoid functions if you are scared of them. And who needs 
documentation...seems like a big waste of time! Programmers don't need 
to know how to write, do they?  Ask some programmers that just taught 
themselves, and they will tell you!


After reading, writing, and arithmetic, then perhaps programming.




Polymorphism... actually, I could explain that to a three year old.

"Eat your broccoli"

"Eat your dessert"

See? Polymorphism. The same operation being done to different things
and having different results.

ChrisA


--
https://mail.python.org/mailman/listinfo/python-list


Re: Python Learning

2017-12-17 Thread Bill

Chris Angelico wrote:

I don't know about vtables as needing to be in ANY programming course.
They're part of a "let's dive into the internals of C++" course. You
certainly don't need them to understand how things work in Python,
because they don't exist; and I'm doubtful that you need to explain
them even to C++ programmers.


Then how are you going to explain dynamic_cast?



Polymorphism... actually, I could explain that to a three year old.

"Eat your broccoli"

"Eat your dessert"

See? Polymorphism. The same operation being done to different things
and having different results.

ChrisA


--
https://mail.python.org/mailman/listinfo/python-list


Re: Python Learning

2017-12-17 Thread Bill

Chris Angelico wrote:


I agree with some of that, but you then take it to absurdity. You most
certainly CAN drive a car without knowing how one works; in fact, with
this century's cars, I think that's very much the case. How many
people REALLY know what happens when you push the accelerator pedal,
and how that makes the car go faster? Originally, it would actually
open a valve and allow more fuel into the engine; now, it's all
managed by a computer. So how much can you really understand of how it
works?


You can understand the "systems" which comprise your car. Engine, 
Cooling, braking, transmission, exhaust, etc.  And you can similarly 
understand the systems which comprise the workings of your computer 
program. As it happens, I've been studying electronics lately.
In answer to your question, there is an "invisible line" between 
hardware and software which most people don't generally cross. As 
another response to your question, try to master all of the features of 
the emacs editor. Personally, I've never felt motivated enough to do so.





You can certainly use functions without knowing details of the
run-time stack, though you'll need at least SOME comprehension of it.

Avoiding functions and documentation, though, now you're just being ridiculous.

ChrisA


--
https://mail.python.org/mailman/listinfo/python-list


Re: Python Learning

2017-12-17 Thread Bill

Chris Angelico wrote:

On Mon, Dec 18, 2017 at 4:04 PM, Chris Angelico  wrote:

On Mon, Dec 18, 2017 at 3:54 PM, Bill  wrote:

Chris Angelico wrote:

I don't know about vtables as needing to be in ANY programming course.
They're part of a "let's dive into the internals of C++" course. You
certainly don't need them to understand how things work in Python,
because they don't exist; and I'm doubtful that you need to explain
them even to C++ programmers.


Then how are you going to explain dynamic_cast?


I wouldn't. I'd teach Python to beginning programmers. C++ is not a
good first language.

And even for C++ programners, you can go a pretty long way without dynamic_cast.
You either know it exists, and what it can do for you, or you don't.  If 
you want to teach a 2nd course in C++, and leave out vtables and 
dynamic_cast, I don't have a problem with that. If you always choose the 
lowest common denominator, your class may not be that interesting.  I 
told my students that my goal was for them was to learn how to learn so 
that they "didn't need me".




ChrisA


--
https://mail.python.org/mailman/listinfo/python-list


Re: Python Learning

2017-12-18 Thread Bill

Chris Angelico wrote:

On Sun, Dec 17, 2017 at 12:01 PM, Bill  wrote:


I think we are talking about the same people.
But in college, the prerequisite of "at least co-enrolled in pre-calc",
turned out to be the right one (based upon quite a lot of teaching
experience).

Fortunately for the programming world, college isn't when everyone
starts. I started coding at six years old. Should I have waited till I
had some pre-calc before getting into programming?


It probably wouldn't have hurt if you had co-enrolled in it.  ;)
And add an English course too to help you to write suitable documentation!
I would think a 6 year old would have priorities above coding--what's 
the hurry?


Bill



ChrisA


--
https://mail.python.org/mailman/listinfo/python-list


Re: Python Learning

2017-12-18 Thread Bill

Christian Gollwitzer wrote:


You don't need to explain a vtable to explain dynamic_cast. Only if 
you want to become a compiler writer. It is not even required, vtables 
are just the most common implementation.


dynamic_cast simply checks if the actual object that the pointer 
points to is an instance of a derived class, and then casts it into 
that. You could "explain" it with the following pseudo-code


template 
T* dynamic_cast(base *input) {
if (isinstanceof(base, *input)) { return (T*)input; }
else { return nullptr; }
}

How that works (particularly the "isinstanceof") is not the business 
of the programmer - it is sufficient to know that the compiler 
somewhere stores this information for every object.


Christian


With that, the students would "boo you off the stage!"... and maybe 
accuse you of being a "know it all".  ; )The point of college is 
more about teaching students to think rather than in being efficient.  I 
have little doubt that a tech school could "get through everything" much 
faster.


Bill
--
https://mail.python.org/mailman/listinfo/python-list


Re: adding elif to for

2017-12-19 Thread Bill

bob gailer wrote:

Has any thought been given to adding elif to the for statement?


I don't think it is a good idea because it needlessly, from my point of 
view, embeds too much complexity into a single construct (making it more 
difficult to maintain, for instance). That's what language designer's do 
though--they kick ideas like that around.  If you have a great idea, 
maybe propose a new language.




for x in foo:
if y: break
elif a==b:
something
else:
something else

as a shortcut to:
for x in foo:
if y: break
else:
if a==b:
something
else:
something else
bob gailer


--
https://mail.python.org/mailman/listinfo/python-list


Re: correctness proof for alpha-beta algorithm

2017-12-20 Thread Bill

namenobodywa...@gmail.com wrote:

On Tuesday, December 19, 2017 at 3:28:39 PM UTC-8, Steve D'Aprano wrote:


Does this have anything specifically to do with Python programming?

i'm working on a game-playing script (ie: in python), i want to incorporate 
pruning into my search algorithm, and i'd like to understand why it works; i'm 
not sure if that counts


Based upon your posts, I think you should just write your own. Then you 
can be sure that it will work. That's better than working with something 
that you don't understand.



--
https://mail.python.org/mailman/listinfo/python-list


Re: correctness proof for alpha-beta algorithm

2017-12-20 Thread Bill

Steve D'Aprano wrote:

On Thu, 21 Dec 2017 08:37 am, Bill wrote:


namenobodywa...@gmail.com wrote:

On Tuesday, December 19, 2017 at 3:28:39 PM UTC-8, Steve D'Aprano wrote:


Does this have anything specifically to do with Python programming?

i'm working on a game-playing script (ie: in python), i want to incorporate
pruning into my search algorithm, and i'd like to understand why it works;
i'm not sure if that counts

Based upon your posts, I think you should just write your own. Then you
can be sure that it will work.

How long did you say you've been programming? Perhaps you've heard of
something we in the programming world call "bugs".


You're supposed to get rid those those.  Use Raid!  : )




--
https://mail.python.org/mailman/listinfo/python-list


Re: Are the critiques in "All the things I hate about Python" valid?

2018-02-16 Thread Bill

boB Stepp wrote:

This article is written by Nathan Murthy, a staff software engineer at
Tesla.  The article is found at:
https://medium.com/@natemurthy/all-the-things-i-hate-about-python-5c5ff5fda95e

Apparently he chose his article title as "click bait".  Apparently he
does not really hate Python (So he says.).  His leader paragraph is:

"Python is viewed as a ubiquitous programming language; however, its
design limits its potential as a reliable and high performance systems
language.


Python is simply not a high performance system language, but it has 
other virtues. You would not likely choose Python for a sophisticated 
distributed computing application, but not everyone needs to write a 
sophisticated distributed computing application.  I believe those that 
do, will be conscientious enough to choose an appropriate tool.






Unfortunately, not every developer is aware of its
limitations."

As I currently do not have the necessary technical knowledge to
properly evaluate his claims, I thought I would ask those of you who
do.  I have neither the knowledge or boB-hours to write a large
distributed system code base, but I am curious if Python is truly
limited for doing these in the ways he claims.

BTW, I am not trying to start (another) heated, emotional thread.  You
guys do sometimes get carried away!  I honestly just what to know the
truth of the matters out of my continuing to learn Python.  I suspect
there is probably some truth in his claims, but I am not sure if he is
taking things out of their proper application contexts or not.

Thanks!


--
https://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   6   7   >