Re: The "loop and a half"

2017-10-03 Thread Larry Hudson via Python-list

On 10/03/2017 10:29 AM, Stefan Ram wrote:

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

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 }' )



This does not answer your question and is only somewhat related.

Here is a generic number input function that I wrote for my own (hobby-programmer) use.  The 
docstring explains it.



def get_num(prmt, lo=None, hi=None, dflt=None, flt=False, abrt=False):
"""Get a number from the console

Parameters:
prmt:   The prompt to be used with the input function, required.
lo: The minimum permissible value, or None if no minimum (the 
default)
hi: The maximum permissible value, or None if no maximum (the 
default)
dflt:   Default value to return with empty input, None is no default 
value
flt:If True, accepts and returns floats
If False, accepts and returns integers (the default)
abrt:   If True empty input aborts and returns None
If False (the default) empty input is handled as invalid data

Invalid input or out-of-range values are not accepted and a warning message
is displayed.  It will then repeat the input prompt for a new value.
Note:  If the dflt parameter is given, its data type is not checked and
could be anything, and could also be used as an abort signal.
"""

while True:
val = input(prmt).strip()
if not val:
if abrt:
return None
if dflt is not None:
return dflt
try:
num = float(val) if flt else int(val)
except ValueError:
print('Invalid input, try again')
continue
#   We have a valid number here, check for in-range
if (lo is None or num >= lo) and (hi is None or num <= hi):
return num
print('Number is out of range')
--

FWIW, as to your question, my preference is for the pseudo-do loop using 'while True' with a 
break as described in other answers here.


Using this function, your loop could be:

while True:
x = get_num('Number (enter ) to terminate:  ')
if x == 0:  #  Or if not x:
break
print(f'Square = { x**2 }')

OR my preference:  Use empty input to terminate by making the input and test:
x = get_num('Number ( to terminate:  ', abrt=True)
if x is None:
break

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


Re: newb question about @property

2017-10-02 Thread Larry Hudson via Python-list

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...)

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


Re: Beginners and experts (Batchelder blog post)

2017-09-27 Thread Larry Hudson via Python-list

On 09/27/2017 09:41 AM, leam hall wrote:

On Sat, Sep 23, 2017 at 5:26 PM, Ned Batchelder 
wrote:

[snip]


The question is, what should a person "know" when hiring out as a
programmer? What is 'know" and what should be "known"? Specifically with
Python.



Hopefully NOT like this person...
(Source:  http://rinkworks.com/stupid/cs_misc.shtml
There is no direct link to this item, it's about 2/3 the way down in a long web 
page...)


Since I teach nights at a local community college, I get a lot of professional programmers in my 
classes upgrading their education. One student, who was one such person, attended every lecture 
and smiled and nodded and took notes. But he only turned in his first assignment. The results of 
his first test were horrid. Out of curiosity, I asked my wife, who barely knew how to turn a 
computer on much less program one, to take the test (which was mostly true/false and multiple 
choice questions). My wife scored higher than this guy.


The semester's end came, and he flubbed his final, too. A few weeks later, I got a call from him 
complaining about his 'F'. I pointed out he hadn't turned in any of his assignments, and those 
counted 75% of the grade.


"Did you hear me say something besides what the other students heard?" I asked.

"Well, I thought my test grades would carry me," he replied.

It had turned out his company had paid for him to take the course. Since he failed, it suddenly 
came to the attention of his employer that he didn't know how to program, and now his job was in 
jeopardy. As I hung up the phone, I mused that his company shouldn't fire him. It was a perfect 
match: a programmer who couldn't program and a company that couldn't figure out sooner that he 
couldn't.



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


Re: "tkinter"

2017-09-13 Thread Larry Hudson via Python-list

On 09/13/2017 05:33 AM, leam hall wrote:

On Wed, Sep 13, 2017 at 8:28 AM, Stefan Ram  wrote:


   I presume that "tkinter" is intended to be pronounced
   "logically":

T K inter (tee kay inter /ti keI In t%/)

   . But it would be faster to pronounce it

T kinter (tee kinter /ti kIn t%/)

   . So far I've only ever read it, never heard it.
   But while I am aware that the logical pronunciation should
   be the correct one, I actually like the faster one.



I heard a speaker mention GvR by name and it took me a bit, and IRC, to
find out the Dutch pronunciation is different from the American. I've seen
his name lots, hadn't heard it.

Leam



Somewhat OT, but...
There is a will-known(?) audio clip of Linus Torvalds pronouncing his name.  
One source is:

http://www.paul.sladen.org/pronunciation/

Click on the MP3 Format or OGG Format links to hear it directly, or the WAV or AU formats to 
download the audio clips.


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


Re: [Tutor] beginning to code

2017-09-13 Thread Larry Hudson via Python-list

On 09/13/2017 09:18 AM, ROGER GRAYDON CHRISTMAN wrote:

I have not yet mastered how to respond to a particular note in a threadwith the
mailer that I use, so this is not in response to anyone in particular,but just
to some of the sentiments as a whole.

  if x:>  # do something

Completely out of context, I would dislike it just because it is far too
vague.Is it testing for zero?  for an empty list?  or for some object's
completelyarbitrary definition of truthiness?


It is absolutely NOT vague, and the answer is Yes for all of the above.  It is well defined that 
ALL values can be used in a boolean sense.


Quoting the on-line Standard Library reference:

4.1. Truth Value Testing

Any object can be tested for truth value, for use in an if or while condition or as operand of 
the Boolean operations below.


By default, an object is considered true unless its class defines either a __bool__() method 
that returns False or a __len__() method that returns zero, when called with the object. [1] 
Here are most of the built-in objects considered false:


constants defined to be false: None and False.
zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
empty sequences and collections: '', (), [], {}, set(), range(0)

Operations and built-in functions that have a Boolean result always return 0 or False for false 
and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or 
and and always return one of their operands.)

-


but in context is another thing entirely.
was x assigned to recently?   

Irrelevant, it uses whatever the current value is.


   is the type of x obvious so its truthiness is
also obvious?Then fine -- if it is clear that x is a list, I'm happy to use
this to test for an empty list.But if x is some other creation, like a user
defined type, I would really prefer to seesomething analogous to:
if not x.is_empty() orx.exists() orx.has_brain()
And most definitely if x is assigned outside my control, I would definitely
wantsome way to test or verify x's type before I start using it, lest my
randomnumber generator with its
(A + B * C) % D
finds itself concatenating strings and formatting data.


Again irrelevant.  That's the beauty/bane of duck typing.  Learn to use it to your advantage and 
only check data types when it is absolutely necessary — which is rarely!



Roger Christman



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


Re: A question on modification of a list via a function invocation

2017-08-17 Thread Larry Hudson via Python-list

On 08/17/2017 12:18 AM, Larry Hudson wrote:

On 08/16/2017 03:39 PM, Chris Angelico wrote:

On Thu, Aug 17, 2017 at 8:29 AM, Mok-Kong Shen

...
Oops, I replied to Chris's post, but it was meant for the OP.  I should have replied to Mok-Kong 
Shen's post instead.  My bad.  Sorry for the confusion, Chris.


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


Re: A question on modification of a list via a function invocation

2017-08-17 Thread Larry Hudson via Python-list

On 08/16/2017 03:39 PM, Chris Angelico wrote:

On Thu, Aug 17, 2017 at 8:29 AM, Mok-Kong Shen
 wrote:

I have earlier learned some other (older) programming languages. For
these the formal parameters are either "by reference" or "by value".
In the first case, any modification of the formal parameter inside
a function affects the corresponding actual parameter of a function
call, while in the second case a copy of the actual parameter is
passed into the function so that any modification of the formal
parameter inside the function has no effect at all outside. This is
extremely clear-cut in comparison to Python, isn't it? Anyway, while
any new user of a programming language certainly can be expected to
take good efforts to learn a lot of new stuffs, I suppose it's good
for any practical programming language to minimize the cases of
surprises for those that come from other programming languages.


Python has a data model that is neither of the above, but it's simpler
in that you have one pattern for everything. Whether you're looking at
function parameters, return values, assignment, loops, function
definitions, or anything else, the model is exactly the same. And that
model is: objects exist independently of names, and names refer to
objects. If you do "x = y", you're saying "figure out which object 'y'
means, and make the name 'x' refer to it". If you do "x[1] = y",
you're saying "figure out which object 'y' means, and tell the object
that 'x' means that it should make [1] refer to that object". So if
you have multiple names referring to the same object, any change you
ask that object to do will be seen by every other name that also
refers to it - because it's all about the object.

ChrisA



Here's another explanation, same concepts just stated differently, perhaps giving a different 
perspective.


In a "traditional" programming language, variables are created/assigned by:

Setting aside a chunk of memory to hold the data and associating the variable name with that 
memory.  And since this chunk is a fixed size, the data type that can be stored there is also 
fixed at that time as well.  This is static typing.


Assignment is done by storing the new data in that memory location, overwriting what was already 
there.  But it has to be the proper data type so it doesn't overrun the memory allocated for it.


Python does it in the opposite order:

The data is stored in memory (or already exists) and the variable name is associated with that 
memory.  Python calls this name binding.  It is possible, and common, that this memory (data) 
has multiple names bound to it.


Assignment is done by associating the name to a different data value (memory location).  This 
data may be newly created or it can be previously existing data.  (The old data may or may not 
be 'garbage collected' — depending on other factors.)  A key point here is that the name has no 
memory size/data type itself and can be bound to ANY data — this is dynamic typing.


Where things get confusing is when we consider mutable/immutable data.

If it is immutable (unchangeable:  ints, floats, strings, tuples...) the _practical_ result is 
that although the implementation details are different, the result of running the program is the 
same.


But for mutable data (changeable IN PLACE:  lists, dictionaries...) the results can be 
surprising from the viewpoint of other languages.  Since this (mutable) data can have multiple 
variable names bound to it, changing the value(s) through ANY of the names changes this data for 
ALL of the names bound to it.


The OP said...

>> I suppose it's good
>> for any practical programming language to minimize the cases of
>> surprises for those that come from other programming languages.

I see your point, but it's irrelevant.  Part of learning any new language is to learn where/how 
the new language handles things differently from your previous experience.  You MUST learn the 
new ways and forget (or at least modify) your previous knowledge.  It's simply a necessary part 
of learning a new language.  Expect it and live with it!


I hope this description gives you another viewpoint to consider.  Good luck on your journey to 
becoming a Pythonista!


concepts in general terms.  The details may be (and probably are) quite different.>


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


Re: A question on modification of a list via a function invocation

2017-08-15 Thread Larry Hudson via Python-list

On 08/14/2017 08:25 PM, Larry Hudson wrote:
[snip]


Here is my attempt to clarify the situation with some ascii graphics.
(Well, not ascii, but utf-8 box-drawing characters — I hope they come through 
ok.
And, of curse, it won't display properly with a proportional font.)

The left side is the program lines, and the right side tries to show the way Python implements 
the name binding to the data in memory.  (But I abbreviated the long assignment line,

alist[0],alist[1],alist[2]=3,6,9 to )

Program line  Variable bound to memory

===  Initial assignment  

ss = [1, 2, 3]  ss ───> [1, 2, 3]

===  test() code  ===

def test(alist):ss ─┬─> [1, 2, 3]
  alist ─┘
-
 alist = [3, 6, 9]   ss ───> [1, 2, 3]
  alist ───> [3, 6, 9]
-
 return  ss ───> [1, 2, 3]
  alist 

===  test1() code  ==
def test1(alist):   ss ─┬─> [1, 2, 3]
  alist ─┘
-
 ss ─┬─> [3, 6, 9]
  alist ─┘
-
 return  ss ───> [3, 6, 9]
  alist 

===  test2() code  ==
def test2(alist):   ss ─┬─> [1, 2, 3]
  alist ─┘
-
ss ─┬─> [3, 6, 9]
 alist ─┘
-
 alist = [30, 60, 90]ss ───> [3, 6, 9]
  alist ───> [30, 60, 90]
-
 return  ss ───> [3, 6, 9]
  alist 



This needs a minor clarification to the test1 example, plus I want to emphasize that the 
assignment here is through the alist variable.


===  test1() code  ==
def test1(alist):ss ─┬─> [1, 2, 3]
  alist ─┘
-
 ss ─┬─> [3, 6, 9]
  alist ─┘
-
 return  ss ───> [3, 6, 9]
  alist   There is nothing to garbage 
collect here.


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


Re: A question on modification of a list via a function invocation

2017-08-14 Thread Larry Hudson via Python-list

On 08/14/2017 01:02 PM, Mok-Kong Shen wrote:

Am 14.08.2017 um 21:53 schrieb Ned Batchelder:

[snip]


def test(alist):
   alist=[3,6,9]
   return

def test1(alist):
   alist[0],alist[1],alist[2]=3,6,9
   return

def test2(alist):
   alist[0],alist[1],alist[2]=3,6,9
   alist=[30,60,90]
   return

ss=[1,2,3]
test(ss)
print(ss)
test1(ss)
print(ss)
test2(ss)
print(ss)


Your test2 function first mutates the caller's list by assigning
alist[0]=3, then it rebinds the local name alist to be a new list.  So
the caller's list is now [3, 6, 9].


Sorry for my poor knowledge. After the line alist[0]..., what is the
status of the name alist? It's now a global name, right? So why in the
line following that the name alist would suddenly be interpreted as
local? I can't yet fully comprehend the logic behind that.

M. K. Shen

Here is my attempt to clarify the situation with some ascii graphics.
(Well, not ascii, but utf-8 box-drawing characters — I hope they come through 
ok.
And, of curse, it won't display properly with a proportional font.)

The left side is the program lines, and the right side tries to show the way Python implements 
the name binding to the data in memory.  (But I abbreviated the long assignment line,

alist[0],alist[1],alist[2]=3,6,9 to )

Program line  Variable bound to memory

===  Initial assignment  

ss = [1, 2, 3]  ss ───> [1, 2, 3]

===  test() code  ===

def test(alist):ss ─┬─> [1, 2, 3]
 alist ─┘
-
alist = [3, 6, 9]   ss ───> [1, 2, 3]
 alist ───> [3, 6, 9]
-
return  ss ───> [1, 2, 3]
 alist 

===  test1() code  ==
def test1(alist):   ss ─┬─> [1, 2, 3]
 alist ─┘
-
ss ─┬─> [3, 6, 9]
 alist ─┘
-
return  ss ───> [3, 6, 9]
 alist 

===  test2() code  ==
def test2(alist):   ss ─┬─> [1, 2, 3]
 alist ─┘
-
   ss ─┬─> [3, 6, 9]
alist ─┘
-
alist = [30, 60, 90]ss ───> [3, 6, 9]
 alist ───> [30, 60, 90]
-
return  ss ───> [3, 6, 9]
 alist 

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


Re: Is An Element of a Sequence an Object?

2017-06-04 Thread Larry Hudson via Python-list

On 06/03/2017 09:39 PM, Chris Angelico wrote:

That's a tricky thing to pin down. Since it's possible for a sequence
to contain itself, or to contain something which contains it,


Like a Tardis?

[Sorry, couldn't resist...]   ;-)

OTOH, On-Topic...  It might be worth while to point out that a 'character' is NOT a data type in 
Python, in the same sense as it is in other languages.


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


Re: Verifiably better, validated Enum for Python

2017-05-26 Thread Larry Hudson via Python-list

On 05/26/2017 04:46 AM, Steve D'Aprano wrote:
[snip..]>

That's not how the C standard defines "undefined behaviour", or the
implication of such.



A little OT here, but...
This brings to mind this entry in the Jargon File:

http://catb.org/jargon/html/N/nasal-demons.html

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


Re: Escaping confusion with Python 3 + MySQL

2017-03-26 Thread Larry Hudson via Python-list

On 03/26/2017 01:21 AM, Νίκος Βέργος wrote:

print('''UPDATE visitors SET (pagesID, host, ref, location, useros, browser, visits) 
VALUES (%s, %s, %s, %s, %s, %s, %s) WHERE host LIKE "%s"''', (pID, domain, ref, 
location, useros, browser, lastvisit, domain) )

prints out:

UPDATE visitors SET (pagesID, host, ref, location, useros, browser, visits) VALUES (%s, 
%s, %s, %s, %s, %s, %s) WHERE host LIKE "%s" (1, 'cyta.gr', 'Άμεση Πρόσβαση', 
'Greece', 'Windows', 'Chrome', '17-03-24 22:04:24', 'cyta.gr')

How should i write the cursor.execute in order to be parsed properly?
As i have it now %s does not get substituted.


You don't get the substitution because you're missing a %.

Change:
... LIKE "%s"''', (pID, ...
To:
... LIKE "%s"''' % (pID, ...

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


Re: Who are the "spacists"?

2017-03-19 Thread Larry Hudson via Python-list

On 03/18/2017 05:01 PM, Nathan Ernst wrote:
[...]

Personally, I dislike any editor that, by default, changes my input to
something else. If I hit tab, I want a tab to be inserted, by default. If I
want something else, I'll change the configuration.

A trivial point (and irrelevant)...  The thing I find annoying about an editor set to expand 
tabs to spaces is that it takes one keypress to indent but four (or whatever) to unindent.


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


Re: The hardest problem in computer science...

2017-01-06 Thread Larry Hudson via Python-list

On 01/06/2017 05:03 AM, Steve D'Aprano wrote:

The second hardest problem in computer science is cache invalidation.

The *hardest* problem is naming things.

In a hierarchical tree view widget that displays items like this:


Fiction
├─ Fantasy
│  ├─ Terry Pratchett
│  │  ├─ Discworld

[snip]


but what do I call XXX and YYY?


Seriously-considering-just-hard-coding-them-as-magic-constants-ly y'rs,


I don't know if this is helpful or even relevant, but here is a class for using these 
box-drawing characters that I wrote for my own use.  (I'm just a hobby programmer...)
It's not very elegant and not particularly convenient to use, but it is usable.  And I hesitate 
to post it because it is so long (approx 90 line docstring to explain its use, and ending with 
some test code).  In any case, here it is...



#   boxch.py

"""
BoxChr class to handle box-drawing characters.

The character is selected by a two-character string:
'tl', 'tm', 'tr' -- Top Left, Top Mid, Top Right:  ┌ ┬ ┐
'ml', 'mm', 'mr' -- Mid Left, Mid Mid, Mid Right:  ├ ┼ ┤
'bl', 'bm', 'br' -- Bot Left, Bot Mid, Bot Right:  └ ┴ ┘
'hz', 'vt'   -- Horizontal and Vertical lines: ─ │
Case is ignored.  Invalid selection string returns a dot:  '·'
NOTE:  It is currently disabled, but the code is still
available to handle small and large dots with 'dt' and 'dd'.
These both ignore the style.

The style is selected by a two-character string:
The characters are 's', 'd' and 'b' for single, double and bold.
The first character defines the horizontal components,
the second defines the vertical components.
The valid styles are 'ss', 'sd', 'sb', 'ds', 'dd', 'bs', 'bb'.
The potential styles 'db' and 'bd' are invalid.
The class defaults to 'ss' -- single horizontal, single vertical.
Case is ignored.  Invalid style string raises ValueError.

NOTE:  The following examples assume bc has been set to a BoxChr class.
bc = BoxChr()   #   Style defaults to 'ss'
  or
bc = BoxChr('sd')   #   Style set to single/double, or whatever desired.
(Examples assume 'ss' style.)

Attributes:
style:  set or return the style-code string.
Case is ignored.  Invalid style raises ValueError.
Examples:  bc.style = 'ds' -- sets style to double/single.
st = bc.style -- sets variable st to current style code.

Methods:
[] (__getitem__):  Returns selected box character.
Case is ignored.  Invalid selector returns a dot:  '·'
Example:  bc['tm'] returns '┬'

bxstr():   Returns a string created from a sequence of box character codes
and 'normal' characters.  (in this description 'selector' refers
to the two-character codes as defined above.)

Each element of the given sequence (list or tuple) must be a
string, either a series of selector codes, or a 'normal' string
(one without any box selectors).  The box character selector string
must start with 'BX' followed by the selector codes, separated by
spaces.  The 'BX' must be upper case, but the case of the selector
codes is ignored.  A space between the 'BX' prefix and the first
selector code is optional.  This selector string can only contain
selector codes.  'Normal' characters are simply given as normal
strings, interspersed with the selector strings in the given
sequence.

If the selection is only box characters, it can opionally be passed
as a single string rather than enclosing it in a list.
Example:
seq = ['BX ml hz', ' TEXT ', 'BX hz mr']
bc.bxstr(seq) returns '├─ TEXT ─┤'
Note:
If you need a string beginning with 'BX' it has to be given
as a single-character string 'B' followed by a string containing
the remaining text.  Example 'BX etc' must be given as:
['B', 'X etc'].

boxtext():  Create boxed text, returned as a single string with
embedded newlines.

Parameters:
txt The text to use
tsize   Expand tabs to specified number of spaces,  Default is 4
just'<', '^' or '>' as left/center/right justification.
Default is '<' — left-justified.
tallIf True, inserts a blank line above and below the text.
If False, no extra blank lines are used.
Default is True.

Text can be either a single string with embedded newlines (ie. a
triple-quoted string) or list of strings.  Trailing blank lines
are removed.  Center and right justification will strip whitespace
from both ends of the lines.  Left justification (the default)
only strips trailing whitespace.

Width is based on the length of the longest line, plus two spa

Re: Hey, I'm new to python so don't judge.

2017-01-06 Thread Larry Hudson via Python-list
On 01/03/2017 04:27 PM, Callum Robinson wrote:
> On Wednesday, January 4, 2017 at 1:17:11 PM UTC+13, Chris Angelico wrote:
>> On Wed, Jan 4, 2017 at 11:03 AM, Erik  wrote:
>>> I doubt it's getting that far (I can see at least one syntax error in the
>>> code pasted).
>>
>> True true. In any case, the point is to copy and paste the error
>> message. Callum, please, copy and paste it.
>>
>> ChrisA
>
> I'm sorry if I'm doing something wrong but all that is happening is when i
try to run it a popup says Invalid syntax
>

Exactly HOW are you running this?

If you are getting a popup, I suspect you are using an on-line version in a 
browser.  To get the
proper Python error messages (called Tracebacks) you MUST run the program in a 
terminal on your
own computer.  These tracebacks are VERY informative (once you get used to 
them).   :-)
And these tracebacks are what WE need to see to help you.

You DO have Python installed, don't you?

--
  -=- Larry -=-

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


Re: Hey, I'm new to python so don't judge.

2017-01-03 Thread Larry Hudson via Python-list

On 01/03/2017 04:27 PM, Callum Robinson wrote:

On Wednesday, January 4, 2017 at 1:17:11 PM UTC+13, Chris Angelico wrote:

On Wed, Jan 4, 2017 at 11:03 AM, Erik  wrote:

I doubt it's getting that far (I can see at least one syntax error in the
code pasted).


True true. In any case, the point is to copy and paste the error
message. Callum, please, copy and paste it.

ChrisA


I'm sorry if I'm doing something wrong but all that is happening is when i try 
to run it a popup says Invalid syntax



Exactly HOW are you running this?

If you are getting a popup, I suspect you are using an on-line version in a browser.  To get the 
proper Python error messages (called Tracebacks) you MUST run the program in a terminal on your 
own computer.  These tracebacks are VERY informative (once you get used to them).   :-)

And these tracebacks are what WE need to see to help you.

You DO have Python installed, don't you?

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


Re: python 2.7.12 on Linux behaving differently than on Windows

2016-12-06 Thread Larry Hudson via Python-list

On 12/06/2016 03:21 AM, BartC wrote:

On 06/12/2016 07:37, Larry Hudson wrote:


Now you're suggesting the _shell_ is going to read and process a CVS
file???


What follows a shell command is a set of values a,b,c,d,e. What is encountered 
in a CSV is a set
of values a,b,c,d,e. You really can't see the similarity?


No.  The way they're used is entirely different.


I get awfully tired of your constant pontificating about your opinions.


Opinions based on facts: I've given a dozen examples where the shell's 
auto-expansion can screw
things up. And I can easily come up with more, as have others in the thread.

People's attitudes seem to be 'So don't that'. Or, 'So what?'.


I'll repeat:  They are OPINIONS and "they ain't gonna change nothin', no how, no 
way, not ever."

MY opinion, which I fully accept "ain't gonna change nothin', no how, no way, not ever" is that 
for someone who claims to be such an expert and experienced programmer, your posts frequently 
show an amazing lack of knowledge.  For example, quoting from another recent post of yours:


>>Read the Python documentation for argparse

> I just tried it, but it was too complex for me to set it up so as to discover with it did 
with * arguments.


Your ignorance is clearly showing.

Finally I have to admit that I'm an old codger and becoming more and more of a curmudgeon.  This 
sometimes shows up in RL, but I generally try to avoid it in public forums like this, but 
occasionally...:-(


[I suspect that there are others who share my opinion, however, whether that is true or not is 
entirely irrelevant as well.]


That is also all I'm going to say on this subject, so don't bother responding to this post.  I 
won't continue it.


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


Re: python 2.7.12 on Linux behaving differently than on Windows

2016-12-05 Thread Larry Hudson via Python-list

On 12/05/2016 10:50 AM, BartC wrote:


And just what ARE A, C, and D?


It doesn't matter, and is not the concern of the shell. It should restrict 
itself to the basic
parsing that may be necessary when parameters are separated by white-space and 
commas, if a
parameter can contain white-space or commas. That usually involves surrounding 
the parameter
with quotes.

One would be very annoyed if, reading a CSV file, where each of N values on a 
line correspond to
a field of record, if one entry of "?LBC" expanded itself to a dozen entries, 
screwing
everything up.


Now you're suggesting the _shell_ is going to read and process a CVS file???


Shell command line processing shouldn't be attempting anything more than that.

I get awfully tired of your constant pontificating about your opinions.  I know they're _VERY_ 
strongly held beliefs on your part, but...  they are ONE person's opinions and are no more than 
opinions and they ain't gonna change nothin', no how, no way, not ever.


[Sorry, I'm in a bad mood today and just had to let off a little steam...]

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


Re: python 2.7.12 on Linux behaving differently than on Windows

2016-12-05 Thread Larry Hudson via Python-list

On 12/05/2016 06:51 PM, Nathan Ernst wrote:

IIRC, command.com was a relic of Win9x running on top of DOS and was a
16-bit executable, so inherently crippled (and probably never support by
the NT kernel). Whereby cmd.exe coexisted but ran in a 32-bit context.


I know my 79-year-old memory is definitely subject to "senior moments" and not too reliable, but 
IIRC it was Windows prior to 9x (Win 3 and earlier) that were 16 bit and ran on top of DOS. 
Win95 was the first 32 bit version and was independent from DOS.


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


Re: Help with two issues, buttons and second class object

2016-11-24 Thread Larry Hudson via Python-list

On 11/24/2016 06:53 AM, Peter Otten wrote:

Thomas Grops via Python-list wrote:

[snip...]

Instead of repeating your code with copy-and-past make a helper function
like the randx() posted by Larry Hudson.

By the way, randint(min, max) may return max so there are 9 possible
outcomes while you handle only 8. To be consistent with Python's half-open
ranges use

random.randrange(8) # may return 0, 1, 2, 3, 4, 5, 6, 7, but not 8



About my (Larry Hudson) randx() example code:

I used randint() in it because that was what the OP was using.  I didn't want to bother with the 
side issue of randint() vs randrange() since it was just meant as example code to be adapted. 
If I had written it for my own use I would have used randrange() for the consistency that you 
are describing.


Not an excuse — just a comment.   ;-)

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


Re: Random number help

2016-11-23 Thread Larry Hudson via Python-list

On 11/23/2016 11:17 AM, Thomas Grops wrote:

I need a way of generating a random number but there is a catch:

I don't want to include certain numbers, is this possible?

random.randint(1,100) works as it will randomly pick numbers between 1 and 100 
but say i don't want 48 to come out is there a way of doing this. It needs to 
be an integer too so not a list unless there is a way to convert list to int

Many Thanks Tom



Here's a possible generic approach:

#  Come up with a better name for this function
def randx(lo, hi, nw):  #  nw is a list of not-wanted ints
while True:
n = random.randint(lo, hi)
if n not in nw:
return n

Use it the same way as randint(), plus a list of the not-wanted values.
Short example:

---
nw = [1, 3, 5, 7, 9]  #  Odd numbers out
for i in range(10):
print(randx(1, 10, nw), end=' ')
print()
---

Here's the results I got for 3 runs...

4 4 4 8 10 6 8 2 4 8
8 4 2 4 6 8 2 4 8 8
10 6 6 4 4 4 8 2 8 4

Of course, the not-wanted list can be a single int, or even empty.

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


Re: How to you convert list of tuples to string

2016-11-23 Thread Larry Hudson via Python-list

On 11/23/2016 03:09 AM, Ned Batchelder wrote:
[snip...]

Or using the new string formatting syntax:

msg = '{},{},{}:{}'.format(*item)

The *item in the format() unpacks the tuple.



"new" == "Introduced in 2.6, available since 2008" :)

--Ned.



Of course.  I probably should have said "newer" or "other".:-)

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


Re: How to you convert list of tuples to string

2016-11-23 Thread Larry Hudson via Python-list

On 11/22/2016 08:51 AM, Michiel Overtoom wrote:

Hi Ganesh,


Any better suggestion to improve this piece of code and make it look more 
pythonic?



import random

# A list of tuples. Note that the L behind a number means that the number is a 
'long'.

data = [(1, 1, 373891072L, 8192), (1, 3, 390348800L, 8192), (1, 4, 372719616L,
8192), (2, 3, 382140416L, 8192), (2, 5, 398721024L, 8192), (3, 1,
374030336L, 8192), (3, 3, 374079488L, 8192), (3, 5, 340058112L, 8192)]

item = random.choice(data)  # Select a random item from the 'data' list.

msg = "%d,%d,%d:%d" % item  # Format it in the way you like.

print msg


Greetings,



Or using the new string formatting syntax:

msg = '{},{},{}:{}'.format(*item)

The *item in the format() unpacks the tuple.

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


Re: Can somebody tell me what's wrong wrong with my code? I don't understand

2016-11-23 Thread Larry Hudson via Python-list

On 11/21/2016 07:10 PM, rmjbr...@gmail.com wrote:

Hi! This is my first post! I'm having trouble understanding my code. I get 
"SyntaxError:invalid syntax" on line 49. I'm trying to code a simple text-based 
rpg on repl.it. Thank you for reading.



print("Welcome to Gladiator Game! Choose your character race, class, and starting 
equipment!")

print('')

print("Race selection: ")

print('')

print("(1) Orcs. Known for their very wide, robust physiques. They are the strongest 
of all the races in Polaris.")

print('')

print("(2) Elves. Thin and wiry. They are known for their amazing agility and 
hand-eye coordiation. They originate from the desert island of Angolia.")

print('')

print("(3) Silverbacks. A hairy, ape-like race from Nothern Polaris. Their metal fur 
provides them with much needed protection.")

print('')

print("(4) Pomongos. An amphibian race believed to inhabit the wet jungles of 
Central Polaris. Legends say they have highly corrosive spit...")

print('')

raceNum=int(input("Select your character's race by entering the corresponding 
number. Then press enter: "))

print('')

while raceNum<1 or raceNum>4:
  raceNum=int(input('Invalid input. Try again: '))

print('')

if raceNum==1:
  print("You're an orc, eh? I won't be sayin' anything mean about you...")
  print('')
  classNum=int(input("What's your profession big fella?"))

elif raceNum==2:
  print("I never liked you elven folk...Let's get on with this.")
  print('')
  classNum=int(input("What's your profession ? Do ye even have one ?"))

elif raceNum==3:
  print("Nice fur. I don't see too many of your kind 'round here. Maybe that's a 
good thing...")
  print('')
  classNum=int(input("What's your profession mate?")

elif raceNum==4: #this line has an error for some reason
  print("Your a 'Mongo eh? I thought you lads were extinct...Just keep your tongue 
in ya mouth and we'll get along fine mate.")
  classNum=int(input("What's your profession?"))



You've already received answers about your typo so I won't repeat that.  However I have a couple 
minor suggestions about your approach.


First, the empty string in your print('') statements is unnecessary.  Just use print(), it does 
the same thing.


Next your menu for the raceNum selection is straight-forward, and there is nothing wrong with 
that.  But another approach that might be a bit shorter is to use a list of strings displayed in 
a loop.  Something like this (very simplified) example...



options = ['First option',
'Next option',
'One more time',
#  etc
]
#  This version assumes the option number is part of the strings
for opt in options:
print(opt)
print()#  If you really want the double-spacing, personally I don't 
think it's needed


Here's a bit more advanced version of the for loop, this one assumnes the option numbers are not 
in the strings in the list...



for num, opt in enumerate(options, 1):
print('({})  {}'.format(num, opt))#  OR   print('(%d)  %s' % (num, opt))
print()#  Again, double-spacing is optional


A similar approach could be used for your classNum section.

Just some suggestions to read/study/adapt...  or ignore.  Whatever you feel 
like.  ;-)

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


Re: A question about sprite rendering in game development

2016-11-16 Thread Larry Hudson via Python-list

On 11/16/2016 12:16 AM, shadecelebi wrote:

thanx a lot you guys. I'm slightly familiar with pygame from before so I'll 
make sure to utilize it. and no I don't have any of the characters yet as I've 
yet to start. I just wanted to know if I should keep learning python or if it 
would be trivial to try making my game a reality with this language. I'll need 
to learn a couple more things before I try to make a prototype. I believe the 
easiest route will be to simply rectangels of different colors for the early 
gameplay and to try and perfect the game mechanics before I move over to adding 
sprites and such. thank you both. I'll post updates in a different thread when 
I'm starting to see some kind of results



There's a book, "Making Games with Python & Pygame", available at 
http://inventwithpython.com/pygame/ you might find worth checking out.


On this site, there are two prominent links to "Buy It" and "Read it on-line".  But below these 
are three 'alternate' links to downloadable PDF and e-Reader versions as well as the source code 
(including the graphics used in the book).  The "Buy It" is for a hard-copy version.


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


Re: Need help with coding a function in Python

2016-10-31 Thread Larry Hudson via Python-list

On 10/31/2016 03:09 PM, devers.meetthebadger.ja...@gmail.com wrote:

http://imgur.com/a/rfGhK#iVLQKSW

How do I code a function that returns a list of the first n elements of the 
sequence defined in the link? I have no idea!

So far this is my best shot at it (the problem with it is that the n that i'm 
subtracting or adding in the if/else part does not represent the element's 
position, but just the n that I am plugging into the function):

def reca(n):
rlist=[0]
while len(rlist) < n:
if (rlist[-1]-n) > 0 and (rlist[-1]-n) not in rlist:
rlist.append(rlist[-1]-n)

else:
rlist.append(rlist[-1]+n)

return(rlist)



I'm not looking at your link or your code, just your description of the problem.
Paraphrased:  "A list of the first n elements of a sequence"

No function necessary, just use slicing...

newlist = oldlist[:n]

list:[1,2,3,4,5,6,7,8,9,10][:5] gives [1,2,3,4,5]
tuple:   (1,2,3,4,5,6,7,8,9,10)[:5] gives (1,2,3,4,5)
string:  "Hello there"[:5] gives "Hello"

Works for sequences shorter than n as well, which gives the full (short) 
sequence.

list:[1,2,3][:5] gives [1,2,3]
etc...

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


Re: Function to take the minimum of 3 numbers

2016-10-09 Thread Larry Hudson via Python-list

On 10/09/2016 05:01 AM, Cai Gengyang wrote:

def min3(a, b, c):

min3 = a
if b < min3:
min3 = b
if c < min3:
min3 = c
if b < c:
min3 = b
return min3


print(min3(4, 7, 5))

4



This is NOT a recommendation here, just a different way of looking at the problem (and is 
probably cheating anyway)...


def min3(a, b, c):
return sorted([a, b, c])[0]  #  Create a list, sort it and return the 1st 
element

It can be extended to take any number of parameters:

def minn(*args):
return sorted(args)[0]

The * syntax takes all the parameters and puts them into a single tuple.

This is _almost_ the same as the built-in min() function — the built-in requires a single 
(sequence) parameter, my minn() function requires multiple individual parameters.  (Both 
versions fail with zero parameters.)


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


Re: Nested for loops and print statements

2016-09-28 Thread Larry Hudson via Python-list

On 09/27/2016 09:20 PM, Steven D'Aprano wrote:

On Wednesday 28 September 2016 12:48, Larry Hudson wrote:


As they came through in the newsgroup, BOTH run correctly, because both
versions had leading spaces only.
(I did a careful copy/paste to check this.)


Copying and pasting from the news client may not be sufficient to show what
whitespace is actually used...

Exactly.  That's why I pointed out the sometime (mis)handling of tabs in newsreaders, and said 
these examples came through in MY reader (Thunderbird) as spaces only, so both examples ran 
correctly.


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


Re: Nested for loops and print statements

2016-09-27 Thread Larry Hudson via Python-list

On 09/26/2016 01:57 PM, Cai Gengyang wrote:

Ok it works now:


for row in range(10):

  for column in range(10):
   print("*",end="")




but how is it different from ---


for row in range(10):

   for column in range(10):
  print("*",end="")

SyntaxError: inconsistent use of tabs and spaces in indentation

Why does the example on top work and the example below doesn't work ? The only difference 
is that the "print" statement is one space different from each other. Forgive 
me if i can't explain things clearly over the forum



As they came through in the newsgroup, BOTH run correctly, because both versions had leading 
spaces only.  (I did a careful copy/paste to check this.)  Tabs are sometimes handled 
incorrectly/inconsistently in newsgroup postings.  But if you read the Traceback error message, 
it is telling you that you have a mix of tabs and spaces _in your original_.  READ the error 
messages, they are important!


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


Re: Nested for loops and print statements

2016-09-26 Thread Larry Hudson via Python-list

On 09/26/2016 08:25 AM, Cai Gengyang wrote:

I just wanted to note that sometimes the code works, sometimes it doesn't. 
(even though both are exactly the same code) ... Weird , dum dum dum



It is NOT weird.  Python is being consistent, YOU are not.

These examples are NOT "exactly the same code"!  The indenting is different.  Python (correctly) 
treats them as being different.


YOU MUST USE CONSISTENT INDENTING.  You MUST always use spaces (the recommended) or always use 
tabs.  Never, ever, not at any time, can you mix them.


(Now, does that emphasize the point enough?)  Go back and REWRITE your code with CONSISTENT 
indenting.


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


Re: strings and ints consistency - isinstance

2016-09-22 Thread Larry Hudson via Python-list

On 09/22/2016 06:40 AM, Sayth Renshaw wrote:
[snip...]


True it failed, just actually happy to get it to fail or pass successfully on 
int input.

Just felt it was a clearer and more consistent approach to verifying input, 
then most of the varied and rather inconsistent approaches I have seen in 
trying to get this to work.

Half opt for try except the other half if else and then implement them largely 
differently. Every many and varied approach str2bool(), isalpha() using list 
with isinstance(var, [ int, str, bool]) etc.

Anyway back to the old drawing board.

Cheers

Sayth



IMHO...  This sort of thing deserves to be written as a separate function which can then be 
called anytime, anyplace.  This keeps your validation and repeated input in one place and is 
done automatically, and lets your main program simply assume the input is valid.


For example, here is the help message for the number input function I wrote for my personal 
utility library:


---
get_num(prmt, min_val=None, max_val=None, flt=False)

Get a number from the console

Parameters:
prmt:   The prompt to be used with the input function, required.
min_val:The minimum permissible value, or None if no minimum (the 
default)
max_val:The maximum permissible value, or None if no maximum (the 
default)
flt:If True, accepts and returns floats
If False, accepts and returns integers (the default)

Invalid input or out-of-range values are not accepted and a warning message
is displayed.  It will then repeat the input prompt for a new value.
---

Admittedly, this may be overkill for general use, but it IS very handy.  Even if it is overkill, 
it is still very easy to use.  Similar validated input functions are useful as well — such as a 
Yes/No function among others.


If you're interested, I could post the source for this version, but if you think of it as a 
generic function rather than for a specific situation, it is pretty straight-forward to write. 
something similar.


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


Re: Data Types

2016-09-22 Thread Larry Hudson via Python-list

On 09/20/2016 09:03 PM, Cai Gengyang wrote:
[snip...]

So for example for "bool" , it only applies to True/False and nothing else? (2 
data types), i.e. :


Not exactly...  bool is the data type (or class), True and False are the only two _values_ (not 
types).





type(True)



type(False)




[snip...]

Besides the bool class, with its two values, there is also the Nonetype class, which has only 
one value:  None.


But to expand on/rephrase what has already been said:  while the bool class/type has only the 
two values True/False, in expressions using logical operators (and, or, not...), ANY data type 
can be interpreted as a boolean.  These are often referred to as truthy and falsey values to 
distinguish them from actual boolean True/False values.


I'm sure you've already seen the list, if not you should quickly learn it...
Any numeric (int, float, complex) that is zero is falsey.
Any empty collection (list, string, dictionary...) is falsey.
EVERYTHING else is truthy.

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


Re: How to split value where is comma ?

2016-09-08 Thread Larry Hudson via Python-list

On 09/08/2016 07:57 AM, John Gordon wrote:

In  Joaquin Alzola 
 writes:


Use the split



a.split(",")
for x in a:
print(x)


This won't work.  split() returns a list of split elements but the
original string remains unchanged.

You want something like this instead:

newlist = a.split(",")
for x in newlist:
print(x)



Even easier...

for x in a.split(','):
print(x)

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


Re: Extend unicodedata with a name/pattern/regex search for character entity references?

2016-09-04 Thread Larry Hudson via Python-list

On 09/04/2016 09:00 AM, Veek. M wrote:

Steve D'Aprano wrote:


On Sun, 4 Sep 2016 06:53 pm, Thomas 'PointedEars' Lahn wrote:


Regarding the name (From field), my name *is* Veek.M […]


Liar.  *plonk*


You have crossed a line now Thomas.

That is absolutely uncalled for. You have absolutely no legitimate
reason to believe that Veek is not his or her real name.

You owe Veek an apology, and a promise to the entire community that
you will not act in such a bigoted, racist manner again.





ah umm.. I'm not overly offended - it was more of a startle. I've gotten
used to USENET, somewhat - nature of the beast.



If you continue to read this forum, you will quickly learn to ignore "Pointy-Ears".  He rarely 
has anything worth while to post, and his unique fetish about Real Names shows him to be a 
hypocrite as well.


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


Re: Multimeter USB output

2016-08-30 Thread Larry Hudson via Python-list

On 08/29/2016 09:24 PM, Paul Rubin wrote:

Larry Hudson  writes:

with BDS-C under CP/M. Somebody remenbering this no-fp compiler from
the dark age before PC und Linux?

I remember it well.  It's what I used to initially learn C.


Source code is online here:

http://www.bdsoft.com/resources/bdsc.html


[...]

I remember reading a magazine interview with Leor Zolman (the author of BDS-C) where he 
mentioned what the BDS stood for...  He said is was his nickname in college:  Brain Dead.


Actually "Brain Dead Software" it was not!  It was really quite good, and rather widely used at 
the time.


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


Re: [OT] Altair

2016-08-30 Thread Larry Hudson via Python-list

On 08/30/2016 11:51 AM, Joe wrote:

Am 30.08.2016 um 17:52 schrieb D'Arcy J.M. Cain:

On Tue, 30 Aug 2016 15:56:07 +0200
Joe  wrote:

Am 30.08.2016 um 13:01 schrieb D'Arcy J.M. Cain:

On Mon, 29 Aug 2016 21:21:05 -0700
Larry Hudson via Python-list  wrote:

I remember it well.  It's what I used to initially learn C.  I'm a
completely self-taught, hobby programmer.  Been around since the
MITS Altair.  How many remember that beast??


Remember it and still have it in the basement.


I read a lot about the Altair in Byte in those days, but never had a
chance to touch it. Wasn't it horrible expensive?




I don't think so.  The figure I have in my (very fallible) mind is $300 (or maybe $600) for my 
original Altair with 1K RAM and no peripherals.



I can't remember what is was going for but I bought mine used for
$1,000.  It had a number of add-ons including a keyboard and floppy
drives.  The power supply was also beefed up.

It also had a replacement bezel.  It seems that the original Altair's
silk screened front panel was crappy and rubbed off easily.  Some
company sold one but it says "Cycloid" instead of "Altair" on it.



I think the first BASIC Interpreter ever sold by Gates & Friend was for this 
machine? How did
you use your floppy drives on this machine (Open-Write-Close)?



('Friend' is Paul Allan.)

My first floppy was from Northstar Computers.  It used the first 5¼ drive made (by Shugart).  It 
came with it's own DOS and BASIC -- somewhat incompatible with Gates' Altair BASIC, but very 
usable.  (Anyway, Altair BASIC did not handle disks — at least the original version did not.)


The Northstar DOS was somewhat weird due to where it was located in memory.  The bottom 8K of 
RAM was free, the next 2K was the DOS (that's right a complete Disk-Operating-System in 2K of 
memory!).  The rest of available memory above that was also free.  The BASIC was also loaded in 
this memory above the DOS.


Trivia:  (and perhaps wrong) — The original name of Northstar Computers was Kentucky Fried 
Computers.


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


Re: Multimeter USB output

2016-08-30 Thread Larry Hudson via Python-list

On 08/30/2016 04:01 AM, D'Arcy J.M. Cain wrote:

On Mon, 29 Aug 2016 21:21:05 -0700
Larry Hudson via Python-list  wrote:

I remember it well.  It's what I used to initially learn C.  I'm a
completely self-taught, hobby programmer.  Been around since the MITS
Altair.  How many remember that beast??


Remember it and still have it in the basement.



Mine is stuffed into the back of a closet.   :-)

It was still working when I stored it, but I don't think I could remember how to bring it up 
again.  As I recall, you had to set the starting memory address via the front-panel switches — 
but the details have long since evaporated from my memory.   :-(


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


Re: Multimeter USB output

2016-08-29 Thread Larry Hudson via Python-list

On 08/29/2016 01:54 AM, Joe wrote:
[snip...]

Interesting, but... The last time I did something with c, it was with BDS-C 
under CM/M. Somebody
remenbering this no-fp compiler from the dark age before PC und Linux?


I remember it well.  It's what I used to initially learn C.  I'm a completely self-taught, hobby 
programmer.  Been around since the MITS Altair.  How many remember that beast??


(And yes -- as you already corrected yourself -- that's CP/M not CM/M.)

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


Re: I am new to python. I have a few questions coming from an armature!

2016-08-17 Thread Larry Hudson via Python-list

On 08/17/2016 04:24 AM, Jussi Piitulainen wrote:
...

http://www-formal.stanford.edu/jmc/recursive/node2.html (the paper
famously titled "Part I" without any Part II, unless I mistake much.)



Totally OT here, but...

This reminds me of a old record I have with the (deliberately tongue-in-cheek) title "Joe 
'Fingers' Karr and Ira Ironstrings Together for the Last Time, Volume I".  Of course, there was 
never a Volume II either.  [In case you don't know those performers:  Joe 'Fingers' Karr was the 
stage-name of Joe Busch when he played honky-tonk style piano, Ira Ironstrings (don't know real 
name) played banjo.]


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


Re: Appending an asterisk to the end of each line

2016-07-05 Thread Larry Hudson via Python-list

On 07/05/2016 03:05 PM, Seymore4Head wrote:

import os

f_in = open('win.txt', 'r')
f_out = open('win_new.txt', 'w')

for line in f_in.read().splitlines():
 f_out.write(line + " *\n")

f_in.close()
f_out.close()

os.rename('win.txt', 'win_old.txt')
os.rename('win_new.txt', 'win.txt')


I just tried to reuse this program that was posted several months ago.
I am using a text flie that is about 200 lines long and have named it
win.txt.  The file it creates when I run the program is win_new.txt
but it's empty.




Not your problem, but you can simplify your read/write loop to:

for line in f_in:
f_out.write(line[:-1] + ' *\n')

The 'line[:-1]' expression gives you the line up to but not including the 
trailing newline.
Alternately, use:  f_out.write(line.rstrip() + ' *\n')

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


Re: Operator Precedence/Boolean Logic

2016-06-22 Thread Larry Hudson via Python-list

On 06/22/2016 12:42 AM, Lawrence D’Oliveiro wrote:
[snip]

I feel that’s a needlessly complicated rule. It would have been simpler if 
boolean operators (and conditional expressions like in if-statements and 
while-statements) only allowed values of boolean types. But that’s one of the 
few warts in the design of Python...



Wart??  I *strongly* disagree.  I find it one of the strengths of Python, it enhances Python's 
expressiveness.  Of course, everyone is entitled to their own opinion...and this is mine.


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


Re: ASCII or Unicode? (was best text editor for programming Python on a Mac)

2016-06-21 Thread Larry Hudson via Python-list

On 06/19/2016 08:29 PM, Steven D'Aprano wrote:

On Mon, 20 Jun 2016 12:07 pm, Rustom Mody wrote:


[snip]

In theory most Linux apps support an X mechanism for inserting characters
that don't appear on the keyboard. Unfortunately, this gives no feedback
when you get it wrong, and discoverablity is terrible. It's taken me many
years to discover and learn the following:

WIN o WIN o gives °
WIN m WIN u gives µ
WIN s WIN s gives ß
WIN . . gives ·

(WIN is the Windows key)

Getting back to ≠ I tried:

WIN = WIN /
WIN / WIN =
WIN < WIN >
WIN ! WIN =

etc none of which do anything.

Another example of missing tooling is the lack of a good keyboard
application. Back in the 1980s, Apple Macs had a desk accessory that didn't
just simulate the keyboard, but showed what characters were available. If
you held down the Option key, the on-screen keyboard would display the
characters each key would insert. This increased discoverability and made
it practical for Hypertalk to accept non-ASCII synonyms such as

≤ for <=
≥ for >=
≠ for <>

Without better tooling and more discoverability, non-ASCII characters as
syntax are an anti-feature.



It sounds like you are almost, but not quite, describing the Linux Compose key.  To get many of 
the 'special' characters, you first press the compose key and follow it with (usually) two 
characters.  (That's ONE press of the compose key, not two like your first examples.)  And yes, 
the unequal sign is  =/


Here are some more examples (I'm not going to specify the  key here, just assume these 
examples are prefixed with it):  These are all pretty easy to remember.

German umlauts a" o" u" give ä ö ü  (or use uppercase)
Spanish eña (spelling?) and punctuations:  n~ ?? !!  -->  ñ ¿ ¡
French accents:  e' e` e^ c,  -->  é è ê ç
Money:  c= l- y- c/  -->  € £ ¥ ¢
Math:  =/ -: +- xx <= >=  -->  ≠ ÷ ± × ≤ ≥
Superscripts:  ^0 ^1 ^2 ^3  -->  ⁰ ¹ ² ³
Simple fractions:  12 13 ... 78  -->  ½ ⅓ ... ⅞
Here's a cute one:  CCCP  -->  ☭  (hammer & sickle)
And like your first examples:  oo mu ss  -->  ° µ ß
Many MANY more obscure codes as well (have to look them up, or make a copy of 
this info.)

Admittedly not much use in programming, but can be useful for other general 
text.

Now, setting the compose key...  Easy (but obscure) in Mint Linux (and I think Ubuntu is the 
same.  I don't know about other distros.):


From the menu, select Preferences->Keyboard->Layouts->Options->Position of 
Compose Key
This opens a list of checkboxes with about a dozen choices -- select whatever you want (I use 
the Menu key).


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


Re: how to search item in list of list

2016-06-13 Thread Larry Hudson via Python-list

On 06/12/2016 08:29 PM, meInvent bbird wrote:

once a nested list have a word "node" then true else false

def search(current_item):
 if isinstance(current_item, list):
 if len(current_item)==4:
 if [item for item in current_item if item[4] == "node"] != []:
 return True
 if True in [search(item) for item in current_item]:
 return True
 else:
 return False

search(mresult)

but it return false


mresult = [[(2, {'11': 1, '10': 1, '00': 0, '01': 1}, ['000', '001', '010', 
'011', '100',
'101', '110', '111'], 'xy', 'start')], [(2, {'11': 1, '10': 1, '00': 0, '01': 1}
, ['000', '001', '010', '011', '100', '101', '110', '111'], 'yz', 'start')], [(2
, {'11': 1, '10': 1, '00': 0, '01': 1}, ['000', '001', '010', '011', '100', '101
', '110', '111'], 'xz', 'start')], [(2, {'11': 1, '10': 0, '00': 0, '01': 0}, ['
000', '001', '010', '011', '100', '101', '110', '111'], 'xy', 'start')], [(2, {'
11': 1, '10': 0, '00': 0, '01': 0}, ['000', '001', '010', '011', '100', '101', '
110', '111'], 'yz', 'start')], [(2, {'11': 1, '10': 0, '00': 0, '01': 0}, ['000'
, '001', '010', '011', '100', '101', '110', '111'], 'xz', 'start')], [(2, {'11':
  1, '10': 0, '00': 1, '01': 1}, ['000', '001', '010', '011', '100', '101', 
'110'
, '111'], 'xy', 'start')], [(2, {'11': 1, '10': 0, '00': 1, '01': 1}, ['000', '0
01', '010', '011', '100', '101', '110', '111'], 'yz', 'start')], [(2, {'11': 1,
'10': 0, '00': 1, '01': 1}, ['000', '001', '010', '011', '100', '101', '110', '1
11'], 'xz', 'start')], [(1, {'11': 1, '10': 1, '00': 0, '01': 1}, ['00', '01', '
11', '11', '10', '11', '11', '11'], 'xy', 'node')], [(1, {'11': 1, '10': 1, '00'
: 0, '01': 1}, ['00', '01', '10', '11', '11', '11', '11', '11'], 'xy', 'node')],
  [(1, {'11': 1, '10': 1, '00': 0, '01': 1}, ['00', '00', '10', '10', '10', 
'10',
  '11', '11'], 'xy', 'node')], [(1, {'11': 1, '10': 1, '00': 0, '01': 1}, ['00',
'00', '10', '11', '10', '10', '10', '11'], 'xy', 'node')], [(1, {'11': 1, '10':
1, '00': 0, '01': 1}, ['00', '00', '10', '10', '10', '11', '10', '11'], 'xy', 'n
ode')]]



I (manually) reformatted your list and found you have a missing left square 
bracket in the middle.
But the way your list is formatted here I really can't tell you where it is -- you'll have to 
reformat

it and/or use an editor that highlights matching brackets to find it yourself.  
Most programming
editors have that bracket matching capability.

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


Re: i'm a python newbie & wrote my first script, can someone critique it?

2016-06-10 Thread Larry Hudson via Python-list

On 06/10/2016 03:52 PM, mad scientist jr wrote:

Is this group appropriate for that kind of thing?
(If not sorry for posting this here.)

So I wanted to start learning Python, and there is s much information 
online, which is a little overwhelming. I really learn best from doing, 
especially if it's something actually useful. I needed to create a bunch of 
empty folders, so I figured it was a good exercise to start learning Python.
Now that it's done, I am wondering what kind of things I could do better.
Here is the code:


It is FAR too complicated -- it's BASIC written Python.  Python is MUCH easier.

First a couple of general comments...

Drop the Hungarian notation!!  Python uses dynamic typing.  Variables do NOT have a type, the 
data they hold have types, but not the variable itself.  ANY variable can hod ANY data type at 
ANY time.  And Python uses duck typing -- get used to it.


Generally you should put all the imports at the beginning of the program, NOT in each function. 
 A possible exception could be if an import is only used in one function.




# GLOBAL VALUES
sForPythonVersion="3"
#sFolderPathTemplate = "c:\\myscripts\\MP3 Disc "
sFolderPathTemplate = "c:\\temp\\MP3 Disc "
iFromCount = 1
iToCount = 250
iCountWidth = 3


Drop the  from the template string.  (More on this below.)



# SUPPORT FUNCTIONS

# 
//
def is_string(myVar): # is_string IS MORE READABLE THAN isinstance (PLAIN 
ENGLISH!)
 #PYTHON 3 IS NOT LIKING THIS: return ( isinstance(myVar, str) or 
isinstance(myVar, unicode) )
 #PYTHON 3 IS NOT LIKING THIS: return isinstance(myVar, basestr)
 return isinstance(myVar, str)


Not necessary.


# 
//
# THIS IS SOME SAMPLE FUNCTION FROM A BOOK I AM READING "PYTHON IN EASY STEPS"
def strip_one_space(s):
 if s.endswith(" "): s = s[:-1]
 if s.startswith(" "): s = s[1:]
 return s


???  Is this used anyplace?  Delete it.


# 
//
def get_exact_python_version():
 import sys
 sVersion = ".".join(map(str, sys.version_info[:3]))
 sVersion = sVersion.strip()
 return sVersion

sys.version_info[:3] by itself gives a three-element tuple.  Probably easier to use than the 
string version.


A couple alternatives:
sys.version[:5] or perhaps a bit safer -- sys.version.split()[0] both directly give you the 
string version.  (Note this uses version not version_info.)



# 
//
# TO DO: RETURN TO THE LEFT OF FIRST "."
def get_python_version():
 sVersion = get_exact_python_version()
 return sVersion[0:1]


Probably unnecessary as a function.  A simple sVersion[0] in-line might be 
easier.


# 
//
# CHECK PYTHON VERSION, IF IT'S WRONG THEN GRACEFULLY EXIT BEFORE IT BLOWS UP
# (DAMN, PYTHON 2.x STILL COMPLAINS WITH SYNTAX ERRORS!!)
# MAYBE THIS COULD STILL BE USEFUL FOR CHECKING THE SUB-VERSION, IN THAT CASE
# TO DO: MORE GRANULAR CHECK, EG IF VERSION >= 3.5.0
def exit_if_wrong_python_version(sRightVersion):
 import os
 sCurrentVersion = get_python_version()
 if (sCurrentVersion != sRightVersion):
 print("" +
   "Wrong Python version (" +
   sCurrentVersion +
   "), this script should be run using Python " +
   sRightVersion +
   ".x. Exiting..."
   )
 os._exit(0)


Get used to Python string formatting...
print("Wrong Python version ({}), this script should be run using "
"Python {}.x,  Exiting...".format(sCurrentVersion, sRightVersion))

Notice how I split the long single-line string into two shorter strings on two lines relying on 
the automatic string concatenation in Python.  "string1 " "string2" becomes "string1 string2". 
Any whitespace (spaces, tabs, newlines) are ignored and the two strings are stuck together.


Also the common use is sys.exit() instead of os._exit().


# 

Re: Summing/combining tuples

2016-05-19 Thread Larry Hudson via Python-list

On 05/18/2016 09:53 PM, DFS wrote:

On 5/18/2016 10:58 PM, Larry Hudson wrote:

[snip...]

Why two loops?  Put both summations in a single loop.  Then you're only
scanning the alist once instead of twice.

groups1 = defaultdict(int)
groups2 = defaultdict(int)
for nm, matches, words in alist:
groups1[nm] += matches
groups2[nm] += words

 -=- Larry -=-



That gives me two lists - how do I combine them?

In the end that'll be at least 6 lines of code.  Do you have a one-liner to 
summarize the data?

Thanks


One-liner?  No way.  I did manage to get the whole conversion down to 6 lines...
(And I am far from an expert pythonista, a more experienced/expert programmer can probably do 
better.)


A two-line helper function
A two-line for loop
A one-line list comprehension
One line to declare a dictionary as an intermediate variable

#  A helper function -- adds two tuples
#  Could add square brackets to return a 2-element list instead of
#  a tuple, but the final result is the same either way.
def addtpl(t1, t2):
return t1[0]+t2[0], t1[1]+t2[1]

#  Accumulate alist data into an intermediate temporary dictionary
tdic = {}
for dat in alist:
tdic[dat[1]] = addtpl(tdic.get(dat[1], (0,0)), dat[2:])

#  Convert the dictionary back to a list of tuples
result = [(str(n), tdic[n][0], tdic[n][1]) for n in tdic]

Of course, this doesn't retain the original order, but you can use the sorted() function to sort 
the results by the names.


Here is the same thing as a single function that returns the sorted list...
(It also automatically throws away the temporary dictionary.  But it's now 7 lines because of 
the added def line.)


def combine(lst):
def addtpl(t1, t2):
return [t1[0]+t2[0], t1[1]+t2[1]
tdic = {}
for dat in lst:
tdic[dat[1]] = addtpl(tdic.get(dat[1], (0,0)), dat[2:])
return sorted([(str(n), tdic[n][0], tdic[n][1]) for n in tdic])

 -=-Larry -=-

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


Re: Program prints questions for user input, but won't show the answer output

2016-05-18 Thread Larry Hudson via Python-list

On 05/18/2016 06:50 PM, Jake Kobs wrote:

MRAB,

I am not quite sure how to return the print statements so I thought that 
returning the displayInfo def would help.. Im so lost.

Why do you think you want to _return_ a print statement?  The print statement _DOES_ the 
printing, there is nothing that needs to be returned.  Sometimes you might want to return a 
_string_ to be printed where it was called from, but that's not what you want here.


You say that the display info isn't shown...  It looks to me like it it isn't shown because your 
program will crash.  What you have here is called "infinite recursion":


displayInfo() calls displayInfo() which calls displayInfo() which calls displayInfo() which 
calls ... and so on forever.


Another comment:  Your getHigh() and getLow() functions are not necessary.  Python already has 
max() and min() functions built in to do this exact same thing.  Instead you can use:


highPints = max(pints)
lowPints = min(pints)

Of course, writing your own versions as a leaning experience is good too.  But I would suggest 
that a for loop instead of a while in your version would be better.  For one thing, it 
eliminates the counter.  My suggested version...


def getHigh(pints):
high = 0
for pint in pints:
if pint > high:
high = pint
return high

And getLow() is similar (but set the initial value to a high number).

The following example may be more advanced than you're ready for now, but you _might_ find it 
worth studying.  It's possible to do both in a single function:


def getMaxMin(pints):
high = low = pints[0]#  Initialize high and low to the first value of 
the array
for pint in pints[1:]:   #  Scan through the remainder of the pints array
if pint > high:
high = pint
if pint < low:
low = pint
return high, low

You would use it as:

highPints, lowPints = getMaxMin(pints)

I'm NOT necessarily recommending this, but just suggesting it as an example to 
study.

Good luck with your Python studies.  It's a great language to learn.

 -=- Larry -=-

PS.  A final thought...

I don't know your situation so this may not be reasonable but...  I HIGHLY recommend switching 
to Python 3 instead of 2.  Version 2 is at "end-of-life" and won't be updated any further. 
Version 3 is where all future development will occur.  It is definitely the better version, and 
while there are certainly differences, to a beginning programmer the learning curve will be the 
same.


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


Re: Summing/combining tuples

2016-05-18 Thread Larry Hudson via Python-list

On 05/18/2016 05:59 PM, DFS wrote:

Have  aList = [
('x','Name1', 1, 85),
('x','Name2', 3, 219),
('x','Name2', 1, 21),
('x','Name3', 6, 169)
]

want

aList = [
('Name1', 1, 85),
('Name2', 4, 240),
('Name3', 6, 169)
]


This drops the first element in each tuple:
alist = [(b,c,d) for a,b,c,d in alist]


Slicing may be more efficient (perhaps, perhaps not -- don't know).  And probably effectively no 
difference, but slightly shorter to write.


alist = [t[1:] for t in alist]



And this summation creates 2 lists that then have to be combined:

groups1 = defaultdict(int)
for nm, matches, words in alist:
 groups1[nm] += matches

groups2 = defaultdict(int)
for nm, matches, words in alist:
 groups2[nm] += words



Is there something shorter and sweeter for the summation?

Thanks



Why two loops?  Put both summations in a single loop.  Then you're only scanning the alist once 
instead of twice.


groups1 = defaultdict(int)
groups2 = defaultdict(int)
for nm, matches, words in alist:
groups1[nm] += matches
groups2[nm] += words

 -=- Larry -=-

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


Re: pylint woes

2016-05-08 Thread Larry Hudson via Python-list

On 05/08/2016 03:07 PM, Chris Angelico wrote:

On Mon, May 9, 2016 at 6:45 AM, Larry Hudson via Python-list
 wrote:

On 05/08/2016 06:01 AM, Chris Angelico wrote:
[snip...]


...  I like to recommend a
little thing called "IIDPIO debugging" - If In Doubt, Print It Out.
That means: If you have no idea what a piece of code is doing, slap in
a print() call somewhere. It'll tell you that (a) the code is actually
being executed, and (b) whatever info you put between the parens
(ideally, some key variable or parameter)...



My personal variation of IIPPID debugging is to use input() instead of
print().  For example:

 input('x = {}, y = {} --> '.format(x, y))

Then the program stops at this point so you can examine the values.  
will continue the program or ^C will abort (if you see what the problem is
now).  Of course this can't be used in all situations, but it's handy where
it can.

Note that my personal preference is to stick that "-->" as a prompt at the
end, but obviously this (or a similar marker) is optional.


Neat technique. Not something to use *every* time (and not always
sensible - eg you don't normally want to stall out a GUI thread), but
definitely worth keeping in the arsenal.

ChrisA



Agreed.  As I said in my post, it is certainly not a universally valid approach, but I do find 
it useful in many cases.


 -=- Larry -=-

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


Re: pylint woes

2016-05-08 Thread Larry Hudson via Python-list

On 05/08/2016 06:01 AM, Chris Angelico wrote:
[snip...]

...  I like to recommend a
little thing called "IIDPIO debugging" - If In Doubt, Print It Out.
That means: If you have no idea what a piece of code is doing, slap in
a print() call somewhere. It'll tell you that (a) the code is actually
being executed, and (b) whatever info you put between the parens
(ideally, some key variable or parameter)...


My personal variation of IIPPID debugging is to use input() instead of print(). 
 For example:

input('x = {}, y = {} --> '.format(x, y))

Then the program stops at this point so you can examine the values.   will continue the 
program or ^C will abort (if you see what the problem is now).  Of course this can't be used in 
all situations, but it's handy where it can.


Note that my personal preference is to stick that "-->" as a prompt at the end, but obviously 
this (or a similar marker) is optional.


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


Re: How to become more motivated to learn Python

2016-05-03 Thread Larry Hudson via Python-list

On 05/03/2016 07:55 PM, Cai Gengyang wrote:

Cool, I have finally summoned up enough activation energy to start on Unit 3, 
now going through the topic on Conditionals and Control Flows (stuff like this)


boolthree = 200 == (50 * 5)
boolthree

False

Guess it would be really cool to work on AI and games. ( I have been addicted 
to computer games for a long time lol --- To be able to design a blockbuster 
like Starcraft 2, Diablo 3 or Final Fantasy 7 would be an incredible feat !)



For an introduction to Python via games you might want to check out the book "Invent Your Own 
Computer Games With Python".  (However, these are strictly text-based games -- no graphics, but 
a fairly good intro to Python programming.)  It's available to read on-line, or for download as 
a .pdf athttp://inventwithpython.com/


Use the "PDF and All Source Code" link to download it.

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


Re: one-element tuples

2016-04-11 Thread Larry Hudson via Python-list

On 04/10/2016 08:19 PM, Fillmore wrote:


Thank you for trying to help, Martin. So:

On 04/10/2016 09:08 PM, Martin A. Brown wrote:

#1: I would not choose eval() except when there is no other
 solution.  If you don't need eval(), it may save you some
 headache in the future, as well, to find an alternate way.
 So, can we help you choose something other than eval()?
 What are you trying to do with that usage?


so, I do not quite control the format of the file I am trying to parse.

it has the format:

"str1","str2",,"strN" => more stuff
   :

in some cases there is just one "str" which is what created me problem.
The first "str1" has special meaning and, at times, it can be alone.

The way I handle this is:

 parts = line.strip().split(" => ")
 tokens = eval(parts[0])



[code deleted...]


which admittedly is not very elegant. If you have suggestions on how to avoid 
the use
of eval() and still achieve the same, I would be delighted to hear them




Here is a possible alternate approach to get you started thinking in a 
different direction...

Assuming your input string format is always as you describe, splitting off the trailing 'noise' 
can be done the way you are already doing.  It can be done other ways as well.  (Of course, for 
a 'real' program you will probably need to verify this assumption and take appropriate action if 
necessary.)


parts = line.strip().split(' => ')[0]

Note that this trailing index of 0 will throw away the trailing junk, and leave just the initial 
part of the original line as a string.  This can then be split on the commas to give you a list 
of strings...


tokens = parts.split(',')

This will give you, for example,

['"str1"']   #  Case 1, or
['"str1"', '"str2"', '"str3"', ...]  #  Case 2

There is still a problem here.  The strings CONTAIN beginning and ending quotes INSIDE the 
strings.  We can strip these internal quotes with slicing.  I'm also using a list comprehension 
here...


tokens = [st[1:-1] for st in tokens]

Which gives:  ['str1', 'str2', 'str3', ...]

Finally, there are at least two ways of splitting off the first string:  
slicing or pop().

key = tokens[0]; tokens = tokens[1:]
or
key = tokens.pop(0)#  This simultaneously removes the first string from the 
tokens list

Where key is the first string, and tokens is a list of the remaining strings.  This list may be 
empty.  You can now use the key for whatever you need it for, and you can use a for loop for the 
remaining strings.  Note that this also works correctly for an empty list -- where it will do 
nothing.


I hope this gets you started reworking (or re-thinking) your program.

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


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Larry Hudson via Python-list

I didn't see anyone responding to this, so I'll pop in here...

On 03/22/2016 04:05 AM, BartC wrote:
[...]

(Suppose you need both the value and its index in the loop? Then the one-line 
for above won't
work. For example, 'something' is [10,20,30] and you want to print:

  0: 10
  1: 20
  2: 30 )



Your lack of knowledge of Python is showing again...
Python has "enumerate" just for this purpose.  Your example would be written as:

for i, val in enumerate(something):
print('{}: {}'.format(i, val))

However, in this specific example, the i is not used as an actual index but rather a 
line-number.  So you can change "enumerate(something)" to "enumerate(something, 1)" to set the 
starting number to 1 instead of the default 0, and the lines will be numbered 1, 2 and 3 rather 
than 0, 1 and 2.


As always, the choice is yours.  ;-)


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


Re: Text input with keyboard, via input methods

2016-03-10 Thread Larry Hudson via Python-list

On 03/09/2016 11:54 PM, Rustom Mody wrote:
[...]

In between these two extremes we have many possibilities
- ibus/gchar etc
- compose key
- alternate keyboard layouts

Using all these levels judiciously seems to me a good idea...


FWIW -- in Mint Linux you can select the compose key with the following:

Preferences->Keyboard->Layouts->Options->Position of Compose Key

then check the box(s) you want.

For those unfamiliar with it, to use it you press your selected compose key followed by a 
sequence of characters (usually 2 but sometimes more).


A couple examples--
n~ gives ñ u" gives üoo gives °  (degree sign)
Here's a cute one:  CCCP gives ☭  (hammer & sickle)

This gives you (relatively) easy access to a large range of 'special' 
characters.

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


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-20 Thread Larry Hudson via Python-list

On 02/20/2016 10:38 AM, wrong.addres...@gmail.com wrote:
[snip]

How complicated could this get in Python? Reading the numbers is one thing, and 
then placing the values in text boxes of the GUI.


If that is the only object of using these values, there is no conversions necessary.  The data 
is read as text (strings), and you could simply write them directly into the text boxes.  Of 
course, this is unlikely -- you surely want the actual numeric values for other purposes.  As 
already pointed out, if you know in advance what the data types are, the necessary conversions 
are trivial.  Just slightly more complex if you don't know the types in advance.


OTOH, the conversion from int or float back to strings is also trivial.  It's as simple as 
writing str(n), where n is an int OR a float -- it works automatically with either.  (Data 
typing in Python is dynamic, you generally don't need to specify the types.)  But if you want 
the strings to be in a specific format, this is also possible with a different syntax that lets 
you specify the output format.  As an example, assume the variable val is 1.97834, and the 
formatting string is "${:.2f}".format(val) -- this will give you the string '$1.98'.  This 
expression breaks down to:

$   ->  a literal dollar sign
{}  ->  a placeholder, it is where the formatted data will be put
:   ->  what follows is formatting code
.2  ->  round to, and print, two decimal places
f   ->  the data is a float
.format(val)  ->  the data to format

BTW, this leaves the variable val unchanged -- it is NOT rounded, it still holds its original 
precision.  It only affects how it is displayed.  You CAN round it if you want, but that's an 
entirely different function.


Naturally, learning all the formatting codes takes some effort, but it allows defining the 
appearance of the resulting strings in a very detailed and complete manner.  [Aside:  this is 
the "new" formatting method.  Python also supports an "old" method, which is very much like the 
way strings are formatted in the C language.]



Or can I write my own reading subroutines which can then be called like
ReadVBstyle 8, ND, NIN, NT
to make the code more readable?


ABSOLUTELY!!  Most Python programming consists of defining the functions and classes needed, 
which definitely makes Python more readable.  (Classes imply Object Oriented Programming. 
Python _allows_ OOP but does not _require_ it -- and is irrelevant here.  Ignore anything I say 
about classes and OOP!)  For your example here, it wouldn't _match_ the BASIC syntax, but would 
be used in an equivalent way.


In fact, if you find yourself writing functions (or classes) that could be general-purpose 
routines, it is a trivial matter to put them into a personal library which you can then use in 
future programs.  You don't need to rewrite them, just use them.


Now, in practice, it takes a little care to write them as library functions.  That is, the 
original version may rely on some details of the original program, so the library version will 
need to be tweaked a bit to remove these 'local' dependencies.  But this is generally easily 
handled through the parameters to the functions.  Also they are probably written with a bit more 
care to handle error conditions (which Python calls exceptions, Python has very extensive 
exception handling).  This capability (a personal library) is enormously convenient.  While I am 
saying 'personal', I really mean library(s) available to everyone involved in a programming 
project.  No need for anyone to re-invent the wheel!  ;-)Python calls them modules rather 
than libraries, but it's the same thing.


 -=- Larry -=-

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


Re: Guido on python3 for beginners

2016-02-20 Thread Larry Hudson via Python-list

On 02/19/2016 06:36 PM, Steven D'Aprano wrote:

On Fri, 19 Feb 2016 02:39 pm, Rustom Mody wrote:


[snip]


But you can't do anything interesting with this language, so it is not
satisfying. On the other hand, here's "Hello World" in another language,
one which is Turing complete so it can do anything Python or C can do:

(=<`#9]~6ZY32Vx/4Rs+0No-&Jk)"Fh}|Bcy?`=*z]Kw%oG4UUS0/@-ejc(:'8dc

but the learning curve is steep enough that it will be frustrating rather
than interesting.

https://en.wikipedia.org/wiki/Malbolge



Somewhat OT, but speaking of "Hello World", check out:

http://www2.latech.edu/~acm/HelloWorld.shtml

It's a collection of "Hello World" programs in umpteen languages.
(Well, not really umpteen, but there are a lot of them.)   ;-)

 -=- Larry -=-

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


Re: Considering migrating to Python from Visual Basic 6 for engineering applications

2016-02-19 Thread Larry Hudson via Python-list

On 02/19/2016 10:14 AM, wrong.addres...@gmail.com wrote:
[snip]


This is precisely reading one character at a time. If not exactly reading one 
character, it is effectively looking at each character to assemble the number. 
Not a good sign. I guess there might be libraries which will help read numbers 
better, but I would expect a good language to be able to handle this basic 
thing for engineers - to read numbers like Fortran and Basic do.

Still, if I have misunderstood something, I will be glad to be corrected. I 
would generally know that the first three numbers will be floating point, the 
next will be something and then the next will be something else, etc. Does that 
help or does one still have to look at each character and determine how to 
place it in a number?

Thanks for your patience. I don't want surprises later on, which is why I am 
asking very stupid questions.

It absolutely does NOT require reading a character at a time!  You are reading the data from a 
text file, which means everything is a string.  These strings (or sub-strings) can represent 
integers, floats, dates, phone numbers or whatever.  Your example data implies a free-form 
style, where it is then necessary to determine the data type for each of these (sub)strings 
individually.  Of course, if your data has a defined fixed format, this is simplified -- but 
they are still initially strings that have to be converted.  String processing in Python is very 
powerful and versatile.


BTW, it does no good to continue to think strictly in BASIC techniques.  Python is a different 
language with a different approach to attacking problems.  If you try to write BASIC (or C or 
Java or ...) programs in Python syntax you'll just get bad programs.  Forget trying to find 
features in Python that are identical to the features of BASIC.  Python requires a different 
mind-set to use it properly -- just like any other language.


Here is a rather naive somewhat brute-force way to read your example data.  I'm using a Python 
list here to simulate the file reading.  (Actually, using read() instead of readline() will also 
give this list.)  Python lists are essentially the same as arrays in other languages, but much 
more powerful and versatile.  Two examples of the differences between arrays and lists are:  can 
use mixed data types, you are not restricted to all the same data type, and the size of lists 
are dynamic -- they grow or shrink as necessary.


Comments start with a #
Strings in Python can be delimited by single-quotes ('), double-quotes (") or triple-quotes (""" 
or ''').  Triple-quoted strings can be multi-line text.  The triple-quote here is used as what 
Python calls a docstring, which it saves internally for documenting your program.



#   Define a function to determine the data type a string represents
def chktyp(s):
"""Check string s for int, float or string.  Returns the data and a type 
code"""
try:
return int(s), 'int'  #  Try to convert to int, return it if 
successful
except ValueError:#  No, it's not an int
pass  #  Drop into float test
try:
return float(s), 'float'  #  Try to convert to float, return it if 
successful
except ValueError:#  No, it's not a float
return s, 'str'   #  It must be a string

#   Here is your (simulated) data as a list of strings
data = [
'2 12.657823 0.1823467E-04 114 0',
'3 4 5 9 11',
'"Lower"',#  Could be left simply as "Lower"
'278.15']

#   Process the data
for line in data: #  For each line of the data
dat = line.split()#  Make a list of the sub-strings in the line
for stng in dat:  #  For each substring
dt, tp = chktyp(stng) #  Get the data and the type
print('{} is a {}'.format(dt, tp))#  Print this data


Running this example gives this result:

2 is a int
12.657823 is a float
1.823467e-05 is a float
114 is a int
0 is a int
3 is a int
4 is a int
5 is a int
9 is a int
11 is a int
"Lower" is a str
278.15 is a float

I hope this gives you a slight hint about the Python way of doing things.  Yes, of course it's 
very different from BASIC, but if you can pick up on the Pythonic way of doing things I think 
you might at least find it useful.


 -=- Larry -=-

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


Re: Syntax error (The Python Book) Linux User and Developer Bookazine

2016-02-15 Thread Larry Hudson via Python-list

On 02/15/2016 07:06 AM, Joel Goldstick wrote:
[snip a lot...]


Learn Python the Hard Way is pretty good some people say.  Its online.
Also Diving into Python is online written by the now offline Mark Pilgrim.


I have a couple of "Hard Way" books and personally, I don't like his style of 
teaching.

Of course, take that as one person's opinion -- and as always, YMMV.   :-)

 -=- Larry -=-

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


Re: Cygwin and Python3

2016-02-09 Thread Larry Hudson via Python-list

On 02/09/2016 08:41 AM, Fillmore wrote:


Hi, I am having a hard time making my Cygwin run Python 3.5 (or Python 2.7 for 
that matter).
The command will hang and nothing happens.



Just curious...

Since Python runs natively in Windows, why are you trying to run it with Cygwin?
I'm not implying that you shouldn't, just offhand I don't see a reason for it.

 -=- Larry -=-


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


Re: x=something, y=somethinelse and z=crud all likely to fail - how do i wrap them up

2016-01-31 Thread Larry Hudson via Python-list

On 01/30/2016 10:29 PM, Veek. M wrote:
[snip]

Trivial comment (and irrelevant to your question)...

Replace your
print('-')
with the shorter
print('-' * 65)

Of course, feel free to disagree if you think the longer version is visually 
more obviously a line.

 -=- Larry -=-

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


Re: psss...I want to move from Perl to Python

2016-01-30 Thread Larry Hudson via Python-list

On 01/28/2016 04:01 PM, Fillmore wrote:


I learned myself Perl as a scripting language over two decades ago. All through 
this time, I
would revert to it from time to time whenever I needed some text manipulation 
and data analysis
script.

My problem? maybe I am stupid, but each time I have to go back and re-learn the 
syntax, the
gotchas, the references and the derefercing, the different syntax between Perl 
4 and Perl 5,
that messy CPAN in which every author seems to have a different ideas of how 
things should be
done

I get this feeling I am wasting a lot of time restudying the wheel each tim...

I look and Python and it looks so much more clean

add to that that it is the language of choice of data miners...

add to that that iNotebook looks powerful

Does Python have Regexps?

How was the Python 2.7 vs Python 3.X solved? which version should I go for?

Do you think that switching to Python from Perl is a good idea at 45?

Where do I get started moving from Perl to Python?

which gotchas need I be aware of?

Thank you


Check out this link:  http://www.linuxjournal.com/article/3882

It is an account of ESR's[1] first experiences going to Python from Perl.  It's somewhat old 
(2000), but a very interesting read.  And probably relevant to your questions.


 -=- Larry -=-

[1]  Eric S. Raymond

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


Re: pip install mitmproxy - fails on watchdog-0.8.3.tar.gz with "Permission denied" error (Python 2.7.11 on Win XP SP3);

2016-01-24 Thread Larry Hudson via Python-list

On 01/23/2016 11:43 AM, Steve Petrie, P.Eng. wrote:
[snip]

I'm not sure what your exact problem is, but I can say that it isn't
this; the Unix-style forward slash is perfectly legal under Windows
(and it's even legal to mix and match).

ChrisA


I never knew that the forward slash is legal under Windows -- thanks for the 
tip :)


A minor clarification...

If the path string is typed directly into Windows where it is parsed by (whatever is the current 
equivalent of) command.com, forward slashes are NOT accepted.  Because there it is used to 
indicate command-line options.


But if this string comes from a program where it is parsed by an API, it IS accepted.  And this 
has been the case even since MSDOS prior to Windows.


 -=- Larry -=-

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


Re: Need help on a project To :"Create a class called BankAccount with the following parameters "

2015-12-25 Thread Larry Hudson via Python-list

On 12/25/2015 06:04 PM, princeud...@gmail.com wrote:

#i have worked over 2hours only to get this: some-one help please
manipulate_data = []

[snip other incorrect nonsense...]


#this is the instruction:
Create a function manipulate_data that does the following

[snip...]

Let's start with your first mistake (because the rest is wrong because of this):

READ YOUR INSTRUCTIONS!
It says "Create a function..."

Your 'solution' creates a list.
A list is NOT a function.

 -=- Larry -=-

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


Re: Weird list conversion

2015-12-13 Thread Larry Hudson via Python-list

On 12/13/2015 12:05 PM, KP wrote:

On Sunday, 13 December 2015 11:57:57 UTC-8, Laura Creighton  wrote:

In a message of Sun, 13 Dec 2015 11:45:19 -0800, KP writes:

Hi all,

  f = open("stairs.bin", "rb")
  data = list(f.read(16))
  print data

returns

['=', '\x04', '\x00', '\x05', '\x00', '\x01', '\x00', '\x00', '\x00', '\x00', 
'\x00', '\x00', '\x00', '\x00', '\x00', '\x00']

The first byte of the file is 0x3D according to my hex editor, so why does 
Python return '=' and not '\x3D'?

As always, thanks for any help!


0x3d is the ascii code for '='


I am aware of that - so is the rule that non-printables are returned in hex 
notation whereas printables come in their ASCII representation?


No.  The data is returned as raw bytes.
It's the print that is responsible for the way these bytes are _displayed_.

 -=- Larry -=-

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


Re: HELP PLEASE printing single characters!

2015-12-03 Thread Larry Hudson via Python-list

On 12/02/2015 04:08 PM, John Strick wrote:

On Wednesday, December 2, 2015 at 12:58:30 PM UTC-6, Dylan Riley wrote:

hi all,
I have been trying to figure out all day why my code is printing single 
characters from my list when i print random elements using random.choice the 
elements in the list are not single characters for example when i print, 
print(LIST[random.choice]) i get:
["e", "x", "a", "m", "p", "l", "e"] when i should get ["example"].

my code is:
#Create a program that prints a list of words in random order.
#The program should print all the words and not repeat any.

import random

LIST = ["blue ", "red ", "yellow ", "green ", "orange "]
order = []

print("This game will print a random order of colours")
print("The list is", LIST)
input("press enter to start")



while LIST != []:
 choice = random.choice(LIST)
 order += choice
 while choice in LIST:
 LIST.remove(choice)
print(order)



input("press enter to exit")

thanks in advance guys


You could just shuffle the list first, then loop through it. This will 
guarantee that each color is only used once.


Not quite.  Only if the original list has no repetitions.

My personal approach would be to use a set to eliminate the duplicates, convert back to a list 
and shuffle that.


no_reps = list(set(LIST))
random.shuffle(no_reps)
print(no_reps)   #  Or use loop to print one-per-line

 -=- Larry -=-

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


Re: Late-binding of function defaults (was Re: What is a function parameter =[] for?)

2015-11-25 Thread Larry Hudson via Python-list

On 11/25/2015 12:32 AM, Chris Angelico wrote:

On Wed, Nov 25, 2015 at 7:14 PM, Antoon Pardon
 wrote:

[snip]


"Oh come on. It's basic arithmetic. You should be able to add 7 and
7... the result's 14!"

"But it's so confusing. Why can't it be 16? It'd be more convenient
for me if it were 16."


No.  It's 42.;-)

 -=- Larry -=-



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


Re: anyone tell me why my program will not run?

2015-11-22 Thread Larry Hudson via Python-list

On 11/21/2015 06:44 PM, Larry Hudson wrote:

On 11/20/2015 07:30 PM, Dylan Riley wrote:

i am learning python and was tasked with making a program that flips a coin 100 
times and then
tells you
the number of heads and tails.


[snip]


import random

heads = int("1")
tails = int("2")
flips = 100
headscount = 0
tailscount = 0

while flips != 0:
 flips -= 1

result = random.randint(heads, tails)
if result = heads:
 headscount += 1
else:
 tailscount += 1


print(headscount, tailscount)

[snip]



It doesn't run because it if full of errors, which have already been discussed 
by others.

I just wanted to show you a (radically) different approach that you can study 
(or not... your
choice).  I'm leaving out your heading and just showing the heart of the 
program.  I am not
necessarily recommending this, I just wanted you to see a different way of 
looking at the
problem.  Except for the initialization and printing of the results, the entire 
thing is done in
one two-line for loop.


from random import randint

#  Put your heading text here...

HEADS = 0
TAILS = 1#  Note:  Python _convention_ is to upper-case constants.
counts = [0, 0]

for flips in range(100):
 counts[randint(0, 1)] += 1

print('Number of heads: ', counts[HEADS])
print('Number of tails: ', counts[TAILS])


Note that the HEADS and TAILS constants are only used in one place (the final 
print functions),
you could simply leave them out and directly use 0 and 1 in those final 
print()s.

  -=- Larry -=-



I purposely didn't give any explanation of this code in my original message because I wanted to 
allow people (particularly the OP) a chance to figure it out by themselves. But here's a bit of 
explanation...


The counts variable is a two-element list. It's usage is, the count of heads is counts[0] and 
the count of tails is counts[1] -- or equivalently, counts[HEADS] and counts[TAILS]. Both values 
are initialized to 0.


The body of the for loop is the very terse (and confusing?) expression:
counts[randint(0, 1)] += 1

But if you break it down and look at the pieces individually, it's not too hard 
to understand.
1. randint(0, 1) gives a random value of either 0 or 1.
2. counts[...] gives you access to the heads count or tails count (... is the 0 or 1 from the 
randint() function).

3. counts[...] += 1 increments the appropriate counter value.

Broken down that way it’s not too hard to understand, is it?   :-)

-=- Larry -=-

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


Re: anyone tell me why my program will not run?

2015-11-21 Thread Larry Hudson via Python-list

On 11/20/2015 07:30 PM, Dylan Riley wrote:

i am learning python and was tasked with making a program that flips a coin 100 
times and then tells you
the number of heads and tails.

I have done so coming up with this piece of work but it doesnt run can anyone 
help me out?

#This is credited to dylan

print(" \\ \\ \\ \\ \\ \\ \\ \\ D FLIPS \\ \\ \\ \\ \\ \\ \\ \\")
print("\n\nThis is D's coin flipper program. You get 100 flips. \n\t LETS SEE HOW 
LUCKY YOU ARE")
input("Press enter")

import random

heads = int("1")
tails = int("2")
flips = 100
headscount = 0
tailscount = 0

while flips != 0:
 flips -= 1

result = random.randint(heads, tails)
if result = heads:
 headscount += 1
else:
 tailscount += 1


print(headscount, tailscount)

input("press enter to exit")


It doesn't run because it if full of errors, which have already been discussed 
by others.

I just wanted to show you a (radically) different approach that you can study (or not... your 
choice).  I'm leaving out your heading and just showing the heart of the program.  I am not 
necessarily recommending this, I just wanted you to see a different way of looking at the 
problem.  Except for the initialization and printing of the results, the entire thing is done in 
one two-line for loop.



from random import randint

#  Put your heading text here...

HEADS = 0
TAILS = 1#  Note:  Python _convention_ is to upper-case constants.
counts = [0, 0]

for flips in range(100):
counts[randint(0, 1)] += 1

print('Number of heads: ', counts[HEADS])
print('Number of tails: ', counts[TAILS])


Note that the HEADS and TAILS constants are only used in one place (the final print functions), 
you could simply leave them out and directly use 0 and 1 in those final print()s.


 -=- Larry -=-

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


Re: Question about math.pi is mutable

2015-11-13 Thread Larry Hudson via Python-list

On 11/13/2015 01:19 AM, Denis McMahon wrote:

On Fri, 13 Nov 2015 09:04:54 +1100, Steven D'Aprano wrote:


On Fri, 13 Nov 2015 07:40 am, Thomas 'PointedEars' Lahn wrote:



[crap I expect]



And you should consider the irony, and hypocrisy, of somebody who signs
his posts "PointedEars" bitching about supposed "real names".


TPEL has been trolling html, php and javascript newsgroups for years,
recently he seems to have discovered python newsgroups. :(

I found that TPEL post to be particularly amusing/ironic (hilarious, really) when he continued 
by talking about a group that ignores posts by people who don't use real names!   :-)

I generally ignore his posts as well.

 -=- Larry -=- <-- My real name, which is NOT Lawrence (or anything 
similar)!

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


Re: What is wrong in this example code?

2015-11-12 Thread Larry Hudson via Python-list

On 11/12/2015 06:07 AM, fl wrote:

On Thursday, November 12, 2015 at 8:58:33 AM UTC-5, fl wrote:

Hi,




 def tick(self):
 """ Time will be advanced by one second """
 if self.__seconds == 59:
 self.__seconds = 0
 if (self.__minutes == 59):
 self.__minutes = 0
 self.__hours = 0 if self.__hours==23  else self.__hours+1
else:
self.__minutes += 1;
else:
 self.__seconds += 1;



Nothing to do with your original question, just a trivial suggestion which you are free to 
ignore.  You can shorten this tick() method by using the divmod() function.  It does a division 
and returns both the quotient AND the remainder.  IOW, given divmod(x, y) it returns the tuple 
(x/y, x%y).  It is a very useful function.  Try this:


def tick(self):
xtra, self._seconds = divmod(self._seconds + 1, 60)
xtra, self._minutes = divmod(self._minutes + xtra, 60)
self._hours += xtra

Explanation:  (to shorten this, I'm leaving off the leading "self._" from the 
actual code.)
The first divmod() sets xtra = (seconds+1) / 60, which is the 'overflow' if any, from the 
division by 60, and seconds is the updated seconds limited to 0-59 (the result of (seconds+1) % 
60).  The second divmod() does the same thing to update minutes (if xtra != 0) and xtra is set 
to the 'overflow' from that division, which is then added to hours.


More confusing perhaps, but definitely shorter.
As I said above, use it if you want or ignore it if it's too confusing.

 -=- Larry -=-

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


Re: using binary in python

2015-11-10 Thread Larry Hudson via Python-list

On 11/10/2015 12:14 PM, Dennis Lee Bieber wrote:

On Mon, 9 Nov 2015 22:20:25 -0800, Larry Hudson via Python-list
 declaimed the following:


Of course it can.  The only difference a text file and a binary file is the way 
it's opened.
Text files are opened with 'r' or 'w', while binary files are opened with 'rb' 
or 'wb'.  Being
different modes, the reading/writing is handled differently.  One obvious 
difference, the lines
of a text file are marked by ending them with a newline character, so it's easy 
to read/write
the text line-by-line.  But the data in a binary file is completely arbitrary 
and is much


To be strict -- a text file has  system defined means of marking
line endings. UNIX/Linux uses just a  character; Windows uses the pair
. TRS-DOS used just  for end of line. Some operating systems
may have used count-delimited formats (and then there is the VMS FORTRAN
segmented records with start and end segment bits).

The main purpose of my message was to get across the idea of separating the actual data (as 
binary values) and the way this data is displayed (to the user/programmer).  They are two 
entirely different concepts, and the OP was obviously confused about this.  But of course, 
you're right -- I was careless/imprecise in some of my descriptions.


 -=- Larry -=-

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


Re: using binary in python

2015-11-09 Thread Larry Hudson via Python-list
Your questions are somewhat difficult to answer because you misunderstand binary.  The key is 
that EVERYTHING in a computer is binary.  There are NO EXCEPTIONS, it's all binary ALL the time. 
 The difference comes about in how this binary data is displayed and manipulated.  I want to 
emphasize, ALL the DATA is binary.


On 11/08/2015 01:27 PM, kent nyberg wrote:

Hi there,
Lets say I want to play around with binary files in python.
Opening and using files in python is something that I think I've sort of got 
the hang of.
The thing im wondering about is binary files.
While searching for binary and python I started reading about bin().
I can use bin() to convert integers to binary.


No.  It doesn't convert anything.  It takes the integer data (which is internally binary) and 
gives you a _string_ representing that value in a binary format.  The same with hex() and oct() 
which give _strings_ of text corresponding to those formats.  The original integer data is 
unchanged -- and is still internally binary data.



Now, I thought..  some way it should be possible to write "binary" files.
That is, non ascii-files.  For example, on Linux, if I run the command 'less' 
on a binary;
for example /bin/ls, then the command asks me if I really want to do it, since 
its a binary file.
I know why, since the non ascii-stuff messes up the terminal, and most likely 
since you rarely want to
look at a binary file with less.


Not so much that it's rare, it's just that the less (and similar) commands expect the _binary 
data_ that it is given represents text encoded in ascii, utf-8, whatever...  And ls is a 
executable program not text.  So less (or the like) tries to display that data as text, and of 
course, the result is garbage.  (GIGO)


If you really want to look at a non-text file this way, there are utilities to do this properly, 
like hexdump.



Well, lets assume I want to write and read binary.  How is it done?
The built in bin() function only converts integers to binary but the variable 
or return is still just letters right?
Converting the integer '1' to binary with bin() return 0b1. Which is ok. Its 
the binary representation of integer 1.
But since.. there is files which contains data that is not representable as 
ascii, then I assume it can be written.
But can it by Python?


Of course it can.  The only difference a text file and a binary file is the way it's opened. 
Text files are opened with 'r' or 'w', while binary files are opened with 'rb' or 'wb'.  Being 
different modes, the reading/writing is handled differently.  One obvious difference, the lines 
of a text file are marked by ending them with a newline character, so it's easy to read/write 
the text line-by-line.  But the data in a binary file is completely arbitrary and is much 
trickier to handle (is an individual piece of data 1 byte, two bytes, 12,428 bytes or...)  Once 
again I'll emphasize that the _data_ in a text file is binary, it's just that these binary data 
values represent text codes.  The data in a binary file can represent anything, a program, a 
.jpg picture, .mp3 music, a company Personnel record, or anything else.


BTW, I talk about text codes as a generic term -- there are many choices of how 
text is encoded.


Ok, I get the feeling now that its hard to understand my question. I assume in 
the C language its just matter of
writing a complex struct with strange variables and just write it to a file. 
But in python..?


There is no essential difference between how C and Python handle binary files.  The principles 
are the same, only the details differ.  You can ignore comparing to C here.



Can some one give a short explenation of a python write to file, that makes it 
a binary file?


A short explanation, probably not in a newsgroup post.  Try searching the web for Python binary 
files, or similar search terms.  Then sit down and play!  ;-)



Thanks alot,  and forgive me for my stupid questions. :)
/Kent Nyberg


It's not a stupid question, but is is based on your misunderstanding of binary.  Don't give up, 
you'll get it!  Just keep in mind that _ALL_ the underlying _DATA_ is binary, it is just how 
this data is displayed and manipulated that makes the differences.  And it is important that you 
understand the difference between the actual (binary) data and the way it is displayed -- these 
are two entirely different things.


Sorry that I'm not more specific on the 'how' to use binary files, but the subject is more 
complex than a simple explanation can properly give.


 -- Larry -=-

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


Re: What does “grep” stand for?

2015-11-06 Thread Larry Hudson via Python-list

On 11/06/2015 05:25 AM, William Ray Wing wrote:



On Nov 5, 2015, at 10:36 PM, Larry Hudson via Python-list 
 wrote:


[snip]

You’re not REALLY an old timer unless you’ve used TECO.

-Bill


Agreed.  I'm not really and old-timer, just old (I'm 78).

My first exposure to computers was the MITS Altair, (around late '75) and my computer use has 
always been hobby-oriented, never professional.  I only know of TECO by reputation, not 
experience.   :-)


 -=- Larry -=-

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


Re: What does “grep” stand for?

2015-11-05 Thread Larry Hudson via Python-list

On 11/05/2015 05:18 PM, Dennis Lee Bieber wrote:

On Thu, 5 Nov 2015 20:19:39 + (UTC), Grant Edwards
 declaimed the following:


Though I used a line-editor for a while on VMS, I was never very good
at it, and abanded it for a full-screen editor at he first
opportunity.  But, if you ever get a chance to watching somebody who
_is_ good at 'ed', it's something you'll remember...


I didn't convert to EDT until DEC dropped SOS... And then shortly later
I keymapped the Blaise ([Alcor] Pascal) editor on the TRS-80 Mod-III to
replicate EDT (as much as possible, given only three function keys on the
numeric pad)

The Amiga used to have two standard editors -- a screen editor and a
line editor; as I recall the line editor supported a file window, so one
could edit large files by making a single direction pass using a smaller
window and a script. Later the screen editor gained ARexx support, so one
could script it using ARexx. (And by then they also included a form of
microEMACS, my C compiler had a look-alike vi editor... and a later C
compiler had another editor integrated to the compiler so that error
message reports could trigger the editor to open the file and move to the
error position)


Anyone besides me remember the CP/M editor Mince (Mince Is Not Complete EMACS)?
It was an emacs-like editor, without any e-Lisp or other way of extending it.  I believe it was 
my first exposure to a screen-oriented editor.  I quite liked it at that time (but that was a 
looonnng time ago!)


 -=- Larry -=-

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


Re: GoPiGo script

2015-11-02 Thread Larry Hudson via Python-list

On 11/02/2015 11:31 AM, Robin Koch wrote:

Am 02.11.2015 um 15:32 schrieb input/ldompel...@casema.nl:


Thank you for the explanation for it.
I must tell you that  i yust beginning with python.
I bought the book beginning programming with python.


Have you programming experience with other languages?

Well, the very first thing you should have learned is the basic syntax of 
Python. (That's how a
program has to be written to work properly.)

And one of those first things is that python code is structured not by braces 
(like many other
programming languages), but by intendation (as mentioned by others before).

 ^^^

[snip a lot of text, also using the word intend...]

The word you want is indent not intend.
Intend means something entirely different,
and is not a Python term.

 -=- Larry -=-

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


Re: Execute Python Scripts

2015-10-14 Thread Larry Hudson via Python-list

On 10/14/2015 10:04 AM, Cai Gengyang wrote:

So I am going through this article on Python for newbies 
---http://askpython.com/execute-python-scripts/

Managed to create a file with these contents :

1 #!/usr/bin/env python3
2
3 print('hello world')

and saved it as hello.py


You did write that file _without_ the line numbers, I hope.

Line numbers are sometimes used in text to discuss a Python program, but they are _NOT_ used in 
an actual program.


-=- Larry -=-

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


Re: Learning Modules, Arguments, Parameters (imma noob)

2015-09-25 Thread Larry Hudson via Python-list

You've already received a lot of answers and guidance, but here is on more 
point...

On 09/25/2015 12:03 PM, Cody Cox wrote:
[snip]

 this I am not sure about, I set Kilo=get_input(kilo), ...


Watch your capitalization!  Kilo is _NOT_ the same as kilo.  Case is significant in Python (as 
well as in many other programming languages).


Also, as has already been pointed out:  what you want here is kilo=get_input().  Along with the 
corresponding change to the get_input() definition.  This function does NOT need a passed parameter.


-=- Larry -=-

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


Re: Learning Modules, Arguments, Parameters (imma noob)

2015-09-24 Thread Larry Hudson via Python-list

On 09/24/2015 11:45 AM, codyw...@gmail.com wrote:

I seem to be having a problem understanding how arguments and parameters work, 
Most likely why my code will not run.
Can anyone elaborate on what I am doing wrong?

'''
Cody Cox
9/16/2015
Programming Exercise 1 - Kilometer Converter
Design a modular program that asks the user to enter a distance in kilometers 
and then convert it to miles
Miles = Kilometers * 0.6214
'''

def main():
get_input()
convert_kilo()


  def get_input(kilo):
kilo = float(input('Enter Kilometers: '))
return kilo

  def convert_kilo(kilo,miles):
  miles = float(kilo * 0.6214)
  print( kilo,' kilometers converts to ',miles,' miles')

  main()


--
> def main():
>...
I'm going to discribe this last

>   def get_input(kilo):
> kilo = float(input('Enter Kilometers: '))
> return kilo
>
1)  def get_input(kilo):  has a leading space.  This is an indenting error
2)  You use parameters to send data TO the function, NOT to return it (generally, there are 
exceptions).  Leave out the kilo, you want simply 'def get_input():'

3)  The body,  kilo = ... and return ..., is ok, but can be shortened to a 
single line:
return float(input('Enter Kilometers: '))

>   def convert_kilo(kilo,miles):
>   miles = float(kilo * 0.6214)
>   print( kilo,' kilometers converts to ',miles,' miles')
>
1)  Again indenting error, and miles (an output) is not needed as a parameter.
2)  miles = float(kilo * 0.6214):  kilo and 0.6214 are already floats.  There is no need to 
_convert_ to float.  Doesn't hurt, but it is redundant.
3)  The print is acceptable, but has unnecessary spaces.  Print() by default puts a space 
between the items, so using spaces inside the strings gives you double-spaces, one from the 
print() and one from the string.


> def main():
> get_input()
> convert_kilo()
>
1)  get_input() as you have it written requires a parameter, you are not giving it one. 
However, as I explained above, get_input() should not have a parameter anyway.

2)  get_imput() returns a value (kilo), but here you are throwing it away.  
This needs to be:
kilo = get_input()
3)  convert_kilo() _requires_ a parameter, you are not giving one.  And it does NOT need the 
second (miles) parameter that you originally wrote.  What you want is:

   convert_kilo(kilo)

I hope you can make sense out of my explanations.

 -=- Larry -=-

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


Re: Pipes

2015-08-10 Thread Larry Hudson via Python-list

On 08/10/2015 01:43 PM, E.D.G. wrote:
[snip]

   It has been my experience that researchers, particularly scientists, 
need to have some
versatile and powerful programming language available that is compatible with 
the Windows
operating system.  The language needs to make certain resources available to 
the researchers.
And in some form it should ultimately be compatible with other operating 
systems.

[snip]

This is just a comment that may or may not be worthwhile...

I just ran across a new O'Reilly book, Effective Computation in Physics (subtitle: Field Guide 
to Research with Python), ISBN: 978-1-491-90153-3.  It seems to cover all the subjects you bring 
up, and specifically uses Python.


I have only glanced through it and I'm not ready to comment on it myself -- (Aside:  I was once 
a physics major (unfortunately unsuccessful), but that was a loonnngg time ago.)  But 
quoting the blurb on the back cover...



More physicists today are taking on the role of software development as part of their research, 
but software development isn't always easy or obvious, even for physicists.  This practical book 
teaches essential software development skills to help you automate and accomplish nearly any 
aspect of research in a physics-based field.


Written by two PhDs in nuclear engineering, this book includes practical examples drawn from a 
working knowledge of physics concepts.  You'll learn now to use the Python programming language 
to perform everything from collecting and analyzing data to building software and publishing 
your results.



I don't know if a book is relevant to your needs, but I thought it was worth 
mentioning.

 -=- Larry -=-

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


Re: Who uses IDLE -- please answer if you ever do, know, or teach

2015-08-07 Thread Larry Hudson via Python-list

On 08/05/2015 06:06 PM, Terry Reedy wrote:
[snip]

0. Classes where Idle is used:
Where?
Level?


None


Idle users:

1. Are you
grade school (1=12)?
undergraduate (Freshman-Senior)?
post-graduate (from whatever)?


Some college, but didn't complete.
Never had any CS or programming courses.


2. Are you
beginner (1st class, maybe 2nd depending on intensity of first)?
post-beginner?


post-beginner (and self-taught)


3. With respect to programming, are you
amateur (unpaid)
professional (paid for programming)


amateur

My situation:  Amateur/hobbyist programmer.  (Retired from electronics industries.)  My 
programming needs are very modest -- mostly simple utilities for my own use.  In the past used C 
extensively, C++ some.  But after I found Python I haven't looked back.


Programming environment:  Linux Mint (hate Windows!).  Using simple editor (usually gedit) and a 
terminal window, but I usually have Idle running (minimized) to be able to quickly check syntax, 
run help(...), etc.  I rarely use it for actual programming.


One minor complaint about Idle:  In the interactive mode the auto-indent uses a tab character 
which the display expands to 8-character columns.  This large indent is annoying.  The editor 
mode can be set for smaller indents but the interactive mode can't -- at least I haven't found 
how if it is possible.


 -=- Larry -=-

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


Re: Most pythonic way of rotating a circular list to a canonical point

2015-08-03 Thread Larry Hudson via Python-list

On 08/02/2015 01:58 PM, Joonas Liik wrote:

I have this feeling that you would get a lot more useful anwsers if
you were to describe your actual problem in stead of what you think
the solution is. There might be other, better solutions but since we
know so little about what you are doing we will likely never find them
by just guessing..

Sorry if I wasn't clear.  This is not _my_ problem, this was intended to re-state the OP's 
fundamental problem.  And the quoted text was the OP's original message.  I felt that most 
(anyway many) responders here were missing this point.


This is what I saw as the OP's underlying problem, but as I also said in my message, my 
interpretation certainly could be wrong.:-)


 -=- Larry -=-

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


Re: Most pythonic way of rotating a circular list to a canonical point

2015-08-02 Thread Larry Hudson via Python-list

On 08/01/2015 01:34 PM, Lukas Barth wrote:

Hi!

I have a list of numbers that I treat as "circular", i.e. [1,2,3] and [2,3,1] 
should be the same. Now I want to rotate these to a well defined status, so that I can 
can compare them.

If all elements are unique, the solution is easy: find the minimum element, 
find its index, then use mylist[:index] + mylist[index:], i.e. the minimum 
element will always be at the beginning.

But say I have [0,1,0,2,0,3]. I can in fact guarantee that no *pair* will 
appear twice in that list, i.e. I could search for the minimum, if that is 
unique go on as above, otherwise find *all* positions of the minimum, see which 
is followed by the smallest element, and then rotate that position to the front.

Now that seems an awful lot of code for a (seemingly?) simple problem. Is there 
a nice, pythonic way to do this?

Thanks for enlightening me!

Lukas



Let me try to re-state what I see is your actual problem.  (Of course I could 
be wrong...)   ;-)

Most of the answers you have been getting concentrate on comparisons and hashes, but those are 
irrelevant to your need -- they come later.  What you are trying to do is to uniquely and 
independently determine the "starting point" for the rotation.  That is, which element will be 
rotated to index 0.  Using the minimum is possible, but that fails if that minimum appears more 
than once in the list -- it does not give a unique solution.


For a specific example...  if you are given any _one_ of these lists:
[1, 5, 0, 3, 0], [5, 0, 3, 0, 1], [0, 3, 0, 1, 5], [3, 0, 1, 5, 0], [0, 1, 
5, 0, 3]
it can be _independently_ rotated to (for example) [3, 0, 1, 5, 0]

That example does not use the minimum as the starting point, but how the starting point can be 
absolutely and uniquely determined is your fundamental problem.  I do not have an answer for 
that.  But I thought this might be a clearer description of what I think you are really looking for.


I hope I'm right.   ;-)   Good luck.

 -=- Larry -=-

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


Re: Noob in Python. Problem with fairly simple test case

2015-07-16 Thread Larry Hudson via Python-list

On 07/15/2015 08:11 PM, Chris Angelico wrote:

On Thu, Jul 16, 2015 at 1:01 PM, Larry Hudson via Python-list
 wrote:

On 07/15/2015 05:11 AM, Chris Angelico wrote:



[snip]



In addition to using print(), in some places I like using input() instead,
as in:
 input('x={}, y={} --> '.format(x, y))
Then the program stops at that point so you can study it.
To continue just press , or Ctrl-C to abort.


That's a neat trick, as long as you actually do have a console. IIDPIO
is extremely general (works across languages, across frameworks (eg a
web server), etc), but these kinds of extensions are pretty handy when
they make sense.

ChrisA

Actually, that was an (unstated) point -- it's handy where it _can_ be used and makes sense, but 
it is certainly not a universal technique.


Also I didn't specifically point out the '-->' that I use at the end of the string as an input 
prompt.  Obviously, optional as well.


 -=- Larry -=-

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


Re: Noob in Python. Problem with fairly simple test case

2015-07-15 Thread Larry Hudson via Python-list

On 07/15/2015 05:11 AM, Chris Angelico wrote:

On Wed, Jul 15, 2015 at 9:44 PM, Jason P.  wrote:

I can't understand very well what's happening. It seems that the main thread 
gets blocked listening to the web server. My intent was to spawn another 
process for the server independent of the test. Obviously I'm doing something 
wrong. I've made several guesses commenting pieces of code (tearDown method for 
example) but I didn't manage to solve the problem(s).



When you find yourself making guesses to try to figure out what's
going on, here are two general tips:

1) Cut out as many pieces as you can. Test one small thing at a time.
2) If In Doubt, Print It Out! Stick print() calls into the code at key
places, displaying the values of parameters or the results of
intermediate calculations - or just saying "Hi, I'm still here and I'm
running!".


In addition to using print(), in some places I like using input() instead, as 
in:
input('x={}, y={} --> '.format(x, y))
Then the program stops at that point so you can study it.
To continue just press , or Ctrl-C to abort.

 -=- Larry -=-

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


Re: Why doesn't input code return 'plants' as in 'Getting Started with Beautiful Soup' text (on page 30) ?

2015-07-12 Thread Larry Hudson via Python-list

On 07/12/2015 05:48 AM, Simon Evans wrote:

Dear Peter Otten,
Yes, I have been copying and pasting, as it saves typing. I do get 'indented 
block' error responses as a small price

> to pay for the time and energy thus saved.
>
You CANNOT ignore indenting.
Indenting is NOT optional, it is REQUIRED by Python syntax.
Changing indenting TOTALLY changes the meaning.

> Also Console seems to reject for 'indented block' reasons better known to 
itself, copy and
> pasted lines that it accepts and  are exactly the same on the following line 
of input.
>
As above, that is Python syntax.

> Maybe it is an inbuilt feature of Python's to discourage copy and pasting.
>
Absolutely not.  As noted above, this is the way Python is defined to work.

 -=- Larry -=-

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


Re: Using Python instead of Bash

2015-06-01 Thread Larry Hudson via Python-list

On 05/31/2015 05:42 AM, Cecil Westerhof wrote:

I help someone that has problems reading. For this I take photo's of
text, use convert from ImageMagick to make a good contrast (original
paper is grey) and use lpr to print it a little bigger.

I''m wondering why you bother to take a photo, which then has to be adjusted for quality.  A 
screen-capture program is much easier and immediately gives you a perfect(?) starting image.


Linux Mint that I use has the program 'gnome-screenshot' (in the main menu under Accessories as 
'Screenshot').  It gives you the options to capture the whole screen, the current active window, 
or any arbitrary rectangular area of the screen.  It saves it as a .png and allows you to 
specify the path/filename to save it.  I'm sure there are many other equivalent programs 
available as well, and this one or others are likely available by default in other Linux 
distros.  Or easily installed if not.


Of course, this just gives you the original 'raw' image that you can then process further as 
necessary.  But this is _FAR_ easier and better quality than the round-about method of using a 
camera.


 -=- Larry -=-

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


Re: Where is 'palindrome' defined?

2015-06-01 Thread Larry Hudson via Python-list

On 05/31/2015 09:46 PM, fl wrote:

Hi,

When I search solution of reverse a string/number, I came across a short
function online:


def palindrome(num):

return str(num) == str(num)[::-1]

I thought that it is a general function. And with the following variable:


a

'1234_'


parlindrome(a)


Traceback (most recent call last):
   File "", line 1, in 
 parlindrome(a)
NameError: name 'parlindrome' is not defined


Then, I find that parlindrome is a special checking mirrored word.
I use Python 2.7.9. Why does the error message show

name 'parlindrome' is not defined



Thanks,


Don't be embarrassed, everybody does this:  You're blind to your own typos...

You define palindrome() then call parlindrome() -- with an extra 'r'.

 -=- Larry -=-

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