Re: [Tutor] Looking for some direction

2019-05-11 Thread Marc Tompkins
On Sat, May 11, 2019 at 12:05 PM Cranky Frankie 
wrote:

> 2) For wxPython I'm finding a lot of the documentation is outdated.


I'm a fan of wxPython myself, for a number of reasons - it suits the way I
think, and the applications it generates look native to the platform
they're running on, as opposed to the way Java apps always seem look a
little odd whether you run them on Windows or Mac.  wxPython is a Python
wrapper around the wxWidgets library (written in C, I believe); any time
I've found the wxPython documentation lacking, the wxWidgets docs filled in
the gaps.  But the best documentation of all is the wxPython demo app; it
contains working examples - with modifiable source code - for nearly every
wxPython control, plus a few user-contributed extra controls.
There's also an excellent mailing list (wxpython-us...@googlegroups.com)
which is a great place to get help.

The downsides:
 - there's no (working) WYSIWYG code generation tool - wxGlade is so bad
it's worse than nothing
 - layout is controlled by sizers in a model that might be different from
what you're used to; failure modes if/when you screw up are surprising and
nonintuitive.  (Not disastrous, just confusing.)  Make sure to include the
Layout Inspection Tool while you're codebashing, and comment it out for
production!

Welcome to Python (and wxPython, I hope) - enjoy!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "Python not recognized as a command"

2018-09-01 Thread Marc Tompkins
On Sat, Sep 1, 2018 at 10:40 AM, Dana O'Connor 
wrote:

> Hi,
> I've been trying to download and use Python 3.7 for the past few days and
> every time I try to open it it tells me I don't have "pip" which should be
> impossible because this version of Python is supposed to automatically come
> with pip (?).  Additionally, whenever I open the command prompt on my
> computer, the command "python" is not even recognized by the system even
> though Python is downloaded onto the computer.  I cannot use Python at all
> until I figure out this problem, so I guess my overall question is why
> doesn't my computer acknowledge Python when it has been downloaded (and
> redownloaded) several times on my computer?
>

A bit more on Alan's point:
I believe that your question is a bit more of an operating system question
than purely a Python question; I also suspect (though I could be wrong)
that your previous experience has been with iOS or Android, and that you're
relatively unfamiliar with older desktop operating systems.
In iOS and Android, programs are packaged in such a way (and the package
installer is configured in such a way) that "downloading" and "installing"
are practically the same thing.  Apple OSx is nearly as seamless, and the
various Linux distros have been trying to move in this direction as well.
Even Windows - with "Universal" apps in Windows 8 and 10 - has been moving
in this direction.

But traditional "desktop"-side Windows, and traditional Windows programs
such as Python, still leave many details to the the user, and so the
process involves a few steps:
-  You download the installer.  This is actually a combination package: a
compressed archive of the actual program you want, wrapped up with a
program that knows how to unpack the archive, distribute its contents to
the appropriate locations, and register its various bits with the operating
system.
-  Once you've downloaded the installer, you run it, and it does its
magic.  It may prompt you to make some choices about where to put things.
-  Now that you've installed the program (Python in this case), you can run
it.  BUT - when you type a command at the prompt, the operating system
needs to know where to find the program file to fulfill your request.
That's where the PATH comes in - it's a list of locations where the OS can
look for, e.g. "python.exe" when you type "python" at the prompt.
-  PATH is a system variable, and it should be set by the installer when
you run it.  But the installer is a program, and sometimes programs fail.
So it's possible that you'd need to fix that; it's easy to do, but we need
more info first.

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


Re: [Tutor] try, except syntax

2018-08-02 Thread Marc Tompkins
try... except is meant to catch errors: places where your program would
otherwise crash.  It does NOT work as a truth check.
In your example:

> try:
> type(uvc) == float
> except TypeError as e:
> print(e, msg)
>
> "type(uvc)==float" resolves to a standalone True or False, not an
exception.  What you want in that case is an assertion:

>   try:
>   assert type(uvc)==float
>   except AssertionError as e:
>   print(e, msg)


An assertion says "The following statement is True.  If it isn't, I'm going
to throw an exception."  They're especially useful when writing tests, and
should be part of your flow-control toolbox.

In your last two examples,

> if type(uvc) != float:
> raise TypeError("Bad argument provided. And this is also old test."
> " The value of UVC must be a float. This is old test")
> if uvc < 0.0 or uvc > 1.0:
> raise ValueError("Bad argument provided. The value of uvc must be "
>  "greater than 0.0 and less than 1.0. This is old
> test")


I assume you must either already be using try/except, or else never getting
incorrect input; if you raise an exception but don't catch it, the program
terminates.  I would wrap those thusly:

> try:
>   if type(uvc) != float:
>   raise TypeError("Bad argument provided. And this is also old test."
>   " The value of UVC must be a float. This is old
> test")
>   if uvc < 0.0 or uvc > 1.0:
>   raise ValueError("Bad argument provided. The value of uvc must be "
>"greater than 0.0 and less than 1.0. This is old
> test")
> except Error as e:
>   print(e,msg)


Generally, however, my approach is to use if/then for normal program flow,
and wrap those in try/except for cases where e.g. user error may cause
crashes.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] SSL Error

2018-08-01 Thread Marc Tompkins
On Wed, Aug 1, 2018 at 1:13 AM, Alan Gauld via Tutor 
wrote:

> On 01/08/18 05:07, Saket Mehrotra wrote:
> > Hi
> >
> > I am also not using any Open SSL package.
> > I have just added  " import requests" in py file. And when I run the
> module
> > I   get the SSL package error ,not sure why.
>
> Then you really need to send the complete error message
> and the code that generates it - the full function
> definition at least.
>

THIS.
Give us the _whole_ error message, even the parts that look like they don't
make any sense.  For one thing, the traceback tells us exactly which line
of code triggered the exception - and which file that line of code came
from.  From your description, it sounds like the error is being thrown by
the requests module, but we can't tell.

I've just taken a look at the source for "requests"; it never asks for
 PROTOCOL_SSLv23
specifically, so I don't know where that's coming from.  PROTOCOL_SSLv23 is
a constant in the standard-library ssl module, but not in pyopenssl.  (You
mentioned that you uninstalled pyopenssl, but requests imports it - so
there must be another copy of it on your machine somewhere?)

I can't emphasize this enough: the right way to ask questions is also the
easiest way - cut and paste.  Don't paraphrase, don't edit, don't try to be
creative or descriptive.  Just give us the entire error message and
traceback, and we can go from there.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] SSL Error

2018-07-31 Thread Marc Tompkins
On Tue, Jul 31, 2018 at 10:03 AM, Alan Gauld via Tutor 
wrote:

> On 31/07/18 03:52, Saket Mehrotra wrote:
>
> > error  ssl.PROTOCOL_SSLv23: OpenSSL.SSL.SSLv23_METHOD,
> > AttributeError: module 'ssl' has no attribute 'PROTOCOL_SSLv23'
>
> Are you sure you spelled the attribute correctly?
>
> Have you tried
>
>
> >>> import ssl
> >>> dir(ssl)
>
> Top see what the attribute names look like?
> Is PROTOCOL_SSLv23 one of them?
>
> What I was getting at earlier: it isn't clear, without seeing his code,
whether he's directly asking for PROTOCOL_SSLv23, or whether it's an
internal result of a call he made.  If it's the first, then the problem is
with his code; if it's the second, it's a problem with how the package is
built on his machine.  Really can't tell without context.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] SSL Error

2018-07-31 Thread Marc Tompkins
This is a general Python tutor group; I'm not sure anybody here can help
you with the OpenSSL package (I've definitely never used it myself.)  We're
all willing to help, but this might not be the right place to ask this
question.

More to the point, though, when you ask questions on this list it's best to
just cut and paste BOTH your code and the actual error message/traceback;
from the bit that you've posted, it sounds like it might be as simple as a
typo, but we can't really tell without seeing your code.

On Mon, Jul 30, 2018 at 7:52 PM, Saket Mehrotra 
wrote:

> Hi
>
> I am trying to run import requests in a py file but I am getting below
> error  ssl.PROTOCOL_SSLv23: OpenSSL.SSL.SSLv23_METHOD,
> AttributeError: module 'ssl' has no attribute 'PROTOCOL_SSLv23'
> >>>
>
> I tried to execute below from the terminal but it still remains unresolved.
>
> sudo easy_install --upgrade pip
>
> I've also had to run:
>
> sudo pip uninstall pyopenssl
>
> sudo pip install mozdownload
>
>
> Can you please help me .
>
> Thanks & Regards
> Saket Mehrotra
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] confused about Pypi

2017-10-29 Thread Marc Tompkins
On Sat, Oct 28, 2017 at 1:43 PM, Mark Anderson 
wrote:

> Hello, I am currently doing an online course to learn Python. Generally
> ive followed it well and am enjoying my first go at programming. However
> the description of how to get modules from PyPi has left me confused. Ive
> only recently downloaded python so it already has pip installed. As I
> understand it I have to write certain text into the command prompt (I’m
> using windows 10). It tells me that python -m is not recognised.
> Can anyone help please
>

I strongly recommend the excellent "pip-Win" utility.  It's a very small
download and a very quick install; it figures out your various virtual
environment(s) and makes everything incredibly easy.  I feel like I'm
cheating by using it, frankly, but the fact is that I like my tools to work
for ME, not the other way around; I came here to use Python, not fight with
command-line syntax.

https://sites.google.com/site/pydatalog/python/pip-for-windows
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Am I missing something obvious about "FizzBuzz"?

2017-10-01 Thread Marc Tompkins
On Sun, Oct 1, 2017 at 12:48 PM, Alan Gauld via Tutor 
wrote:

> But to address another issue raised by Mats:
> > Probably the best programming test there is look at code
> > that's already been developed,
>
> Very true and in an ideal world what you would do, but...
>
> It is what we did with the bug finding test. But, as alluded
> to by Steve, it's really hard to do this for anything
> significant in an interview, since you would need to be
> familiar with the system's framework and libraries since
> most code consists of calls to libraries.


First off, a confession: I'm an English major, not CS or IT.  But this
conversation reminded me of my interview for (what turned out to be) my
first-ever programming job.  I'd been working as BOFH (operating a
System/360) for a few months, and heard about a better job in an HP shop
closer to where I lived.  So I applied, and during the course of the
interview I discovered that it was a blended position: programming during
the day, operator in the evening.  I kept a poker face, and when I was
asked whether I'd written any COBOL I lied and said yes.  (I knew the name,
but had never seen a line of code - only BASIC and Pascal up to that time.)
My test was, fortunately for me, not a start-from-scratch FizzBuzz problem,
but debugging a report module that was on the department's "to-fix" list.
It took me about twenty-five minutes to find the problem (it was an
off-by-one bug, as I recall), most of which was taken up translating COBOL
to Pascal in my head...  I got the job, and went straight to the local
university bookstore and bought every book I could find on COBOL.  Good
times, good times...
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dictionaries are same but returning false

2017-07-05 Thread Marc Tompkins
On Wed, Jul 5, 2017 at 9:51 AM, Ashfaq  wrote:

> Hi Peter,
> The way you find the issue is really cool! Very cool! :)
>
>
I agree - that is very cool.  But I have also made this sort of mistake a
few times, and found it by using a very quick, low-tech method...
"Unfold" the lines of the two dictionary specifications and put them one
above the other - I usually just cut'n'paste into a text editor and delete
the newlines.  If the two unfolded lines don't line up (which these
wouldn't, because one has extra quotes in it) the error will be immediately
visible.  Subtler typos will be harder to spot, but still much easier than
trying to compare two folded paragraphs several lines apart.

Not nearly as sophisticated, but sometimes quick'n'dirty is best.


> On Wed, Jul 5, 2017 at 6:10 PM, shubham goyal 
> wrote:
>
> > Thank you Peter.
> > Silly mistakes 
> >
> > On Jul 5, 2017 5:10 PM, "Peter Otten" <__pete...@web.de> wrote:
> >
> > > shubham goyal wrote:
> > >
> > > > null=None
> > > > x={'_udp_options': None, '_icmp_options': None, 'attribute_map':
> > > > {'icmp_options': 'icmpOptions', 'protocol': 'protocol', 'source':
> > > > {'source',
> > > > 'tcp_options': 'tcpOptions', 'is_stateless': 'isStateless',
> > > 'udp_options':
> > > > 'udpOptions'}, '_is_stateless': False, 'swagger_types':
> > {'icmp_options':
> > > > 'IcmpOptions', 'protocol': 'str', 'source': 'str', 'tcp_options':
> > > > 'TcpOptions', 'is_stateless': 'bool', 'udp_options': 'UdpOptions'},
> > > > '_protocol': '6', '_source': '0.0.4.0/24', '_tcp_options': {
> > > >   "destination_port_range": {
> > > > "max": "22",
> > > > "min": "22"
> > > >   },
> > > >   "source_port_range": null
> > > > }}
> > > >
> > > > y={'_udp_options': None, '_icmp_options': None, 'attribute_map':
> > > > {'icmp_options': 'icmpOptions', 'protocol': 'protocol', 'source':
> > > > {'source',
> > > > 'tcp_options': 'tcpOptions', 'is_stateless': 'isStateless',
> > > 'udp_options':
> > > > 'udpOptions'}, '_is_stateless': False, 'swagger_types':
> > {'icmp_options':
> > > > 'IcmpOptions', 'protocol': 'str', 'source': 'str', 'tcp_options':
> > > > 'TcpOptions', 'is_stateless': 'bool', 'udp_options': 'UdpOptions'},
> > > > '_protocol': '6', '_source': '0.0.4.0/24', '_tcp_options': {
> > > >   "destination_port_range": {
> > > > "max": 22,
> > > > "min": 22
> > > >   },
> > > >   "source_port_range": null
> > > > }}
> > > > if x==y:
> > > > print "true"
> > > > else:
> > > > print "false"
> > > >
> > > >
> > > > These dictionaries are same exactly. but its returning false. i don't
> > > > understand
> > > > what to do?
> > >
> > > Let's narrow down the problem, with the help of the interactive
> > > interpreter:
> > >
> > > >>> changed = [k for k in x if x[k] != y[k]]
> > > >>> changed
> > > ['_tcp_options']
> > > >>> k, = changed
> > >
> > > A closer look:
> > >
> > > >>> x[k]
> > > {'source_port_range': None, 'destination_port_range': {'max': '22',
> > 'min':
> > > '22'}}
> > > >>> y[k]
> > > {'source_port_range': None, 'destination_port_range': {'max': 22,
> 'min':
> > > 22}}
> > >
> > > So x uses strings for min/max while y uses integers, and those do not
> > > compare equal in Python:
> > >
> > > >>> 22 == "22"
> > > False
> > >
> > > Once you fix this
> > >
> > > >>> x[k]["destination_port_range"]["max"] = 22
> > > >>> x[k]["destination_port_range"]["min"] = 22
> > >
> > > you get the expected result:
> > >
> > > >>> x == y
> > > True
> > >
> > >
> > > ___
> > > Tutor maillist  -  Tutor@python.org
> > > To unsubscribe or change subscription options:
> > > https://mail.python.org/mailman/listinfo/tutor
> > >
> > ___
> > Tutor maillist  -  Tutor@python.org
> > To unsubscribe or change subscription options:
> > https://mail.python.org/mailman/listinfo/tutor
> >
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Thread Object integration with GPIO

2017-04-30 Thread Marc Eymard
Hello there,

I have hooked up an ultrasonic sensor to my Raspberry Pi-enabled robot
in order to get continuous distance-to-obstacle reading.

The sensor is properly connected via GPIO and already reads the distance
properly when running a simple script.

However, I need to integrate the sensor reading logic to an existing
script provided by PiBorg called YetiBorg.py

The way I have decided to go about implementing the sensor reading is by
creating a Thread object and update the distance attribute of this very
same object from the run() function. The idea is to encapsulate the
distance reading within the sensor object as much as possible by i.
creating a sensor/thread object and by ii. avoiding global variables.

Below the script I have come up along with the error print.
I believe there are multiple issues, but at least it gives an idea of
what I currently want to achieve and how.

Can a charitable soul advise whether my approach makes sense and whether
I am using the right type of object for the task at hands?

I am looking for guidance and willing try completely different
approach/objects if necessary.

Thanks in advance for sending me into the right direction.
Marc

Python Shell

2.7.9

OS-

Raspian Pixel on Raspberry Pi Zero



---traceback



Traceback (most
recent call last):

File
"/home/pi/Desktop/distance sensor class object.py", line
57, in 


SensorA = Sensor(interval=1, gpio_trig=23, gpio_echo=24)

File"/home/pi/Desktop/distance sensor class object.py", line
23, in __init__self.start()


RuntimeError:
thread.__init__() not called





--sensor.py-


import threading
import RPi.GPIO as GPIO
import time

#GPIO Mode (BOARD / BCM)
GPIO.setmode(GPIO.BCM)

class Sensor(threading.Thread):

"""ultrasonic sensor continous distance reading at given interval in 
seconds"""

def __init__(self,interval, gpio_trig, gpio_echo):
self.inter = interval
self.trig = gpio_trig
self.echo = gpio_echo

#set GPIO pins direction (IN / OUT)
GPIO.setup(gpio_trig, GPIO.OUT)
GPIO.setup(gpio_echo, GPIO.IN)

self.dist = 0
self.terminated = False
self.start()

def run(self):
while not self.terminated:
# set Trigger to HIGH
GPIO.output(gpio_trig, True)

# set Trigger to LOW after 0.01ms
time.sleep(0.1)
GPIO.output(gpio_trig, False)

StartTime = time.time()
StopTime = time.time()

# save StartTime
while GPIO.input(gpio_echo) == 0:
StartTime = time.time()

# save time of arrival
while GPIO.input(gpio_echo) == 1:
StopTime = time.time()

# time difference between start and arrival
TimeElapsed = StopTime - StartTime
# multiply by sonic speed (34300 cm/s)
# and divide by 2, because there and back
self.dist = (TimeElapsed * 34300) / 2

time.sleep(self.inter)

def get_dist(self):
return self.dist

#Sensor object "instanciated" with GPIO programmable pins 23 and 24
SensorA = Sensor(interval=1, gpio_trig=23, gpio_echo=24)

try:
while True:
print("Measured Distance = %.1f cm" % SensorA.get_dist())
except KeyboardInterrupt:
GPIO.cleanup()
SensorA.terminated = True



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


[Tutor] Thread Object integration with GPIO

2017-04-29 Thread Marc Eymard
Hello there,

I have hooked up an ultrasonic sensor to my Raspberry Pi-enabled robot 
in order to get continuous distance-to-obstacle reading.

The sensor is properly connected via GPIO and already reads the distance 
properly when running a simple script.

However, I need to integrate the sensor reading logic to an existing 
script provided by PiBorg called YetiBorg.py

The way I have decided to go about implementing the sensor reading is by 
creating a Thread object and update the distance attribute of this very 
same object from the run() function. The idea is to encapsulate the 
distance reading within the sensor object as much as possible by i. 
creating a sensor/thread object and by ii. avoiding global variables.

Attached the script I have come up with, which keeps returning multiple 
run time errors whenever I try to fix it.
I believe there are multiple issues, but at least it gives an idea of 
what I currently want to achieve and how.

Can a charitable soul advise whether my approach makes sense and whether 
I am using the right type of object for the task at hands?

I am looking for guidance and willing try completely different 
approach/objects if necessary.

Thanks in advance for sending me into the right direction.
Marc

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


Re: [Tutor] Count for loops

2017-04-11 Thread Marc Tompkins
On Tue, Apr 11, 2017 at 9:48 AM, Rafael Knuth 
wrote:

> I tested this approach, and I noticed one weird thing:
>
> Pi_Number = str(3.14159265358979323846264338327950288419716939)
> Pi_Number = "3" + Pi_Number[2:]
> print(Pi_Number)
>
> == RESTART: C:\Users\Rafael\Documents\01 - BIZ\CODING\Python
> Code\PPC_56.py ==
> 3141592653589793
> >>>
>
> How come that not the entire string is being printed, but only the
> first 16 digits?
>

That's due to how str() works; it's simply making (its own conception) of a
pretty representation of what's fed to it, which in the case of
floating-point numbers means that they're represented to 16 digits
precision.
str(3.14159265358979323846264338327950288419716939) is _not_ the same as
"3.14159265358979323846264338327950288419716939"

>From the docs: "Return a string containing a nicely printable
representation of an object. For strings, this returns the string itself.
The difference with repr(object) is that str(object) does not always
attempt to return a string that is acceptable to eval()
; its goal is to
return a printable string."
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question to Phyton and XBee

2017-04-11 Thread Marc Tompkins
On Tue, Apr 11, 2017 at 9:12 AM, Daniel Berger  wrote:

>Hello,
>
>I have installed the modules to control xbee with Python
>https://pypi.python.org/pypi/XBee). Afterwards I have set the path
>variable on C:\Python27\python-xbee-master and also the subdirectories.
> To
>check, if the modules are available, I have written the code as
>recommended (https://pypi.python.org/pypi/XBee)
>
># Import and init xbee device
>from xbee import XBee
>import serial
>import arduino
>
>The interpreter gave the error message
>File "C:/Users/daniel/PycharmProjects/hardware_test/test_xbee.py",
> line 2,
>in 
>from xbee import XBee
>ImportError: No module named xbee
>
>I have done the same with https://github.com/nioinnovation/python-xbee
> and
>it have the same effect.
>As I'm not very familiar with Python, I would like to know, what is
> going
>wrong and how I can find the module.
>

How did you install it?  If you use the very simplest method -  "pip
install xbee" - it should automatically take care of the path for you.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How do we create a GUI to run a simple calculation program in Python?

2017-04-04 Thread Marc Tompkins
On Tue, Apr 4, 2017 at 9:55 AM, Lisa Hasler Waters 
wrote:

> Hello Tutor,
>
> A middle school student of mine created a program to calculate simple and
> compound interest. He built it in PyCharm EDU using a Mac running 10.11.6.
>
> He would like to create a GUI to run this program. Please, can you advise
> on how he could build this?
>
> Others have mentioned Tkinter and HTML; I''d like to put in my two cents'
worth for wxPython .  HTML is probably the best
cross-platform solution, and requires the least extra stuff bolted on, but
wxPython lets you create desktop apps that look like they were actually
developed for the computer they run on.

Alan Gauld's comments about separating the GUI from the program logic are,
as usual, spot-on.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor Digest, Vol 157, Issue 39

2017-03-19 Thread Marc Sebek
Hi Rafael

You are appending quit to the list, before checking to see if quit has been
typed. You could move the "if Statement" up in the code and add an else
statement, so Quit is not appended to the list first thing.

while True:
activity = input(prompt)

if activity == "quit":
print("Let me recap. This is what you've done today: %s." % ",
" .join(LogActivities))
   else:
LogActivities.append(activity)

But you have an infinite loop here too, so unless you are adding more to
this, and plan to get out the loop, you should also add a break statment:

if activity == "quit":
print("Let me recap. This is what you've done today: %s." % ",
" .join(LogActivities))
   break ###<<< wrote:

> Send Tutor mailing list submissions to
> tutor@python.org
>
> To subscribe or unsubscribe via the World Wide Web, visit
> https://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body 'help' to
> tutor-requ...@python.org
>
> You can reach the person managing the list at
> tutor-ow...@python.org
>
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Tutor digest..."
>
> Today's Topics:
>
>1. tiny, little issue with list (Rafael Knuth)
>
>
> -- Forwarded message --
> From: Rafael Knuth 
> To: "Tutor@python.org" 
> Cc:
> Bcc:
> Date: Sun, 19 Mar 2017 13:17:03 +0100
> Subject: [Tutor] tiny, little issue with list
> LogActivities = []
> prompt = ("What have you done today? ")
> prompt += ("Enter 'quit' to exit. ")
>
> while True:
> activity = input(prompt)
> LogActivities.append(activity)
>
> if activity == "quit":
> print("Let me recap. This is what you've done today: %s." % ",
> " .join(LogActivities))
>
> This program is supposed to take user input and to log his activities
> into a list.
> All works well, only when the user quits, the program adds 'quit' to
> LogActivities.
> How do I prevent my program from doing this?
>
> Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900
> 32 bit (Intel)] on win32
> Type "copyright", "credits" or "license()" for more information.
> >>>
> = RESTART: C:/Users/Rafael/Documents/01 - BIZ/PYTHON/Python
> Code/PPC_159.py =
> What have you done today? Enter 'quit' to exit. shower
> What have you done today? Enter 'quit' to exit. walk the dog
> What have you done today? Enter 'quit' to exit. drink coffee
> What have you done today? Enter 'quit' to exit. prepare lunch
> What have you done today? Enter 'quit' to exit. take coding lesson
> What have you done today? Enter 'quit' to exit. quit
> Let me recap. This is what you've done today: shower, walk the dog,
> drink coffee, prepare lunch, take coding lesson, quit.
> What have you done today? Enter 'quit' to exit.
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> https://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Problem with Spyder IDE in Anaconda3

2017-02-27 Thread Marc Tompkins
On Mon, Feb 27, 2017 at 12:52 PM, Stephen P. Molnar <s.mol...@sbcglobal.net>
wrote:

> On 02/27/2017 02:29 PM, Marc Tompkins wrote:
>
>> On Mon, Feb 27, 2017 at 10:46 AM, Stephen P. Molnar
>> <s.mol...@sbcglobal.net <mailto:s.mol...@sbcglobal.net>> wrote:
>>
>> I had sent the following message to Anaconda Support:
>>
>> I have just installed anaconda3-4.3.0 and upgraded Spyder to v-3.1.3.
>>
>> When I open Spyder and run a python script that has run perfectly in
>> a previous  version of Spyder I get the results that I expect,but
>> with 'Kernel died, restarting' and I get a new iPython console
>> prompt. Also a popup that asks 'Do  you want to close this
>> console?'.  If I answer 'No' I get the following in the Internal
>> Console:
>>
>>
>> Spyder Internal Console
>>
>> This console is used to report application
>> internal errors and to inspect Spyder
>> internals with the following commands:
>>spy.app, spy.window, dir(spy)
>>
>> Please don't use it to run your code
>>
>>  >>> WARNING:traitlets:kernel restarted
>> Traceback (most recent call last):
>>File
>> "/home/comp/Apps/anaconda3/lib/python3.6/site-packages/qtcon
>> sole/base_frontend_mixin.py",
>> line 163, in _dispatch
>>  handler(msg)
>>File
>> "/home/comp/Apps/anaconda3/lib/python3.6/site-packages/spyde
>> r/widgets/ipythonconsole/namespacebrowser.py",
>> line 192, in _handle_execute_reply
>>  super(NamepaceBrowserWidget, self)._handle_execute_reply(msg)
>>File
>> "/home/comp/Apps/anaconda3/lib/python3.6/site-packages/qtcon
>> sole/jupyter_widget.py",
>> line 184, in _handle_execute_reply
>>  super(JupyterWidget, self)._handle_execute_reply(msg)
>>File
>> "/home/comp/Apps/anaconda3/lib/python3.6/site-packages/qtcon
>> sole/frontend_widget.py",
>> line 492, in _handle_execute_reply
>>  self._request_info['execute'].pop(msg_id)
>> KeyError: '50af986d-2e5c-4cef-aef4-827370619c86'
>>
>> Very strange, and most annoying.
>>
>> I received an answer:
>>
>> I know a solution for this problem. I guess you are using Kaspersky
>> product. You need to add "python.exe", and "pythonw.exe" of Anaconda
>> specific into Exclusions list and make them trusted applications.
>>
>>
>> Where would I find such a list?  There is no mention of such a list
>> in the Debian Handbook and a Google search didn't find anything that
>> I could see would apply to solution to this problem.  Nothing I
>> found about the Kaspersky product told me where (or how) to find an
>> exclusion list.
>>
>>
>> With the usual caveats that your question isn't Python-specific, here's
>> the page from Kaspersky's website on how to create exclusions:
>> https://support.kaspersky.com/2695#block2
>>
>> But: are you actually running Kaspersky Antivirus on a Debian machine?
>> Nothing wrong with that if so, but it's pretty unusual.  If not, then
>> you need to push the Anaconda people a bit harder for ideas.
>>
>
>
> To the best of my knowledge I am not running any anti-virus software. This
> has always been a Linux computer and there has been no need.
>
> In fact, this has only happened since I had to reinstall Debian v8.5 and
> all of the upgrades.
>
>
In that case, their answer was completely irrelevant to your problem.  I'm
afraid I don't know Anaconda at all, nor the Spyder IDE, so I really don't
have any insight - and, since this is the Python Tutor list, I don't know
whether anyone else here will either.  The Anaconda Community is probably
your best bet:
https://www.continuum.io/anaconda-community

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


Re: [Tutor] Problem with Spyder IDE in Anaconda3

2017-02-27 Thread Marc Tompkins
On Mon, Feb 27, 2017 at 10:46 AM, Stephen P. Molnar 
wrote:

> I had sent the following message to Anaconda Support:
>
> I have just installed anaconda3-4.3.0 and upgraded Spyder to v-3.1.3.
>
> When I open Spyder and run a python script that has run perfectly in a
> previous  version of Spyder I get the results that I expect,but with
> 'Kernel died, restarting' and I get a new iPython console prompt. Also a
> popup that asks 'Do  you want to close this console?'.  If I answer 'No' I
> get the following in the Internal Console:
>
>
> Spyder Internal Console
>
> This console is used to report application
> internal errors and to inspect Spyder
> internals with the following commands:
>   spy.app, spy.window, dir(spy)
>
> Please don't use it to run your code
>
> >>> WARNING:traitlets:kernel restarted
> Traceback (most recent call last):
>   File 
> "/home/comp/Apps/anaconda3/lib/python3.6/site-packages/qtconsole/base_frontend_mixin.py",
> line 163, in _dispatch
> handler(msg)
>   File "/home/comp/Apps/anaconda3/lib/python3.6/site-packages/spyde
> r/widgets/ipythonconsole/namespacebrowser.py", line 192, in
> _handle_execute_reply
> super(NamepaceBrowserWidget, self)._handle_execute_reply(msg)
>   File 
> "/home/comp/Apps/anaconda3/lib/python3.6/site-packages/qtconsole/jupyter_widget.py",
> line 184, in _handle_execute_reply
> super(JupyterWidget, self)._handle_execute_reply(msg)
>   File 
> "/home/comp/Apps/anaconda3/lib/python3.6/site-packages/qtconsole/frontend_widget.py",
> line 492, in _handle_execute_reply
> self._request_info['execute'].pop(msg_id)
> KeyError: '50af986d-2e5c-4cef-aef4-827370619c86'
>
> Very strange, and most annoying.
>
> I received an answer:
>
> I know a solution for this problem. I guess you are using Kaspersky
> product. You need to add "python.exe", and "pythonw.exe" of Anaconda
> specific into Exclusions list and make them trusted applications.
>
>
> Where would I find such a list?  There is no mention of such a list in the
> Debian Handbook and a Google search didn't find anything that I could see
> would apply to solution to this problem.  Nothing I found about the
> Kaspersky product told me where (or how) to find an exclusion list.
>
>
With the usual caveats that your question isn't Python-specific, here's the
page from Kaspersky's website on how to create exclusions:
https://support.kaspersky.com/2695#block2

But: are you actually running Kaspersky Antivirus on a Debian machine?
Nothing wrong with that if so, but it's pretty unusual.  If not, then you
need to push the Anaconda people a bit harder for ideas.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What is wrong with my Python program that causes it to run but not give results?

2016-10-25 Thread Marc Tompkins
On Oct 25, 2016 3:07 PM, "Ed Troy"  wrote:
>I get an error message:
> edward@ubuntu:~$ python LED_model_utf8.py LED_IV.txt
> Traceback (most recent call last):
>   File "LED_model_utf8.py", line 4, in 
> import matplotlib.pyplot as plt
> ImportError: No module named matplotlib.pyplot
>

That last line tells you what you need to know:  Python can't find the
pyplot module, which is part of matplotlib.  In other words, you're missing
at least one of the required dependencies; there may be others once you've
resolved this one.

The tutorial you're following should tell you how to install the
dependencies;  either you've missed a step, or the author has.  If it's not
in the tutorial,  Google "matplotlib" for instructions on installing it.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Help me out please

2016-07-19 Thread Marc Sànchez Quibus
Hi,
First of all I'm gonan introduce myself. My name is Marc and I'm a student
and also a python's programmer begginer. I've been studying/learning python
and now I need some help to finish my project.
I have two scripts, one of them in python (the main script) and the other
one written in html. Well, is just a brief javascript (an app) that I took
by Github. I need to change a variable inside this html script. I was
wondering wether I could change this variable from my python script or not.
Is there some way to do it?
Thanks in advance and sorry for the inconvenience.

-- 
*Marc Sànchez Quibus*
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Newbie question: programs not printing

2016-03-10 Thread Marc Tompkins
On Thu, Mar 10, 2016 at 5:33 AM, Patrick Craine 
wrote:

> >>> x = int(raw_input('Enter an integer: '))
> if x%2 == 0:
> print 'Even'
> else:
> print 'Odd'
> if x%3 != 0:
> print 'And not divisible by 3'
> Enter an integer: 3
> >>>
>
> It could be your email program that's messing with your indentation, but
to me it looks like you're not indenting at all.  And that would be a
problem - Python is whitespace-aware, and indentation levels are crucial.
Try this (if, that is, MY indentation doesn't get trashed!):

if x%2 == 0:
print 'Even'
else:
print 'Odd'
if x%3 != 0:
print 'And not divisible by 3'




0
viruses found. www.avast.com

<#DDB4FAA8-2DD7-40BB-A1B8-4E2AA1F9FDF2>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Beginner: Socket object and packets

2015-12-05 Thread Marc Eymard

Hi tutor,

I am trying to locate the first blank line in the first received packet 
when pinging an internet server using a socket object.


My assumption is there will be a mandatory blank line right after the 
http headers in accordance with the http protocol.


Consider the following:

import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect( ('www.py4inf.com/code/', 80) )
mysock.send('GET http://www.py4inf.com/code/' + ' HTTP/1.0\n\n')
data_str = mysock.recv(700)

My question:

Why is the following statement False when there is an actual blank line 
in the received packet:

'\n\n' in data

The statement 'any_string in data' works fine with any character except 
the double line drop i.e. '\n\n'.


Attached full script for your consideration.

Thanks in advance for your guidance,
Marc


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


Re: [Tutor] Creating lists with definite (n) items without repetitions

2015-09-07 Thread Marc Tompkins
On Fri, Sep 4, 2015 at 7:28 AM, marcus lütolf 
wrote:

> I should probably tell you the real task are a series (maximum ~ 301)
> lists in which real names  of people are assigned to the items/letters for
> 2 people(golfers) can be in  the same list(flight)  only once for an
> extended period of time.
> The next step would be to assign compatible and noncompatible attributes
> to the items/letters which will reduce the maximum of possible
> lists(flights)
>
>
I came up with this (obviously it could be made shorter, but I thought it
would be clearer this way):

import string, itertools

def main():
validCombos = []
usedPairs = []
allCombos = itertools.combinations(string.ascii_lowercase, 3)
for combo in allCombos:
pair1 = (combo[0],combo[1])
pair2 = (combo[0],combo[2])
pair3 = (combo[1],combo[2])
if pair1 in usedPairs or pair2 in usedPairs or pair3 in usedPairs:
next
else:
usedPairs.append(pair1)
usedPairs.append(pair2)
usedPairs.append(pair3)
validCombos.append(combo)
print(validCombos)
print(len(validCombos))
if __name__ == '__main__':
main()


The resulting triplets seem to meet your criteria - but there are only 90
of them.  How confident are you about the number 301?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] About using list in a function

2015-08-19 Thread Marc Tompkins
On Wed, Aug 19, 2015 at 10:25 AM, Alan Gauld alan.ga...@btinternet.com
wrote:

 On 19/08/15 17:09, Michelle Meiduo Wu wrote:

 Hi there,
 I'm trying to use List in a function. But it doesn't work. Here are
 sample code not work: ---def
 getResult():ls = []ls= ls.append(100)ls= ls.append(200)
 return ls
 reList = []reList = getResult()lsLength = len(reList)print '\n The length
 of the list is:' + str(lsLength)-I
 ran the above code, there is an error message: AttributeError: 'NoneType'
 object has no attribute 'append'
 But the code below not using list in a function
 works.--### This works:ls =
 []ls.append(100)ls.append(200)lsLength = len(ls)print '\n list length is: '
 + str(lsLength)- Do you
 know  the reason?
 Thank you,Michelle


 As you can (hopefully!) see above, this message is completely scrambled.
 Normally that means HTML. But the headers suggest it is plain text.
 Also, I see that Steve replied with a correctly formatted inclusion.

 Did anyone else get the scrambled version?
 And does anyone have any clues why I did?

 (Using Thunderbird v31.8 and normally not having major issues.)

 Same here, using Gmail and usually pretty happy with it.

Completely off-topic: why such an old version of TBird?  I have some
clients (the local office of a large multinational) who need to communicate
with corporate... but corporate IT hasn't dropped SSL 3.0 yet, so they
can't upgrade past version 33. (Every couple of weeks, despite my repeated
attempts to stop TBird from auto-updating, I find that they've got a new
version and can't connect.  Fortunately Mozilla hasn't changed their DB
format, so I can just re-install 33.)  Anyway, I know why _they_ are using
an old, less-secure version, but I'm curious why anybody else would be.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] About using list in a function

2015-08-19 Thread Marc Tompkins
On Wed, Aug 19, 2015 at 11:36 AM, Emile van Sebille em...@fenx.com wrote:

 On 8/19/2015 11:20 AM, Marc Tompkins wrote:

 (Every couple of weeks, despite my repeated
 attempts to stop TBird from auto-updating, I find that they've got a new
 version and can't connect.  Fortunately Mozilla hasn't changed their DB
 format, so I can just re-install 33.)  Anyway, I know why _they_ are using
 an old, less-secure version, but I'm curious why anybody else would be.


 We're stuck on 29 due to some ECMAScript compatibility issues with
 existing internal servers.

Interesting.  There are eight million stories in the naked city; I wonder
how many stories there are behind old software versions?  =D


 We keep users from upgrading by configuring all user workstations to
 update only from an internal server where we have only approved compatible
 sources/packages.

 I only dream of having that sort of control.  Ah well.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dave Angel

2015-08-18 Thread Marc Tompkins
Thank you very much - and thanks to Dave for his contributions over the
years.

On Tue, Aug 18, 2015 at 1:49 AM, Alan Gauld alan.ga...@btinternet.com
wrote:

 Many members of the list will remember Dave Angel as a regular and active
 participant over many years. However, Dave has not been active on the list
 for a little while.

 I regret to inform you that Dave passed away at the end of May.
 There is an obituary here:

 http://www.monaghanfunerals.com/obits/obituary.php?id=552157

 I have left a message of condolence on behalf of the tutor list.

 Alan G.
 List moderator.

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

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


Re: [Tutor] Pep 8, about indentation

2015-08-10 Thread Marc Tompkins
On Aug 10, 2015 12:17 PM, David Rock da...@graniteweb.com wrote:
 Yeah, BS is more accurate (although BS says Delete on my keyboard).
 Gotta love consistency :-)

I'm guessing you use a Mac, then...?
Whenever I have to use a Mac keyboard,  the lack of a Delete/relabeling of
the Backspace key drives me nuts.

The explanation I've heard is why would I need to delete what I haven't
typed yet?
Grrr.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is there a way to store and later use comparison operators (, =, =, =, ) ?

2015-04-29 Thread Marc Tompkins
On Wed, Apr 29, 2015 at 1:10 PM, boB Stepp robertvst...@gmail.com wrote:

 Python 2.4.4, Solaris 10.

 I have some functions that I believe I could collapse into a single
 function if I only knew how:

 def choose_compare(operator, value0, value1, pass_color, fail_color):
 
 Perform the comparison indicated by operator. Return pass_color if
 true, fail_color if false.
 
 if operator == '':
 return less_than(value0, value1, pass_color, fail_color)
 elif operator == '=':
 return less_than_or_equal(value0, value1, pass_color, fail_color)
 elif operator == '=':
 return equal(value0, value1, pass_color, fail_color)
 elif operator == '':
 return greater_than(value0, value1, pass_color, fail_color)
 elif operator == '=':
 return greater_than_or_equal(value0, value1, pass_color,
 fail_color)
 else:
 print 'WarningMessage = Invalid comparison operator in
 function, choose_compare().@Please contact script administrator for
 assistance.;'

 def less_than(value0, value1, pass_color, fail_color):
 
 See if value0 is less than value1. If true, return pass_color. If
 false, return fail_color.
 
 if value0  value1:
 return pass_color, True
 else:
 return fail_color, False

 def less_than_or_equal(value0, value1, pass_color, fail_color):
 
 See if value0 is less than or equal to value1. If true, return
 pass_color. If false, return fail_color.
 
 if value0 = value1:
 return pass_color, True
 else:
 return fail_color, False

 ... 3 more functions ...

 I won't give the remaining functions for the other comparison
 operators. The string variable, operator, is originally populated from
 a data file, which tells what type of comparison needs to be made. The
 last two functions I gave (and the ones I omitted giving) all follow
 the same exact pattern. I know there has to be some way to replace
 these 5 functions with 1, but what experimentation I have done to date
 has not worked.

 Also, what about the first function above? I could use 2 dictionaries,
 1 for calling the 5 functions and one to pass the arguments, but is it
 worth doing this? Or, I would not be surprised if there is a much
 better way! ~(:))

 Thanks!


Here's what I came up with:

def choose_compare(operator, value0, value1, pass_color, fail_color):
comps = {=:==, :, :, =:=, =:=}
if operator in comps.keys():
operator = comps[operator]
if eval({} {} {}.format(value0, operator, value1)):
return pass_color, True
else:
return fail_color, False
else:
print('WarningMessage')

I would ordinarily avoid eval() like the plague, but I think that this
sanitizes the input pretty effectively.  I had to make comps a dict instead
of a list because (in your example, anyway) you're using a single equals
sign to check for equality, which throws a Syntax Error (e.g.  if 1 = 2
instead of if 1 == 2).
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Pun panic, was Re: calling a method directly

2015-04-21 Thread Marc Tompkins
On Tue, Apr 21, 2015 at 7:09 AM, Martin A. Brown mar...@linux-ip.net
wrote:

 And, I dairy not chase this pun any further


No - keep milking it.  It gets butter all the time.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] bin to dec conversion puzzlement

2015-04-20 Thread Marc Tompkins
On Apr 20, 2015 6:56 AM, Jim Mooney cybervigila...@gmail.com wrote:

 I can't seem to get my head around this 'simple' book example of
 binary-to-decimal conversion, which goes from left to right:

 B = '11011101'
 I = 0
 while B:
 I = I * 2 + int(B[0])
 B = B[1:]

 print(I)
  221

 My thought was to go from right to left, multiplying digits by successive
 powers of two, and adding, like so:

 B = '11011101'
 sum = 0

 for exp, num in enumerate(reversed(B)):
 sum += int(num) * 2**exp

 print(sum)
  221

 Both methods work but I just can't see how the first one does. Am I
missing
 something obvious

Start from 0.
As long as there are any digits left,
a) Multiply by 2, add the leftmost digit.
b) Chop off the leftmost digit.
Lather, rinse, repeat.

It _does_ seem counterintuitive to do it from the left, but it's actually
quite simple.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] GUI

2015-02-02 Thread Marc Tompkins
On Mon, Feb 2, 2015 at 9:13 AM, Alan Gauld alan.ga...@btinternet.com
wrote:

 Don't expect a whole heap of support from the GUIs. A lot of the work will
 have to come from you.
 I suspect the standard GUI framework Tkinter is not going to be your best
 bet. You might find that PyQt or PyGTK will offer better multi lingual
 support  (although thats just a guess on my part!).


Might I also suggest wxPython?  I tried Tk and Qt early on, but found that
wx fit my needs much better (and I like the looks of the result better too.)
I have little to no experience with LTR handling myself, but there's a very
good, active support list for wxPython and I suspect that someone on that
list may have insights that can help...
wxpython-us...@googlegroups.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] GUI

2015-02-02 Thread Marc Tompkins
On Mon, Feb 2, 2015 at 1:18 PM, Mark Lawrence breamore...@yahoo.co.uk
wrote:

 On 02/02/2015 20:59, Marc Tompkins wrote:

 On Mon, Feb 2, 2015 at 9:13 AM, Alan Gauld alan.ga...@btinternet.com
 wrote:

  Don't expect a whole heap of support from the GUIs. A lot of the work
 will
 have to come from you.
 I suspect the standard GUI framework Tkinter is not going to be your best
 bet. You might find that PyQt or PyGTK will offer better multi lingual
 support  (although thats just a guess on my part!).


 Might I also suggest wxPython?  I tried Tk and Qt early on, but found that
 wx fit my needs much better (and I like the looks of the result better
 too.)
 I have little to no experience with LTR handling myself, but there's a
 very
 good, active support list for wxPython and I suspect that someone on that
 list may have insights that can help...
 wxpython-us...@googlegroups.com


 For the type of work the OP has previously described I doubt that wxPython
 fits the bill as the Python 3 version called Phoenix is still in
 development.  More here http://wiki.wxpython.org/ProjectPhoenix


Still under development, true - but all but a few of the controls are up
and running, and a lot of the people on the list are using Phoenix now.
(Not I - I'm still using 2.7 - but I've been following developments with
interest.)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] “has a value of True” versus “evaluates true”

2014-11-13 Thread Marc Tompkins
On Thu, Nov 13, 2014 at 12:40 PM, Ben Finney ben+pyt...@benfinney.id.au
wrote:

 Danny Yoo d...@hashcollision.org writes:

   To quote: Let your statement be: 'Yes, yes', or no, no': anything
   beyond these is of evil.
  
   Have you stopped abusing small children yet?
 
  :(
 
  I don't understand what your response here means.

 He's pointing out that many questions that ask a yes-or-no question
 can't actually be truthfully answered “yes, yes”, nor “no, no”.

 It seems you demonstrated his point quite well :-)


The classic version, of course, is Have you stopped beating your wife?
http://en.wikipedia.org/wiki/Loaded_question
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Would somebody kindly...

2014-10-30 Thread Marc Tompkins
On Wed, Oct 29, 2014 at 10:39 PM, Clayton Kirkwood c...@godblessthe.us
wrote:

 When I run:
 values = [ ('a', 1), ('b', 2), ('a', 5), ('c', 7)]
 key = 'a'
 pair=[]

You just created an empty list and called it pair.

 [pair for pair in values if key == pair[0]]

Two things to bear in mind here:
- The stepper variable in a list comprehension lives in a distinct
namespace.  To the human reader, the list called pair outside the
comprehension and the object called pair inside look identical - but Bad
Things would happen if Python were as easily confused as humans, so it
isn't.  To Python, they are no more alike than two humans who happen to
have the same first name.
- As soon as the list comprehension stops executing - from the reader's
perspective, as soon as you read past the rightmost square bracket - it,
and its stepper variable, disappear.  You didn't assign the list that the
comprehension generated _to_ anything, so it evaporates.  (Of course,
nothing is really gone until it's garbage collected - but since you don't
have any control over that, consider it gone.)

print(pair)

 I get [].

As expected - it's the same empty list you started out with, and you didn't
do anything to it.



 When I run:
 values = [ ('a', 1), ('b', 2), ('a', 5), ('c', 7)]
 key = 'a'
 pair=[]

You're still not doing anything with that list...

 x=[pair for pair in values if key == pair[0]]

This time, you ARE doing something with the list that the comprehension
generates - you're naming it x.

 print(x)

And now you're printing it.


 I get [('a', 1), ('a', 5)]

Again, as expected.

I can't help thinking that part of the difficulty here is that you're using
object names that aren't meaningful to Python, but that seem to be
meaningful to _you_.  pair is just a name; it doesn't mean anything to
Python.  Neither do key or values - but they SEEM meaningful, and
they're kinda close to actual Python keywords.  This is a bad and dangerous
practice!

Try changing it up:
 whatsits = [ ('a', 1), ('b', 2), ('a', 5), ('c', 7)]
 thingy = 'a'
 twofer=[]
 x=[twofer for twofer in whatsits if thingy == twofer[0]]
Obviously you needn't make your variable names as silly as that, but - for
your own sake - don't make them official-sounding either.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Auto-response for your message to the Tutor mailing list

2014-10-26 Thread Marc Tompkins
On Sun, Oct 26, 2014 at 1:15 PM, Danny Yoo danny@gmail.com wrote:


  why is it I get this messages repeatedly despite having been reading
 and writing on the list for over a year now?

 This has happened to me once in a while too.  I conjecture that it might
 be a bug with Mailman, but I'd have to dive into the code to be certain.


I get these every few months, especially (but not exclusively) if I've been
silent for a while.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to count vehicle? I'm trying but my code don't increasing..

2014-09-05 Thread Marc Tompkins
On Fri, Sep 5, 2014 at 4:09 AM, Whees Northbee ch.de2.2...@gmail.com wrote:
 I'm really sorry if my post doesn't appropriate to the forum rule.. I
 already asked in other forums 2 months ago, but no answer or had voted down
 and closed..

It's not that you've broken a rule.  It's just that you're asking on a
forum where you're not likely to get an answer, because nobody here
(that I am aware of) is an expert in computer vision.  The way you
phrased the question at first made it sound like you were asking about
the basic math - we can help you with that, and with turning that math
into Python.  But for questions about OpenCV, you're going to have to
ask in a place where people actually use OpenCV.  It's not a matter of
etiquette or forum rules - it's a matter of asking in a place where
people can actually answer your question.  If you asked in OpenCV
forums, and got no answer/voted down... we're sorry, but we can't
really help you with that.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Vol 127, Issue 15

2014-09-05 Thread Marc Tompkins
On Fri, Sep 5, 2014 at 2:32 PM, Crush crushe...@gmail.com wrote:
 Ok nevermind, I did not figure it out. My code...

 count = 0
 while count  3:
 count += 1
 Subprocess.Popen('command')
 if count == 3:
 sys.exit()

 This does not work as I want it to; it consecutively executes the command  
 three times in a row. I only want it to execute once. However, if there is an 
 error, I want it to try again, but only if count does not equal 3. If count 
 equals 3, i want it to give up and exit or do something else.

I don't know what command does, or what an error would mean for
your purposes - if you want an exact answer, you'll need to provide
more detail.  However, I'm going to assume that if an error occurs,
a Python exception of some sort gets raised.  If so, here's how I
would handle this:

count = 0
success = False
while (count  3) and not success:
try:
Subprocess.Popen('command')
success = True
except:  # (you shouldn't use a bare except, but I don't know what
to expect)
count +=1
sys.exit()
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor Digest, Vol 127, Issue 12

2014-09-04 Thread Marc Tompkins
On Thu, Sep 4, 2014 at 3:26 PM, Alan Gauld alan.ga...@btinternet.com wrote:
 On 04/09/14 21:37, Najam Qasim wrote:
 I downloaded notepad++. Can you please help me how to run python script in
 notepad++?

 I only played with notepad++ briefly but I seem to recall it had a menu with
 commands to 'make' and 'run' a file. You could configure the commands
 associated with those menus in the settings somewhere.

I use Notepad++ all the time as my go-to text editor - but I don't use
it as an IDE precisely, because it doesn't have an integrated
interpreter/debugger/etc.  There _is_ a Run menu, but it's just a
generic program launcher; I think your memory is playing tricks on you
as far as a Make command is concerned.  Notepad++ does have a large
plugin ecosystem, and there may be some IDE-ish plugins out there, but
that's not really what the program is meant for.

 Hopefully somebody who currently uses the editor can provide clearer help.
 Meantime just save the file and run it from the Windows Explorer or (better)
 an OS command prompt
This would be my advice also.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using unittest module for Test Driven Development

2014-08-25 Thread Marc Tompkins
On Mon, Aug 25, 2014 at 12:04 AM, Alex Kleider aklei...@sonic.net wrote:

 I appreciate your further elucidation, like your 'sledge hammer' metaphor and 
 thank you for the fragility warning. I expect within such a limited scope, 
 the dangers are not great.

As someone who has been burned by this sort of thinking, please allow
me to urge you:  get into good habits now!  At various points in my
career when I've been learning a new language/technology/paradigm,
I've decided to take shortcuts when writing my early toy programs.
Unfortunately, in several cases, my toy programs ended up evolving
into production code - shortcuts and all.  In particular, I used to
assume that my code - since it was either a learning exercise or a
utility for myself alone - would only ever run in a
single-user/single-tasking environment, and that when I wrote the
real program later (in my copious free time) I would take the
necessary precautions.  Please, take a fool's advice: always assume
that any program you write (more complex than Hello world) will
eventually be running in a busy environment, or that your user will
manage to invoke five copies of it instead of one, or...
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Building Starships -- object of type 'int' has no len()

2014-08-20 Thread Marc Tompkins
On Aug 20, 2014 12:07 PM, Terry--gmail terry.kemme...@gmail.com wrote:

 Alan Gauld

 Hi!
 We are not quite out of the woods on this last example you gave me. It
now seems to be complaining
 that it doesn't want to append an integer to the list or that this isn't
the place to use '.append'  -- I am probably interpreting it's complaint
wrong:

 Python 3.3

 If I run this last piece of code that we just added 'enumerate(row)' to:

 lens = [0] * len(catalog2[0])
 for row in catalog2:

 for col, item in enumerate(row):
 print(col, item, len(item))

 lens[col].append(len(item))
 lens = [max(col) for col in lens]

 My result is:

 0 Drives 6  my print statement result

 Traceback (most recent call last):
   File /home/justme/1a_Computer_Related/Python/scripts/scratch.py, line
43, in module
 lens[col].append(len(item))
 AttributeError: 'int' object has no attribute 'append'

Once again you're confusing the list with its contents.  lens is a list;
lens[col] is an integer.  lens.append(whatever) should do the trick.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Building Starships -- object of type 'int' has no len()

2014-08-20 Thread Marc Tompkins
On Wed, Aug 20, 2014 at 1:38 PM, Terry--gmail terry.kemme...@gmail.com wrote:
 Marc, my understanding is, is that:

 lens[col].append(len(item))

 -should be building a mirror image of my list of lists called catalog2,
 which currently has 9 columns by x number of rows, and that we are plugging
 into these positions, the sizes of all the elements in that block of data.

What's important is how you defined lens:
  lens = [0] * len(catalog2[0])

That's a list of integers, as far as I can tell without running it
(I'm away from an interpreter at the moment.)  So no, you cannot do
lens[col].append(whatever), because - as the error message said -
'int' object has no attribute 'append'.

There might be some misunderstanding about what list.append(whatever)
does - it adds whatever to the end of list.  It does NOT assign
values to elements that already exist; to do that, you need to do
assignment by index.  So maybe this is what you're looking for?:
 lens[col] = len(item)



 So, I completely don't understand why we would eliminate the positioning of
 which list we are referencing in lens by saying:

 lens.append(len(item))

 It seems to me that, that statement would put the entire block of element
 sizes into one list, and the next MAX statement would then yield only a
 single number, which would be the largest size element it encounted in the
 whole of catalog2!

 Or am I really missing the boat here? :)

 lens.append(len(item))
will append a single integer to lens.  I'm afraid I don't quite follow
the bit about the next MAX statement, as I've lost the thread of
what your larger project is trying to accomplish...  In any case,
max() _should_ only return a single number, no?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Building Starships -- object of type 'int' has no len()

2014-08-19 Thread Marc Tompkins
On Mon, Aug 18, 2014 at 1:00 AM, Marc Tompkins marc.tompk...@gmail.com wrote:

 Also, looking at the Ninja-IDE website more closely I see that,
 although they do mention compatibility with multiple languages, they
 were designed by and for Python programmers - which makes the
 tab/space issue less likely.  I dunno.

Update: I tried out NinjaIDE myself, and confirmed that copying
four-space indented code from Ninja, then pasting it into a plain-text
compose box in GMail results in flat code/extra newlines; I can only
presume that it's much the same with TBird.  The problem is definitely
not (as I had thought) a space/tab problem; it has something to do
with how Ninja (and GMail, and TBird) deals with the clipboard.

I can copy from Ninja and paste into Notepad++; the indentation is
preserved.  If I then re-copy the same text from Notepad++ and paste
it into the compose box, the indentation is preserved.  But if I go
straight from Ninja to compose - flat!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Building Starships -- object of type 'int' has no len()

2014-08-19 Thread Marc Tompkins
On Tue, Aug 19, 2014 at 1:04 PM, Mark Lawrence breamore...@yahoo.co.uk wrote:
 I'm not aware of any problem with Thunderbird or any (semi-)decent mail
 client.

The original poster uses NinjaIDE and Thunderbird, and his code was
being persistently flattened when he copied/pasted.  I believe I've
just tracked it down to an incompatibility between the two (which also
happens to extend to Ninja/Gmail.)  I'm not sure how Google Groups
enters into it.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Building Starships -- object of type 'int' has no len()

2014-08-18 Thread Marc Tompkins
On Sun, Aug 17, 2014 at 10:51 PM, Terry--gmail terry.kemme...@gmail.com wrote:
 I'm copy and pasting from Ninja-IDE, which I thought was created
 specifically to do python programming...

Specifically for programming, yes, and Python is among the supported
languages - but according to their web page, they support many
languages (and in many other languages, whitespace is either not
meaningful, or else you might actually want the Tab key to produce a
tab character.)
Anyway, I'm only guessing that the reason your indentation was
disappearing was a tab/space issue; I don't actually know.


 for line_number, row in enumerate(catalog2):
 for col, item in enumerate(row):
 if lens[col]  len(item):
 lens[col] = len(item)

 How's that?

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


Re: [Tutor] Building Starships -- object of type 'int' has no len()

2014-08-18 Thread Marc Tompkins
On Mon, Aug 18, 2014 at 12:13 AM, Cameron Simpson c...@zip.com.au wrote:
 On 17Aug2014 23:51, Terry--gmail terry.kemme...@gmail.com wrote:

 I'm copy and pasting from Ninja-IDE, which I thought was created
 specifically to do python programming...so I never checked to see if it
 needs to have the tab set to enter 4 spaces, as it appeared visually to be
 doing that.  But, I don't remember whether I used their tab or manually
 typed 4 spaces. SO, I have typed the lines below in manually:

 for line_number, row in enumerate(catalog2):
for col, item in enumerate(row):
if lens[col]  len(item):
lens[col] = len(item)

 How's that?


 All good except for the last line, which would normally be indented further
 than the if.
Poop.  I missed that.

Also, looking at the Ninja-IDE website more closely I see that,
although they do mention compatibility with multiple languages, they
were designed by and for Python programmers - which makes the
tab/space issue less likely.  I dunno.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Building Starships -- object of type 'int' has no len()

2014-08-17 Thread Marc Tompkins
On Sun, Aug 17, 2014 at 4:48 PM, Terry--gmail terry.kemme...@gmail.com wrote:
 WOW! There is a lot of help on this mailing list! I want to thank everyone
 for their valuable input! Thanks!  (I am working my way through the
 replies.)

 Sorry about the HTML. I think I have it turned off now in Thunderbirdy for
 this address. If so, then what follows should not be flat. If it is flat,
 please tell me.

It's not only flat, but appears in a confusing array of sizes and
styles - VERY SHOUTY bold 18-point for most of the text; 12.8 regular
for code; 15.8 regular for the text that appears after the code.  Hard
to read the prose, never mind that it wiped out the indentation of
your code.


 Mark:

 You commented on the non-Pythonic nature of my program. HA HA HA! I don't
 doubt it!

What I was getting at is a sort of feeling.  Taking the length of a
list, then using that length as the end value for range(), then
counting up to the end of that range to step through the list...  does
it not feel like you've got unnecessarily far from the subject at
hand?  The Pythonic way would be to step through the list itself - or,
if you must have a numeric index, to get it from enumerate()ing the
list.

As for a general theory of Pythonicity... it's a bit like all of those
Zen koans where a novice monk asks the master Does (x) have
Buddha-nature?  (Not _quite_ as impossible to grasp as that, though!)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Building Starships -- object of type 'int' has no len()

2014-08-17 Thread Marc Tompkins
On Sun, Aug 17, 2014 at 9:40 PM, Terry--gmail terry.kemme...@gmail.com wrote:
 I found another place in Thunderbirdy to set 'plain text'.

 This is a test.

 Does the below code look correct now?

 --And did I reply correctly this time?  (Reply-All and keep only
 tutor@python.org address...)


 for line_number, row in enumerate(catalog2):

 for col, item in enumerate(row):

 if lens[col]  len(item):

 lens[col] = len(item)

1)  It's plain text - no more funky font changes.
2)  Addressing is good.
3)  Indentation is still flat.

Ah well.  As Meat Loaf sang, two out of three ain't bad...
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Building Starships -- object of type 'int' has no len()

2014-08-17 Thread Marc Tompkins
On Sun, Aug 17, 2014 at 9:49 PM, Marc Tompkins marc.tompk...@gmail.com wrote:
 On Sun, Aug 17, 2014 at 9:40 PM, Terry--gmail terry.kemme...@gmail.com 
 wrote:
 I found another place in Thunderbirdy to set 'plain text'.

 This is a test.

 Does the below code look correct now?

 --And did I reply correctly this time?  (Reply-All and keep only
 tutor@python.org address...)


 for line_number, row in enumerate(catalog2):

 for col, item in enumerate(row):

 if lens[col]  len(item):

 lens[col] = len(item)

 1)  It's plain text - no more funky font changes.
 2)  Addressing is good.
 3)  Indentation is still flat.

It just occurred to me: how are you indenting?  If you're using tabs,
that would explain the problem (TBird might be helpfully converting
tabs to newlines); in any case, the usual Python convention is to use
four spaces for indentation (it's pretty easy to set your text editor
to convert tabs to spaces on-the-fly, too.)
If you're already using spaces, please disregard.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Building Starships -- object of type 'int' has no len()

2014-08-15 Thread Marc Tompkins
On Fri, Aug 15, 2014 at 10:46 AM, Terry--gmail terry.kemme...@gmail.com wrote:

(By the way - your indentation got flattened - cue the inevitable
chorus of DON'T POST TO THIS LIST IN HTML - so this is my best-guess
reconstruction.)
 lens = []
 # pre-format the list called lens for maximum number of columns contained in
 catalog2
 lens = [0] * len(catalog2[0])
 # map the largest sizes of each column into list 'lens'
 col, line_number = 0, 0
 for line_number in range(len(catalog2)):
 for col in range(len(catalog2[line_number])):
 if lens[col]  len(catalog2[line_number][col]):
 lens[col] = len(catalog2[line_number][col])

There are two separate issues here - the syntactic mistake that's
giving you the error, and the non-Pythonic nature of for col in
range() - let's deal with the first one.

catalog2 is a list containing lines; line_number is a list containing
integers.  catalog2[line_number][col] is an integer; len(int) gives
you a TypeError, as you've seen.
I don't entirely understand what you're trying to do, so I can't tell
you whether you want
 if lens[col]  len(catalog2[line_number]):
or
 if lens[col]  catalog2[line_number][col]:
but it's probably one or the other.


Now, for the second issue - to take the length of a list and use that
as the limit for a one-by-one crawl through the list is not the Python
way.  Rather than:
 for line_number in range(len(catalog2)):
use
 for line_number, item in enumerate(catalog2):

https://docs.python.org/3/tutorial/datastructures.html#looping-techniques
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] New to Python - print function - invalid syntax

2014-08-05 Thread Marc Tompkins
On Tue, Aug 5, 2014 at 12:48 AM, Maxime Steisel maximestei...@gmail.com wrote:
 I think this is because on windows, *.py files are associated with py.exe
 that choose the python version depending on the first line of your file.

No.  *ix operating systems (Unix, Linux, OS X, etc.) inspect the first
line of a file to determine how to handle it; Windows does NOT.
Windows simply looks at the filename extension (.py, .pyw, etc.) and
consults its internal registry of file type associations.  The way
that you, as a user, can edit those associations has changed over the
years; in Windows 7 and 8, it's Control Panel\All Control Panel
Items\Default Programs\Set Associations.

On the other hand, when you start up CMD.EXE and type python at the
prompt, Windows uses a procedure that goes back to DOS 2 or so: the
PATH environment variable.  This is similar to, but a little different
from, the way that *ixes work; Windows first compares what you've
typed with the list of commands built-in to CMD, then with all of the
executable files in the current working directory, THEN
walks through the directories listed in PATH.  The first matching
command or executable it finds is the one that runs.

 Putting #!python3 on the first line of game_over2.py should solve it.
NO.  #! has no effect in Windows, because the choice of Python
interpreter has already been made by the time anybody gets round to
reading the first line of the file.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] New to Python - print function - invalid syntax

2014-08-05 Thread Marc Tompkins
On Tue, Aug 5, 2014 at 8:23 AM, Zachary Ware
zachary.ware+py...@gmail.com wrote:

 which it should be if the most recently
 installed Python was 3.3 or 3.4, installed with default options.


And there we have my problem with this glorious new feature.  YOU
CAN'T RELY ON IT, because it depends on the most recent version having
been installed most recently.  Much better to depend on the underlying
behavior of the operating system.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Comparing two different text file

2014-07-29 Thread Marc Tompkins
On Tue, Jul 29, 2014 at 4:13 PM, 이명교 t...@naver.com wrote:

 inf1 = open('first.txt')
 for line in inf1.readlines():
 list1.append(line)
So far, so good...

 list1 = line[:-1].split('\n')
...but then you do this, which wipes out list1.


 for a in list1:
 if a not in list1:

Even if you hadn't already wiped out list1, this would be a problem.
These two lines essentially say if a is both in AND not in list1...

There might be other issues, but fixing those will get you started.

Also:  don't be afraid to add print() all over the place so you can
see what's happening!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] (no subject)

2014-07-20 Thread Marc Tompkins
On Sun, Jul 20, 2014 at 8:40 AM, LN A-go-go
lnart...@yahoo.com.dmarc.invalid wrote:


 States OJ
 AK 36
 AL 39
 AR 39
 AZ 45
 CA 61
 CO 54
 CT 61
 DC 93
 DE 62
 FL 51
 GA 47
 HI 72
 IA 54
 ID 36
 IL 62
 IN 50
 KS 41
 KY 41
 LA 40
 MA 62
 MD 62
 ME 58
 MI 57
 MN 54
 MO 49
 MS 43
 MT 47
 NC 50
 ND 45
 NE 41
 NH 54
 NJ 57
 NM 57
 NV 55
 NY 62
 OH 51
 OK 34
 OR 57
 PA 55
 RI 63
 SC 45
 SD 45
 TN 42
 TX 44
 UT 34
 VA 53
 VT 67
 WA 58
 WI 56
 WV 43
 WY 33

  myfile.close()
  infile = open('C:/Python27/egund919/Program1/BOJ_B.txt','r')
  import string
  state_name = []
  data_value = []
  counter = 0
  x = 0
  line = infile.readline()
  while True:
   line = infile.readline()
   if not line: break
   counter = counter + 1
   States, OJ = string.split(line)
   XSTATES = str(States)
   XNUM = int(OJ)
   state_name.append(XSTATES)
   data_value.append(XNUM)

  len(counter)
 Traceback (most recent call last):
   File pyshell#29, line 1, in module
 len(counter)
 TypeError: object of type 'int' has no len()
  counter.count
 Traceback (most recent call last):
   File pyshell#30, line 1, in module
 counter.count
 AttributeError: 'int' object has no attribute 'count'
  len(state_name)
 0
  list.state_name
 Traceback (most recent call last):
   File pyshell#32, line 1, in module
 list.state_name
 AttributeError: type object 'list' has no attribute 'state_name'


First of all, I would take advantage of the with construction, like so:

with open('C:/Python27/egund919/Program1/BOJ_B.txt','r') as infile:
#do stuff with infile

When the block of code inside of the with section finishes, Python
will take care of closing the file for you - even if your program
encountered an error.  MAJOR advantage over doing it yourself.

Second, there's no need to import string anymore; all of the
functions defined in that module are native methods of strings.
line is a string, so you can just do line.split().  split()
returns a list; you can get the first item in that list with
line.split()[0], the second item with line.split()[1], etc.

Third, free your mind from the shackles of counting how many objects
are in a list and using that counter as the index of your loops - this
is not the Python way!  Instead, let Python take care of the counting
and indexing for you.

Fourth (and here I differ from some of the others on this list,
notably Alan G) - I don't like the while True: / break paradigm.
Your mileage may vary, but I find it makes it harder to understand
what the program is actually trying to achieve.  In your case, you
read a line from the file, then check whether it contains anything; I
like to move the readline() to the bottom of the loop.

Having said all that, here's my suggested version:

state_name = []
data_value = []
with open('C:/Python27/egund919/Program1/BOJ_B.txt','r') as infile:
line = infile.readline()  # Doing this twice because you
apparently want to discard the first line...?
line = infile.readline()
while line:
state_name.append(line.split()[0])
data_value.append(line.split()[1])
line = infile.readline()
print(state_name)
print(data_value)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] (no subject)

2014-07-20 Thread Marc Tompkins
On Sun, Jul 20, 2014 at 2:37 PM, Alan Gauld alan.ga...@btinternet.com wrote:

 In fact in this case I suggested he use a for loop to iterate over
 the file and use a dictionary to store the results...

Ah.  I missed that, as I've only noticed this newer thread.  And I
apologize for imputing motive (a liking for while True); I'd just
noticed that you often advise it.  I don't know who _does_ think this
is a desirable pattern; I'd love to hear their argument for it - it
must be really good.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] (no subject)

2014-07-20 Thread Marc Tompkins
On Sun, Jul 20, 2014 at 6:12 PM, Mark Lawrence breamore...@yahoo.co.uk wrote:

 Ah.  I missed that, as I've only noticed this newer thread.  And I
 apologize for imputing motive (a liking for while True); I'd just
 noticed that you often advise it.  I don't know who _does_ think this
 is a desirable pattern; I'd love to hear their argument for it - it
 must be really good.


 It works :)

So does GOTO.

Seriously, though, how is
1)  Do {this} forever, until something happens that I'll tell you about later

better than
2)  Do {this} until this condition, which I'm telling you about RIGHT
NOW, changes
?

Granted, this can all be clarified with good comments - but the second
approach basically documents itself.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Ending a loop with a condition not at the top

2014-07-20 Thread Marc Tompkins
On Sun, Jul 20, 2014 at 8:10 PM, Ben Finney ben+pyt...@benfinney.id.au wrote:
 Marc Tompkins marc.tompk...@gmail.com writes:

 Seriously, though, how is
 1) Do {this} forever, until something happens that I'll tell you about
 later

 better than
 2)  Do {this} until this condition, which I'm telling you about RIGHT
 NOW, changes
 ?

 Here's how:

 The first of them is already implemented in Python, and works well
 enough for the purpose. This is a significant benefit the other lacks.

 The second one is not implemented in Python, and there are no successful
 proposals (which, by the way, are better discussed at the Python Ideas
 forum URL:https://mail.python.org/mailman/listinfo/python-ideas) to
 implement them in a way that justifies the cost of adding it to the
 language.

Actually, if you read the Python docs - 8.2 for Python 3:
  https://docs.python.org/3/reference/compound_stmts.html#the-while-statement
or 7.2 for Python 2:
  https://docs.python.org/2/reference/compound_stmts.html#the-while-statement
you'll see that it _is_ implemented:
 The while statement is used for repeated execution as long as an expression 
 is true:
   while_stmt ::=  while expression : suite
   [else : suite]
 This repeatedly tests the expression and, if it is true, executes the first 
 suite;
 if the expression is false (which may be the first time it is tested) the 
 suite of the else clause, if present, is executed and the loop terminates.

So I don't know where you got the idea that I wanted to change the language.

However, I will admit that, until a few minutes ago, I had not read this:
https://docs.python.org/2/faq/design.html#why-can-t-i-use-an-assignment-in-an-expression
which deals with my preferred while syntax as an edge case:
  There’s an alternative way of spelling this that seems attractive but is 
 generally less robust than the “while True” solution:

One might ask whether the designer(s) of the language are on speaking
terms with whoever wrote that paragraph - but I bow my head to Guido's
(or whoever's) wisdom.

In any case, I wholeheartedly agree with the next paragraph, which states:
  The best approach is to use iterators, making it possible to loop through 
 objects using the for statement.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using module Facebook

2014-07-18 Thread Marc Tompkins
On Fri, Jul 18, 2014 at 9:29 AM, Chris ch2...@arcor.de wrote:

 On 07/18/2014 09:44 AM, Alan Gauld wrote:
  Are you sure thats the version of Python you are running
  in the virtualenv?

 I've modified the first line to #!./bin/python (instead of
 #!/usr/bin/python).

 Now, there's another error message:

 (facebook)[chris@cd facebook]$ ./fb1.py
 Traceback (most recent call last):
   File ./fb1.py, line 6, in module
 import facebook
   File
 /home/chris/software/facebook/lib/python2.6/site-packages/facebook.py,
 line 811
 args = {k: v for k, v in args.iteritems() if v is not None}
^
 SyntaxError: invalid syntax


Well, you've fixed your original problem - that the facebook module wasn't
in the path for the copy of Python you were running - and exchanged it for
another: a syntax error in the facebook module itself.  (Might be that the
module isn't compatible with the version of Python you're now running;
might be an actual problem with the module, but you'd think that would've
been caught before...)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why is Quick Search at docs.Python.org so useless?

2014-07-06 Thread Marc Tompkins
On Sun, Jul 6, 2014 at 1:57 PM, Danny Yoo d...@hashcollision.org wrote:

  2.  Direct feedback to the Python web site maintainers so that either
they fix the problem or are at least aware that something is deficient.

Google offers a per-site custom search; it's free for very basic
functionality and not very expensive for the whole enchilada.  (In any
case, Google has got enough value out of Python over the years that I bet
they'd provide it for free, if asked.)  I suppose there might be a bit of
DIY pride to be lost in using an out-of-the box solution, but...

  4.  Ignore.
  * I will ignore option #4.

I see what you did there.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to list/process files with identical character strings

2014-06-24 Thread Marc Tompkins
On Tue, Jun 24, 2014 at 8:34 AM, mark murphy msmur...@alumni.unc.edu
wrote:



 What I hope to be able to do is scan the directory, and for each instance
 where there are two files where the first 8 characters (TDDD) are
 identical, run a process on those two files and place the output (named
 TDDD) in a new directory.


I don't know the details of your file system, but I would guess that those
files would have some sort of signifier to indicate this file is the first
part of a multi-part image; this file is the second part, etc. - maybe
the first half has the extension .001 and the second half has the
extension .002?  If so, I would search for files with the first part
signifier, and for each one I found I would try to join it with a file with
the same base name but the second part signifier.

If, on the other hand, there's no signifier - just the same date but with a
slightly-different timestamp, you can:
1) grab the list of filenames
2) sort it
3) iterate through the list and compare each filename with the previous
filename; if the first 8 characters match, you do your processing magic; if
not, you move on.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to list/process files with identical character strings

2014-06-24 Thread Marc Tompkins
On Tue, Jun 24, 2014 at 1:02 PM, Peter Otten __pete...@web.de wrote:

 Sorting is probably the approach that is easiest to understand, but an
 alternative would be to put the files into a dict that maps the 8-char
 prefix to a list of files with that prefix:


I was debating the virtues of the two approaches, but figured I'd err on
the side of simplicity...
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python sockets

2014-06-11 Thread Marc Tompkins
On Tue, Jun 10, 2014 at 4:08 PM, Jon Engle jon.en...@gmail.com wrote:
 Ok, so when I run the code it immediately terminates and never 'listens' to
 the ports in the loop. I have verified by running netstat -an | grep 65530
 and the startingPort is not binding.

The problem is that all threads started by a program terminate when
the program terminates - and you haven't told your program to stick
around when it's done setting up.So it's setting up and then
immediately exiting - and by the time you run netstat a few seconds
later you find nothing.  (Also, by leaving HOST = '', you're listening
at address 0.0.0.0, so good luck catching any traffic...)
Try something like this:


#!/usr/bin/python # This is server.py file
from socket import *  #import the socket library
import thread  #import the thread library

def setup(PORT):
HOST = '127.0.0.1'#we are the host
ADDR = (HOST,PORT)#we need a tuple for the address
BUFSIZE = 4096#reasonably sized buffer for data

serv = socket( AF_INET,SOCK_STREAM)

serv.bind((ADDR))#the double parens are to create a tuple with
one element
serv.listen(5)#5 is the maximum number of queued connections we'll allow
print '\nlistening on port %i...' % PORT
conn,addr = serv.accept() #accept the connection
print '\n...port %i connected!'  % PORT
conn.send('TEST')
conn.close()

def main():
startingPort=int(raw_input(\nPlease enter starting port: ))
for port in range (startingPort, 65535):
thread.start_new_thread(setup, (port,))
quitNow = ''
while quitNow not in ('Q', 'q'):
quitNow = raw_input('Enter Q to quit.')

if __name__ == '__main__':
main()


This will stick around until you enter 'Q', and if you run netstat in
another window you'll see that it's LISTENING on all the ports you
asked for.  (All of those print statements will show up in a
surprising order!)

I'm not running the other side of this experiment, so I haven't tested
a successful connection... good luck.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Simple python help

2014-06-10 Thread Marc Tompkins
On Tue, Jun 10, 2014 at 7:55 AM, Stephen Brazil steph...@nmsu.edu wrote:

  Hello! I am brand new to python and need to know how to make the attached
 lines of code work. Should be pretty


You need quotes.

Stephen (without quotes) is an object, which you haven't previously
defined.  'Stephen' is a string, which can be compared to person.

Which version of Python are you using?  If it's 2.x, PLEASE don't use
input() - use raw_input() instead.  In 3.x, input() does what raw_input()
used to, so it's cool.

Finally, you're likely to catch some grief for posting your code as a
picture; in future, post code as plain text.  (Sure, we won't see the nifty
syntax highlighting, but that's OK!)  Every single post to this list that's
anything but plain text generates at least one complaint; it significantly
lowers the signal-to-noise ratio.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python sockets

2014-06-10 Thread Marc Tompkins
On Tue, Jun 10, 2014 at 9:28 AM, Jon Engle jon.en...@gmail.com wrote:


 for port in range (startingPort, 65535):
 thread.start_new_thread(setup, (port,))
  startingPort=startingPort+1
 #print startingPort


I think you just need this:

for port in range (startingPort, 65535):
 thread.start_new_thread(setup(port))
 #print port


and inside of setup, get rid of this line:
PORT = startingPort#arbitrary port not currently in use
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python sockets

2014-06-10 Thread Marc Tompkins
On Tue, Jun 10, 2014 at 2:00 PM, Jon Engle jon.en...@gmail.com wrote:

 Ok, so after making the changes the code does bind the startingPort
 variable but that is the only port that gets bound. Also when connecting to
 the startingPort I receive the following error:

 Please enter starting port: 65520

 listening...

 ...connected!

 Traceback (most recent call last):

   File response.py, line 31, in module

 thread.start_new_thread(setup(port))

 TypeError: start_new_thread expected at least 2 arguments, got 1


Sorry about that!  I should have read the docs
(https://docs.python.org/2/library/thread.html)
for thread.start_new_thread(); you had it right in the code you posted (it
was the rest of your loop that was a problem.)  So, change it back to:


for port in range (startingPort, 65535):
 thread.start_new_thread(setup, (port,))
 #print port


My apologies for the bum steer.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Swampy: No module name World

2014-06-03 Thread Marc Tompkins
On Tue, Jun 3, 2014 at 7:53 AM, Charles Agriesti dragrie...@comcast.net
wrote:

 Thanks all. Problem apparently solved. Shortly after that last message it
 quit working completely. Reinstall Python 2.7 + swampy - no good;
 uninstall both 2.7 and 3.4, manually remove the folders that remained
 because of scripts that got saved in the base folder, reset sys path,
 reinstall both, add 2.7 to path, reinstall Swampy from new download - no
 good; remove 2.7, new 2.7 dl and install, new Swampy dl and install -
 works perfectly this morning.

 Sorry to jump in at the end, but I can't help noticing that something
important (mentioned earlier in the thread) may have got missed: swampy is
available from PyPi, which means that there are several automatic tools
(easy-install, pip, etc.) available to install it for you (and presumably
make the details work properly.)  With very few exceptions, if a module is
available from PyPi, the proper way to install it is via one of those tools
and NOT a manual download.  The fact that you mention installing Swampy
from a download tells me you're not using those tools - am I mistaken?

For Windows users, there's pip-win (
https://sites.google.com/site/pydatalog/python/pip-for-windows).  It's not
only incredibly simple to use, but it's specifically designed for machines
with multiple Python versions; so (gulp!) I actually recommend the Windows
tool over the command-line in this case.





 ---
 This email is free from viruses and malware because avast! Antivirus
 protection is active.
 http://www.avast.com

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

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


Re: [Tutor] Swampy: No module name World

2014-06-03 Thread Marc Tompkins
On Tue, Jun 3, 2014 at 11:00 AM, Mark Lawrence breamore...@yahoo.co.uk
wrote:

pip-win (https://sites.google.com/site/pydatalog/python/pip-for-windows)



 Never heard of it so thanks for the link.

 I don't know how long it's been around but I'll tell you this much for
free: I wish I'd known about it when I first started with Python!  The
hours I wasted, trying to wrangle various XML and SQL packages...  I'll
never get that time back.  (And it was ALL WASTED TIME, because this
mechanical stuff has nothing to do with programming.  I get incredibly
irritated with the tone of some forum posts on this topic - are people
somehow losers because they've got better things to do than figure out the
syntax of one package manager versus another?  These are TOOLS, folks!
They're supposed to work for YOU!)
/rant

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


Re: [Tutor] self keyword in recursive function

2014-05-31 Thread Marc Tompkins
On Fri, May 30, 2014 at 11:06 PM, Ritwik Raghav ritwikragha...@gmail.com
wrote:

 That's all the code I'm writing.


That can't be true - the 11 lines of code you posted doesn't include
anything that would give you Correct Return Value: No, let alone any
reference to PersistentNumber.  From the error message, it would appear
that you've written (at least) 182 lines, and that the problem is on line
182 - but that's not what you're showing us.



 The complete problem statement is:
 http://pastebin.com/E970qYXk


Yes, but that's not _your_ code, so it tells us nothing about your error.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Library for .ppt to .txt conversion

2014-05-30 Thread Marc Tompkins
On Fri, May 30, 2014 at 2:41 AM, Aaron Misquith aaronmisqu...@gmail.com
wrote:

 Like pypdf is used to convert pdf to text; is there any library that is
 used in converting .ppt files to .txt? Even some sample programs will be
 helpful.


I suspect you'd need to use PowerPoint itself to do that cleanly; you can
definitely drive PowerPoint from Python if you so desire, though:
http://www.s-anand.net/blog/automating-powerpoint-with-python/

If anybody's written a package to brute-force the text out of a .ppt file
without using PowerPoint, though, I'm unaware of it.  That way lies
madness, I suspect.  (The new MS Office formats - .docx, .xlsx, .pptx - are
XML files inside of a renamed ZIP container; it should be fairly easy to
get the text out of a .pptx file using any one of Python's XML libraries.
But the older format is proprietary and extremely scary.)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] self keyword in recursive function

2014-05-30 Thread Marc Tompkins
On Fri, May 30, 2014 at 10:16 PM, Ritwik Raghav ritwikragha...@gmail.com
wrote:


 It has again given some error I do not understand. This time my code is:

 count = 0
 def getPersistence(self,n):

 product = 1
 if len(str(n)) == 1:
 return self.count
 else:
 a = str(n)
 for i in a:
 product *= int(i)
 self.count += 1
 return self.getPersistence(product)

 and the error is:

 Correct Return Value: No

 Answer check result:
 Result must be not null.

 Execution Time: 0.017s

 Peak memory used: 24.551MB

 abnormal termination (exit 1)

 Standard Output:


 Standard Error:
 Traceback (most recent call last):
   File Wrapper.py, line 182, in module
 AttributeError: 'module' object has no attribute 'PersistentNumber'


 I do not understand what it is trying to tell me? I tried to test it for
 99.


The error is in some part of your code that you _haven't_ posted here -
please post your entire script (as an attachment, if that's more
convenient) and we'll be better able to help.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I am having difficulty grasping 'generators'

2014-05-27 Thread Marc Tompkins
On Tue, May 27, 2014 at 12:27 PM, Degreat Yartey
yarteydegre...@gmail.com wrote:
 I am studying python on my own (i.e. i am between the beginner and
 intermediate level) and i haven't met any difficulty until i reached the
 topic 'Generators and Iterators'.
 I need an explanation so simple as using the expression 'print ()', in this
 case 'yield'.
 Python 2.6 here!
 Thank you.


Simply put, a generator is just like a function - except that a
function returns a value and then dies, but a generator yields a value
and sticks around, waiting to yield another one - and another, and
another, etc.

I had some difficulty grasping the concept of generators at first
because the examples you get in the tutorials are either trivial (you
could do the same thing some other way, and it would be simpler) or
horribly complex (and you get bogged down in the problem, rather than
getting to grips with generators themselves.)

So here's a real-life example - the first time I actually used
generators... and they actually saved me a LOT of hard work and
confusion.  I needed to read some database files (from a very old
database, for which I don't have an API - so I basically needed to
read each record and interpret it byte-by-byte).  I wrote a bunch of
classes for the different tables in the database (I'll use Patient()
as my example), but the heart of the operation is a generator.


def RecordGenerator(office=None, fileType=None):
obj = fTypes[fileType]()# create an empty record so we can
read its attributes
recLen = obj.RecordLength# such as the record length, the filename, etc.
with open(getattr(office, obj.TLA) + '.dat','rb') as inFile:
tmpIn = inFile.read()
buf = StringIO.StringIO(tmpIn)
inRec = buf.read(recLen)# initialize inRec and burn the
header record
while not (len(inRec)  recLen):
inRec = buf.read(recLen)
obj = fTypes[fileType](inRec)
if (obj.Valid):
yield obj
buf.close()

Now I'm writing a program that needs to process all the patients in
office 01.  I write the following:

for obj in RecordGenerator(01, Patient):
doStuffPart1
doStuffPart2
doStuffPart3
etc.

The generator creates an empty Patient() object, looks at its
attributes, and finds that the filename is 01PAT.dat and the records
are 1024 bytes long.  It opens the file and reads it into tmpIn, then
grabs 1024-byte chunks of tmpIn and passes them to Patient() until it
finds a valid (not deleted, not corrupted) patient record.  It
yields that record to the caller, and waits.
When doStuffPart3 has completed, I go back to the top of the for
loop and ask for the next patient.  RecordGenerator steps through
tmpIn, 1024 bytes at a time, until it finds a valid patient, then
yields it and waits.  When it hits the end of the file (or, more
precisely, when the remaining length of tmpIn is less than a full
record length), it quits.

Essentially, you write a generator as if it were a function - but you
use it as if it were a sequence.  Best of both worlds, baby!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] what is the cores?

2014-05-25 Thread Marc Tompkins
On Sun, May 25, 2014 at 10:32 AM, Marino David davidmarino...@gmail.com wrote:
 Hi all:
 I am a newpie at python.
 I read a python toolbox in which there is code line:import cores as co. I
 wantta know what the cores is.
 When I type import cores as co, error occur as follows:
 Traceback (most recent call last):
   File console, line 1, in module
 ImportError: No module named cores

 I am sure this cores module is related to probability distributions since
 there are a lot of codes like these: co.alpha, co.beta, co.uniform, etc.

 I google cores python, and I did get useful information. Can anyone help
 me out?

cores is not one of the standard Python modules, nor is it part of
the PyPi package index.  I suspect that it's part of the toolbox
(I'm not sure what you mean by that - is it a book, a utility
package...?) that you're using.  Take a closer look; it's probably
referenced elsewhere.

Give us a bit more information about the toolbox you're using, and
we should be able to help you further.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] substituting for time_series, Pandas, Anaconda. Practical Programming, intro Comp Sci, Gries text

2014-05-14 Thread Marc Tompkins
On Wed, May 14, 2014 at 12:08 PM, Charles Agriesti
dragrie...@comcast.netwrote:


 Is this Anaconda thing any part of being able to run the scripts from the
 textbook with time_series? Is it a complete wild goose chase?



First off - I know nothing about using Python in a scientific setting.
Second (before anyone else points this out) this is the Python tutor list;
your question is a bit off-topic (i.e. relating to specific
packages/distributions rather than Python itself.)  This is not a criticism
or rebuke; it's just that you're likely to get better help on a list where
most of the people actually use the stuff you're asking about.

Having said that, Pandas appears to be a pretty normal Python package,
meaning that you could install it by itself; Anaconda is a distribution of
scientific Python that aims to do it all for you in one swell foop - but
it's not necessary.  If you've installed pip, it's as simple as pip
install pandas.  If you haven't installed pip and you use Windows, the
simplest thing is to install pip-Win:
 https://sites.google.com/site/pydatalog/python/pip-for-windows

Anaconda actually installs a virtual environment that doesn't rely on or
interfere with other versions of Python that are already installed, so no
worries there.  As long as you work inside Anaconda, the fact that you also
have 3.4 installed elsewhere is not an issue.  The fact that Anaconda
presents you with a radically different working environment than you're
used to - that might be an issue.



 Should I install SciPy? Is Pandas separate from that?


Can't answer that.  SciPy is a stack, meaning that it contains multiple
packages meant to work together (Pandas is one of them), and the SciPy
people themselves recommend Anaconda as one of the easiest ways to install
SciPy.  Do you need it?  No idea.

Should I install Python33? Will this conflict with the 27 and 34 already on
 this computer?


The chief source of conflict would be file associations and the system path
- i.e. what happens when you double-click on a .py file or type python at
a prompt.  Here's where Python's virtualenv comes in handy, or a Python
distribution that uses it - like Anaconda.  As long as you work inside
Anaconda, you don't have to worry about other versions.


 Give up on the Gries book and try a different one?


It seems well-reviewed; a discontinued package doesn't seem like a good
reason to abandon it, as long as there's a workaround...

It does look like Pandas is the replacement for scikits.timeseries
(although you're writing that as time_series, which makes me wonder
whether it's the same package at all!)  Only trial and error will tell
whether the syntax for using Pandas is the same as what's in your book.
Good luck!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] PyCountry currency formatting woes

2014-05-04 Thread Marc Tompkins
On Sun, May 4, 2014 at 1:55 PM, Sithembewena Lloyd Dube
zebr...@gmail.comwrote:

 Thanks, i was actually getting the error information to update the post.
 Apoligies to waste your time posting here - I could not find an appropriate
 PyCountry discussion list and my next best bet seemed to be a Python users'
 list.


You also posted on StackOverflow; I just answered you there.  In short: the
currency numeric is not guaranteed to be the same as the country numeric
(in the case of the Euro, how could it possibly be?)  The numeric for DE is
276; the numeric for the Euro is 978.  Obviously they don't match.

PyCountry is a wrapper around some tables provided by Debian; those tables
don't include a country/currency mapping.  You can find those mapping
tables at
 http://www.currency-iso.org/en/home/tables/table-a1.html
and roll your own wrapper; I'm sure it's been done a thousand times before,
but I'm not aware of a Python package that does this.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] FW: Beginner - list not returning correct variable value

2014-03-19 Thread Marc Eymard
Hello Tutor,

Could somebody help me with below query?

Thanks
Marc

From: marc_eym...@hotmail.com
To: tutor@python.org
Subject: Beginner - list not returning correct variable value
Date: Thu, 13 Mar 2014 16:12:28 +




Hello Tutor,

I am a self-taught Python script beginner and I do it from the Michael Dawson 
Book.

In attached script, can somebody tell me why the values of the variables 
strenght_points, health_points, wisdom_points and dexterity_points stay at 0 
value when 'printing' their value from the list attributes[] when the 'for' 
loop at the bottom of the script runs.

I have commented out the script to highlight what causes me problem.

I hope this is clear enough a question.

Thanks for your help,
Marc

  #Character role play
#you have 4 attributes and can assign/remove points to/from it
#use short story scripting to task with no MENU tree
#ignore calculus logic limitations

#set variables
strength_points = 0
health_points = 0
wisdom_points = 0
dexterity_points = 0
pool = 30
att_choice = None

attributes = [('strength',strength_points),
  ('health',health_points),
  ('wisdom',wisdom_points),
  ('dexterity',dexterity_points)]



print('Hello gladiator,\n')

print('you have the following attributes with no points:\n')

for i in attributes:
att_name, points = i
print(att_name,'\t',points)

input('\nPress ENTER to continue')

print('\nYou are now entrusted with a pool of 30 points to spend on them as you whish')
input('Press ENTER to continue')

print('\nUsing negative points will move them back to your pool of points')
input('Press ENTER to continue')

print('\nChose an attribute and add/remove points at your will:   ')

while att_choice != '0':

#here proof that variables values are changing as expexted:
print('here proof that variables values are changing as expected:')
print(strength_points,health_points,wisdom_points,dexterity_points,pool)


print('\n[1] stength [2] health [3] wisdom [4] dexterity [0] EXIT')
att_choice = input('ENTER number here: ')

if att_choice == '1':
  print('\nHow many strenght points you want to add (+) or remove (-) ?')
  points = int(input('Enter points here: '))
  strength_points += points
  pool -= points

elif att_choice == '2':
  print('\nHow many health points you want to add (+) or remove (-) ?')
  points = int(input('Enter points here: '))
  health_points += points
  pool -= points

elif att_choice == '3':
  print('\nHow many wisdom points you want to add (+) or remove (-) ?')
  points = int(input('Enter points here: '))
  wisdom_points += points
  pool -= points

elif att_choice == '4':
  print('\nHow many dexterity points you want to add (+) or remove (-) ?')
  points = int(input('Enter points here: '))
  dexterity_points += points
  pool -= points

elif att_choice == '0':
print('Good Bye Gladiator!')
break

else:
print('Sorry I don\'t understand your selection')
input('Press ENTER to try again')

print('\nYou have now the following attributes and points:\n')

#here the loop does not return variable value as expected:
for i in attributes:
att_name, point = i
print(att_name,'\t',point)

input('\nPress ENTER to continue\n')

input('\nPress ENTER to exit')


  

  



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


[Tutor] Beginner - list not returning correct variable value

2014-03-13 Thread Marc Eymard
Hello Tutor,

I am a self-taught Python script beginner and I do it from the Michael Dawson 
Book.

In attached script, can somebody tell me why the values of the variables 
strenght_points, health_points, wisdom_points and dexterity_points stay at 0 
value when 'printing' their value from the list attributes[] when the 'for' 
loop at the bottom of the script runs.

I have commented out the script to highlight what causes me problem.

I hope this is clear enough a question.

Thanks for your help,
Marc
  #Character role play
#you have 4 attributes and can assign/remove points to/from it
#use short story scripting to task with no MENU tree
#ignore calculus logic limitations

#set variables
strength_points = 0
health_points = 0
wisdom_points = 0
dexterity_points = 0
pool = 30
att_choice = None

attributes = [('strength',strength_points),
  ('health',health_points),
  ('wisdom',wisdom_points),
  ('dexterity',dexterity_points)]



print('Hello gladiator,\n')

print('you have the following attributes with no points:\n')

for i in attributes:
att_name, points = i
print(att_name,'\t',points)

input('\nPress ENTER to continue')

print('\nYou are now entrusted with a pool of 30 points to spend on them as you whish')
input('Press ENTER to continue')

print('\nUsing negative points will move them back to your pool of points')
input('Press ENTER to continue')

print('\nChose an attribute and add/remove points at your will:   ')

while att_choice != '0':

#here proof that variables values are changing as expexted:
print('here proof that variables values are changing as expected:')
print(strength_points,health_points,wisdom_points,dexterity_points,pool)


print('\n[1] stength [2] health [3] wisdom [4] dexterity [0] EXIT')
att_choice = input('ENTER number here: ')

if att_choice == '1':
  print('\nHow many strenght points you want to add (+) or remove (-) ?')
  points = int(input('Enter points here: '))
  strength_points += points
  pool -= points

elif att_choice == '2':
  print('\nHow many health points you want to add (+) or remove (-) ?')
  points = int(input('Enter points here: '))
  health_points += points
  pool -= points

elif att_choice == '3':
  print('\nHow many wisdom points you want to add (+) or remove (-) ?')
  points = int(input('Enter points here: '))
  wisdom_points += points
  pool -= points

elif att_choice == '4':
  print('\nHow many dexterity points you want to add (+) or remove (-) ?')
  points = int(input('Enter points here: '))
  dexterity_points += points
  pool -= points

elif att_choice == '0':
print('Good Bye Gladiator!')
break

else:
print('Sorry I don\'t understand your selection')
input('Press ENTER to try again')

print('\nYou have now the following attributes and points:\n')

#here the loop does not return variable value as expected:
for i in attributes:
att_name, point = i
print(att_name,'\t',point)

input('\nPress ENTER to continue\n')

input('\nPress ENTER to exit')


  

  



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


[Tutor] Beginner - Clarifying 'understanding randint arguments'

2014-02-17 Thread Marc Eymard
Hi Tutor,

The previous elements I sent to the mailing list were incomplete and needs no 
answer from Tutor.

To clarify and re-phrase my script issue:

I want to code a game whereby the computer guesses either by luck or deduction 
a number I pick within [0, 100].

In attached machine_guess_number.py in which line 22 statement number = 
random.randint(low_range + 1, high_range - 1) doesn't narrow the range:

- to allow number deduction...
- ...  avoiding ValueError: empty range for randrange()

I also attached the output of the script leading to the error showing that the 
loop does not exit in time to avoid error by working out the answer based on a 
logical narrowing of the guessing range.

Hope this clarifies my previous email (see further down this note).

Thanks,
Marc


 Subject: Your message to Tutor awaits moderator approval
 From: tutor-ow...@python.org
 To: marc_eym...@hotmail.com
 Date: Sat, 15 Feb 2014 17:26:41 +0100
 
 Your mail to 'Tutor' with the subject
 
 Beginner - understanding randint arguments
 
 Is being held until the list moderator can review it for approval.
 
 The reason it is being held:
 
 Post by non-member to a members-only list
 
 Either the message will get posted to the list, or you will receive
 notification of the moderator's decision.  If you would like to cancel
 this posting, please visit the following URL:
 
 
 https://mail.python.org/mailman/confirm/tutor/8ee9ed6d473cbc6d77ddc7af36237a9cc3b1d4b3
 

From: marc_eym...@hotmail.com
To: tutor@python.org
Subject: Beginner - understanding randint arguments
Date: Sat, 15 Feb 2014 16:25:34 +




Hello Tutor,

I need to generate a random integer between 0 and 100.

The range is supposed to be adjusted by my two variables:
low_range and high_range.

The
 logic of using the variables as part of the function arguments is to 
manage to get a smaller range each time the function is called excluding the 
possible repeat of the return value of randint.

Here is what happens in my script:

 import random
 low_range = -1
 high_range = 101
 random.randint(low_range + 1, high_range - 1)
56
 low_range
-1
 high_range
101

I was rather expecting:

  low_range
0
 high_range
100

Can somebody explain why both low_range and high_range are still returning 
their initial values ?

Thanks,
Marc
  
  #Guess my Number game
#The computer has to guess the player's number by either luck or deduction
#number has to be within [0, 100]

import random

print('Pick a number between and 0 and 100...')
print('...and let me try to guess in as few attempts as possible.\n')

input('Press ENTER when ready to play.\n')

# set variables
clue = ''
count_guess = 0
low_range = -1
high_range = 101


while clue != 'correct' and low_range != high_range:


number = random.randint(low_range + 1, high_range - 1)
	
count_guess += 1

print('\nIs your number', number, end= '? ')
clue = input('\n\nEnter one of the following clues:\n\n' \
+ '\t\thigher\n'
+ '\t\tlower\n'
+ '\t\tcorrect\n\n'
+ 'Type here and press ENTER: ')

if clue == 'lower':
 high_range = number			

elif clue == 'higher':
 low_range = number

elif clue == 'correct':

if count_guess  1:
 print('\nYou picked', number,'and it took me only', count_guess, 'attempts to find out.')

else: print('\nI could read your mind at once and saw you picked', number)


if low_range == high_range:
print('\nYou picked', number,'and it took me only', count_guess, 'attempts to find out.')


Python 3.3.2+ (default, Oct  9 2013, 14:50:09) 
[GCC 4.8.1] on linux
Type copyright, credits or license() for more information.
  RESTART 
 
Pick a number between and 0 and 100...
...and let me try to guess in as few attempts as possible.

Press ENTER when ready to play.


Is your number 92? 

Enter one of the following clues:

		higher
		lower
		correct

Type here and press ENTER: higher

Is your number 93? 

Enter one of the following clues:

		higher
		lower
		correct

Type here and press ENTER: higher

Is your number 97? 

Enter one of the following clues:

		higher
		lower
		correct

Type here and press ENTER: lower

Is your number 95? 

Enter one of the following clues:

		higher
		lower
		correct

Type here and press ENTER: higher

Is your number 96? 

Enter one of the following clues:

		higher
		lower
		correct

Type here and press ENTER: lower


Traceback (most recent call last):
  File /home/marc/Ubuntu One/Python/machine_guess_number.py, line 22, in module
number = random.randint(low_range + 1, high_range - 1)
  File /usr/lib/python3.3/random.py, line 214, in randint
return self.randrange(a, b+1)
  File /usr/lib/python3.3

Re: [Tutor] thanks - Beginner - explaining 'Flip a coin' bug

2014-02-15 Thread Marc Eymard
Hi David,

Thanks for your input about the logic of this little script of mine.

I confess I omitted the edge possibility and assumed heads or taisl only.

As I progress further with getting the foundation knowledge of the language 
itself, it is really appreciated to be corrected on what good programming is 
about regardless of the language.

Please keep commenting/helping whenever necessary.

Cheers,
Marc

Date: Fri, 14 Feb 2014 22:49:43 -0500
Subject: Re: [Tutor] Beginner - explaining 'Flip a coin' bug
From: dwightdhu...@gmail.com
To: marc_eym...@hotmail.com
CC: tutor@python.org

Here is a problem I've come across, from empirical evidence, that also relates 
to your equation. We always assume
 that their are always two probabilities, that a coin can be either head or 
tails. 


However, there are dynamics within a third realm of the dimensionality of the 
coin...it's not a two dimensional plane. So the planar probabilities in 
relation to the 'surface are' hold another possibility...the 'edge'.


The algorithm of applying the edge are up to you, but I've seen the coin land 
on it's curved edge more than once, so this function you've designed, should 
have more than two possibilities, within a complete algorithm to the real world 
functionality of the coin in question.



On Wed, Feb 12, 2014 at 10:25 AM, Marc Eymard marc_eym...@hotmail.com wrote:




Hello there,

I want to emulate a coin flip and count how many heads and tails when flipping 
it a hundred times.

I first coded coinflip_WRONG.py with count_flips += 1 statement within the 
if/else block.

When running it, either returned values are wrong or the script seems to enter 
in an infinite loop showing no return values at all.

coinflip.py is a corrected version I worked out myself. I moved count_flips+= 
1 out of if/else block and inserted it before if/else.


However, I still don't understand the bug since, in my understanding, both 
files are incrementing variable count_flips each time until the loop becomes 
false.

Can somebody explain the reason of the bug.

Cheers,

Marc
  

___

Tutor maillist  -  Tutor@python.org

To unsubscribe or change subscription options:

https://mail.python.org/mailman/listinfo/tutor




-- 
Best Regards,
David Hutto
CEO: http://www.hitwebdevelopment.com


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


[Tutor] Beginner - understanding randint arguments

2014-02-15 Thread Marc Eymard
Hello Tutor,

I need to generate a random integer between 0 and 100.

The range is supposed to be adjusted by my two variables:
low_range and high_range.

The logic of using the variables as part of the function arguments is to manage 
to get a smaller range each time the function is called excluding the possible 
repeat of the return value of randint.

Here is what happens in my script:

 import random
 low_range = -1
 high_range = 101
 random.randint(low_range + 1, high_range - 1)
56
 low_range
-1
 high_range
101

I was rather expecting:

  low_range
0
 high_range
100

Can somebody explain why both low_range and high_range are still returning 
their initial values ?

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


[Tutor] Beginner - explaining 'Flip a coin' bug

2014-02-12 Thread Marc Eymard
Hello there,

I want to emulate a coin flip and count how many heads and tails when flipping 
it a hundred times.

I first coded coinflip_WRONG.py with count_flips += 1 statement within the 
if/else block.
When running it, either returned values are wrong or the script seems to enter 
in an infinite loop showing no return values at all.

coinflip.py is a corrected version I worked out myself. I moved count_flips+= 
1 out of if/else block and inserted it before if/else.

However, I still don't understand the bug since, in my understanding, both 
files are incrementing variable count_flips each time until the loop becomes 
false.

Can somebody explain the reason of the bug.
Cheers,

Marc
  #Coin Flip
#Flip a coin 100 times and count heads and tails

input('Press ENTER to flip a coin a hundred times')

import random

#set count values
count_heads = 0
count_tails = 0
count_flips = 0


while count_flips != 100:
coin_side = random.randint(1,2)
count_flips += 1

if coin_side == 1:
count_heads += 1
#count_flips += 1

else: count_tails += 1
#count_flips += 1

print('The coin returned',count_heads,'heads and',count_tails,'tails.')
#Coin Flip
#Flip a coin 100 times and count heads and tails

input('Press ENTER to flip a coin a hundred times')

import random

#set count values
count_heads = 0
count_tails = 0
count_flips = 0


while count_flips != 100:
coin_side = random.randint(1,2)
#count_flips += 1


if coin_side == 1:
count_heads += 1
count_flips += 1

else: count_tails += 1
count_flips += 1

print('The coin returned',count_heads,'heads and',count_tails,'tails.')
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Which computer operating system is best for Python

2014-02-05 Thread Marc Tompkins
On Wed, Feb 5, 2014 at 3:18 PM, Joel Goldstick joel.goldst...@gmail.comwrote:

 I would get a laptop with as large a screen as you can afford. Windows or
 Linux.

 I second that emotion, and also: try out the keyboard first (or rather,
have your kid try it out).  We spend a lot of time on our laptops, and a
badly-designed keyboard can ruin an otherwise-great machine.  Yes, you can
plug in an external keyboard, mouse, and monitor, but most of the time
you're gonna stick with what came in the box.  Make sure you won't hate it.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Stuck on error

2013-12-21 Thread Marc Tompkins
On Sat, Dec 21, 2013 at 12:36 PM, NZHacker1 . nikolau...@gmail.com wrote:


 I'm not finished with the program and I put Plays = int(x) * 100,
 plays = int(x) * 100
 on purpose.


I don't think you understood what people were trying to tell you.  Python
is case-sensitive; plays and Plays are NOT the same variable.

The problem with line 47 is that you have this on the left side of the
equals sign: Game + z.
Can't assign to operator means that Python thinks you are trying to
assign a value to the plus sign, which is obviously impossible.

I'm not sure I understand what you really wanted to do in line 47.  I don't
know what your Game variable is supposed to be - is it a string?  A list of
strings?

Leaving aside the fact that what you've written is a syntax error... your
line 47 is trying to do this:
String + int = int + int + int + int + int + int

which wouldn't make any sense, and is probably not what you had in mind
anyway.

I think you're trying to get Game to contain a string that says something
like Game 5: 45 57 38 24 66 89, right?  If so, you want to use string
formatting for that, NOT addition.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What is a namespace? What is meant by A namespace is a mapping from names to objects

2013-12-09 Thread Marc Tompkins
On Sun, Dec 8, 2013 at 8:46 PM, Varuna Seneviratna 
varunasenevira...@gmail.com wrote:

 But what is meant by A *namespace* is a mapping from names to objects

Steven touched on this, but I'd like to emphasize: in Python, EVERYTHING is
an object - variables, functions, integers, strings, you name it.  (Even
names and namespaces, but that might be getting a little TOO meta.)
When I first came to Python, after years of languages where some things are
objects and other things aren't, this concept gave me a little trouble;
once I got my head around it, namespaces made sense too.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Issue w/ while loops

2013-11-23 Thread Marc Tompkins
On Sat, Nov 23, 2013 at 8:30 AM, Rafael Knuth rafael.kn...@gmail.comwrote:

 Marc,

 great feedback - thank you very much!
 I will bear that in mind for the future.

 I modified my program as you suggested, but I received a runtime
 error; I tried to fix that but unfortunately I didn't succeed.
 The modified program executes well only when the user input has the
 correct format (integer or float) and it breaks when the user enters a
 string (at that point the program should print (Invalid input) and
 loop back to its beginning).
 Can you please advise how I should change the program?
 Thank you so much!
 Raf

 Here's the original program:

 print(TIME TRACKING)

 while True:
 hours_worked = input(How many hours did you work today? )
 try:
 hours_worked = float(hours_worked)
 break
 except ValueError:
 print (Invalid input)
 if hours_worked  24:
 print(You must be a human.)
 else:
 print(You must be a cyborg.)

 Here's the modified version:

 print(TIME TRACKING)

 hours_worked = Invalid input
 while hours_worked == Invalid input:
 hours_worked = input(How many hours did you work today? )
 try:
 hours_worked = float(hours_worked)
 break
 except ValueError:
 print (Invalid input)
 if hours_worked  24:
 print(You must be a human.)
 else:
 print(You must be a cyborg.)

 And here's the error message I get:

 
 TIME TRACKING
 How many hours did you work today? very long hours
 Invalid input
 Traceback (most recent call last):
   File C:\Users\Rafael_Knuth\Desktop\Rookies At
 Work\Python\TimeReckord.py, line 12, in module
 if hours_worked  24:
 TypeError: unorderable types: str()  int()
 


The TypeError is basically just telling you that there's no meaningful way
to compare the string very long hours with the integer 24.  I should have
recommended an exit condition more along the lines of checking whether
hours_worked was still a string, like so:
while isinstance(hours_worked, str)

What I actually had in mind was to put the assignment to hours_worked
inside the try/except - initialize it to a value that will keep you inside
the loop, and only change its value to something that will escape the loop
if the user enters a valid value.  Like so:

hours_worked = Invalid input
while isinstance(hours_worked, str):
try:
hours_worked = float(raw_input(How many hours did you work today?
))
except ValueError:
print (Invalid input)
if hours_worked  24:
print(You must be a human.)
else:
print(You must be a cyborg.)

Note that I changed input to raw_input; I'm still using Python 2.7.  If
you're using Python 3, please disregard.

In any case, the objective I was after was to make the break
unnecessary.  Breaking out of a loop should only happen in unusual cases;
it shouldn't be the primary flow control.  (Not because it's necessarily
less efficient, or computationally wrong - but because a future maintainer
will have to drill down into the loop to figure out what's happening.)  If
your IDE supports collapsing indented sections, it should be possible to
understand the code flow without fully expanding it - or at least that's
what I strive for.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Finding a nearest perfect cube

2013-11-07 Thread Marc Tompkins
On Thu, Nov 7, 2013 at 2:25 PM, donsuni dons...@gmail.com wrote:

 Hi, I am new to python and i have to write a following code without using
 any
 inbuilt function or a for loop. Only while and if loops are allowed.

 If i input a number, i should get a perfect cube nearest to it.
 For eg: if
 input=4, output=8
 input=8, output=27
 and so on
 can some one help with the code?


You're about to get a deluge of responses just like this, but:
We don't do people's homework for them.
If you've made some effort and you're stuck, show us what you've done and a
LOT of people will be happy to help.  But doing it for you?  Not so much.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Parsing multiple lines from text file using regex

2013-10-27 Thread Marc
Hi,
I am having an issue with something that would seem have an easy solution,
which escapes me.  I have configuration files that I would like to parse.
The data I am having issue with is a multi-line attribute that has the
following structure:

banner option banner text delimiter
Banner text
Banner text
Banner text
...
banner text delimiter

The regex 'banner\s+(\w+)\s+(.+)' captures the command nicely and
banner.group(2) captures the delimiter nicely.

My issue is that I need to capture the lines between the delimiters (both
delimiters are the same).

I have tried various permutations of 

Delimiter=banner.group(2)
re.findall(Delimiter'(.*?)'Delimiter, line, re.DOTALL|re.MULTILINE)

with no luck

Examples I have found online all assume that the starting and ending
delimiters are different and are defined directly in re.findall().  I would
like to use the original regex extracting the banner.group(2), since it is
already done.  

Any help in pointing me in the right direction would be most appreciated.

Thank you,

Marc

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


Re: [Tutor] Want to keep to two decimal places for currency

2013-10-24 Thread Marc Tompkins
On Thu, Oct 24, 2013 at 11:25 AM, bob gailer bgai...@gmail.com wrote:

 On 10/24/2013 2:09 PM, Danny Yoo wrote:

 Related: I saw a picture the other day on Google+ of an mailing envelope
 whose zip code was written in scientific notation.

 That;s odd - since ZIP codes are character, not integer,


You'd like to think that, wouldn't you?  I've dealt with a disturbing
number of programs (some of them from big enough names that you'd think
they'd know better) that chose to represent zip codes as integers.  You'd
think that the fact that some of them have to be zero-filled would be a big
clue... but no.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Want to keep to two decimal places for currency

2013-10-24 Thread Marc Tompkins
On Thu, Oct 24, 2013 at 1:21 PM, Marc Tompkins marc.tompk...@gmail.comwrote:

 On Thu, Oct 24, 2013 at 11:25 AM, bob gailer bgai...@gmail.com wrote:

 On 10/24/2013 2:09 PM, Danny Yoo wrote:

 Related: I saw a picture the other day on Google+ of an mailing envelope
 whose zip code was written in scientific notation.

 That;s odd - since ZIP codes are character, not integer,


 You'd like to think that, wouldn't you?  I've dealt with a disturbing
 number of programs (some of them from big enough names that you'd think
 they'd know better) that chose to represent zip codes as integers.  You'd
 think that the fact that some of them have to be zero-filled would be a big
 clue... but no.


Zip+4 is a HUGE hassle for programs that have chosen to do things this
way...  Zip+4 has always been optional, but the 5010 format for healthcare
billing now requires that all zip codes (except patient's actual home
addresses) be represented in 9 glorious digits... that's made a bunch of
people scramble, let me tell you!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] class data member and objects of class in python

2013-09-11 Thread Marc Tompkins
On Wed, Sep 11, 2013 at 5:40 AM, zubair alam zubair.alam@gmail.comwrote:

 i am learning how a __class__ data member behaves in python as compared to
 static data member in java, but following code is throwing error


 class PizzaShop():
 pizza_stock = 10
 def get_pizza(self):
 while not PizzaShop.pizza_stock:
 PizzaShop.pizza_stock -= 1
 yield take yours pizza order, total pizzas left
 {}.format(PizzaShop.pizza_stock)

 mypizza_shop = PizzaShop()
 pizza_order = mypizza_shop.get_pizza() # iterator is obtained
 print a pizza pls!! {}:.format(pizza_order.next())
 print a pizza pls!! {}:.format(pizza_order.next())

 output:
 Traceback (most recent call last):
   File /home/scott/pythonfiles/core_python/pizza.py, line 10, in module
 print a pizza pls!! {}:.format(pizza_order.next())
 StopIteration


 don't know where i am doing mistakeany help will be appreciated... i
 have other questions on based on this class



Change while not PizzaShop.pizza_stock: to while
PizzaShop.pizza_stock:; I get the following output:

 a pizza pls!! take yours pizza order, total pizzas left 9:
 a pizza pls!! take yours pizza order, total pizzas left 8:

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


Re: [Tutor] dbus.Array to string

2013-08-13 Thread Marc Tompkins
On Tue, Aug 13, 2013 at 8:59 AM, Amit Saha amitsaha...@gmail.com wrote:


 What does it mean (and will it always work?) when I don't specify any
 encoding:

  bytearray(ssid).decode()
 u'BigPond679D85'


If you don't specify an encoding, then the default encoding is used; as you
point out a bit later, your local default is ascii.

Will it always work?  NO.  If there are any characters in the input stream
(the SSID in this case), .decode will fail (probably with
UnicodeDecodeError, but I can't test it at the moment.)

I don't know the WiFi spec well enough to know whether you're ever going to
run into non-ASCII characters in an SSID; I'm guessing that people in e.g.
Russia name their networks in Cyrillic, but (despite living in a Russian
neighborhood of Los Angeles) I've never seen any SSIDs that weren't pure
ASCII.  Does anybody out there know the rules for this?  Just now I tried
to change the SSID of my cell phone's mobile hotspot to Cyrillic, but the
configuration utility wouldn't even let me change keyboards; I don't know,
though, whether this is a limitation of the spec or just the local
implementation.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] To find the least number divisible by all numbers from 1-20

2013-08-13 Thread Marc Tompkins
On Tue, Aug 13, 2013 at 9:45 AM, #PATHANGI JANARDHANAN JATINSHRAVAN# 
jatinshr...@e.ntu.edu.sg wrote:

  Hello All,

 Sorry for the earlier mail without subject. I was in a hurry so I missed
 that

  I am solving problem number 5 in project euler. I think my solution
 seems logically correct but it is not giving an answer as it is taking too
 long to execute. So can someone suggest an alternative solution?


My approach: factor each number from 1 to 20 (for example, 20 factors to 1,
2, 2, 5) and build a list of factors; for each number, check to see that
the list contains enough copies of all of the current number's factors
(e.g. four 2s and two 3s) and add them to the list if not; at the end,
multiply the list of factors.

It took me about a minute in Excel; about 45 minutes to work out my
algorithm in Python - but it executed in less than a second.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to access a method defined in one class from another class (which is a thread) in Python3?

2013-08-08 Thread Marc Tompkins
On Thu, Aug 8, 2013 at 7:15 PM, Joel Goldstick joel.goldst...@gmail.comwrote:

 On Thu, Aug 8, 2013 at 9:52 PM, SM sunith...@gmail.com wrote:

 
  OP is me? Not sure what it stands for, but I am a 'she' :)

 FYI (For you information) OP means Original Poster.  Although people
 do refer to names in replies here, the term OP is used quite often.
 As for the implication of he not she, I guess we are stuck with
 guessing in English usage. (They doesn't cut it with Language mavens!)
 Good to have shes' to get more diverse user base.  Best thing about
 user groups is that different backgrounds make for better discussions
 and interesting ways of solving problems

 You know the old joke: on the Internet, nobody knows you're a dog...
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Can anyone explain this

2013-08-07 Thread Marc Tompkins
On Fri, Aug 2, 2013 at 4:33 PM, Amandeep Behl amandeep...@gmail.com wrote:

 Can anyone explain this code below:



 import sys
 import os

 if __name__ == '__main__':
 sys.path.insert(0, ..)
 else:
 sys.path.insert(0, os.path.join(
 os.path.split(__file__)[0], '..'))



When you run this module as a standalone, the value of __name__ will be
__main__; this is a standard test to see whether you're running it from
the command line or importing it from another script.

If you're running this code standalone, it will insert the directory one
level up from the current working directory (..) as the first item in the
Python path, so that subsequent imports will look there first.

If you're calling this code from another script, it can't rely on knowing
the current working directory - so it calls os.path.split to find the
directory where this file is located; then it inserts the parent of that
directory as the first item in the Python path.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] object size in python is in what units?

2013-07-23 Thread Marc Tompkins
On Tue, Jul 23, 2013 at 12:09 AM, Jim Mooney cybervigila...@gmail.comwrote:

 I've noticed that when I create a number of objects from a class, one
 after another, they're at different IDs, but the IDs all appear to be
 equidistant, so that they all appear to have the same size. But what does
 that size represent? is it bytes? ie - if I run this over and over I get
 different id numbers but they are always 40 apart. Or is that distance
 machine-specific as to units?:



 41599624 - different results for each run but always 40 apart
 41599664
 41599704
 '''


When I saved your code as a file on my machine (Python 2.7 on Win8 64-bit)
and ran it from the command line, I got the same result as you - three IDs,
40 apart every time.  However, I initially pasted your code into
PyScripter, and when I ran it inside PyScripter the results were different:
if the first ID was x, then the second was x+160, and the third was x+200.
(160 is obviously divisible by 40... I have no idea what conclusion to draw
from that.)

I simplified the test-harness portion as follows:
kronkList = []
for kronknum in xrange(0,100):
kronkList.append(Kronk(kronknum))
print(kronkList[kronknum].getzar())
print(kronkList[kronknum].getself())

and now the ID is incremented by 40 each time regardless how I run the
script.

Each time I run it, the last digit stays the same throughout the run (as
you would expect, given that we're adding 40 each time), but the last
digits are NOT consistent _between_ runs.  It appears to always be an even
number, though.

As an experiment, I added a couple of extra methods and attributes to the
Kronk class, but it didn't change anything - IDs still incremented by 40
each time.  eryksun will no doubt chime in to tell us exactly how object
IDs are derived in cPython, but I'll go out on a limb and say that they
have nothing to do with the size of the object; also that one would be very
silly to make a program rely in any way on predicting the next ID, since
external factors may throw off the calculations (as when I invoked your
original script from inside PyScripter).  All that you can rely on is that
each unique object (i.e. doesn't pass an is comparison with any other
object) has a unique ID... and, for all I know, not even that.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] object size in python is in what units?

2013-07-23 Thread Marc Tompkins
On Tue, Jul 23, 2013 at 1:13 AM, Marc Tompkins marc.tompk...@gmail.comwrote:


 As an experiment, I added a couple of extra methods and attributes to the
 Kronk class, but it didn't change anything - IDs still incremented by 40
 each time.  eryksun will no doubt chime in to tell us exactly how object
 IDs are derived in cPython, but I'll go out on a limb and say that they
 have nothing to do with the size of the object; also that one would be very
 silly to make a program rely in any way on predicting the next ID, since
 external factors may throw off the calculations (as when I invoked your
 original script from inside PyScripter).  All that you can rely on is that
 each unique object (i.e. doesn't pass an is comparison with any other
 object) has a unique ID... and, for all I know, not even that.


A couple of clarifications I wish I'd made before hitting Send:  I
shouldn't have said that IDs are derived or calculated; they're
assigned, presumably on a first-come, first-served basis; when I said
external factors may throw off the calculations I meant may make your
calculations non-congruent with reality.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] object size in python is in what units?

2013-07-23 Thread Marc Tompkins
On Tue, Jul 23, 2013 at 1:17 AM, Jim Mooney cybervigila...@gmail.comwrote:

 On 23 July 2013 00:40, Steven D'Aprano st...@pearwood.info wrote:


 No no no, a thousand times no!!! IDs are just numeric IDs, that is all,
 like your social security number or driver's licence number. Don't think of
 them as having any meaning at all, except that they are unique during the
 lifetime of the object.


 Okay, ID stands for a location fixed until the object disappears, but we
 don't know where that location is. But what about object offsets from self?
 Is the beginning of self.spam always the same distance from the beginning
 of self.eggs? Or can I just forget the hard ground of assembler-metaphors
 entirely as I float off into abstractville? I guess the fixed lengths I
 kept getting on re-runs were coincidental but not to be relied on.


As Steven said: they are NOT locations, they are IDs.  There is no distance
involved.  You CAN find the size of an object, and you can find its
location in memory (but you really shouldn't bother, or rely on it) but
neither of those things has any particular relation to the ID, except
accidentally.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] close, but no cigar

2013-07-23 Thread Marc Tompkins
On Tue, Jul 23, 2013 at 7:46 AM, Steven D'Aprano st...@pearwood.infowrote:

 This is not quite as silly as saying that an English E, a German E and a
 French E should be considered three distinct characters, but (in my
 opinion) not far off it.


I half-agree, half-disagree.  It's true that the letter E is used
more-or-less the same in English, French, and German; after all, they all
use what's called the Latin alphabet, albeit with local variations.  On
the other hand, the Cyrillic alphabet contains several letters that are
visually identical to their Latin equivalents, but used quite differently -
so it's quite appropriate that they're considered different letters, and
even a different alphabet.
I don't know enough about the similarities and differences between various
East Asian languages to know whether, say, Chinese and Korean are more like
English and German or more like English and Russian - but that, rather than
the visual similarity, would be my criterion for deciding.

Spot the differences:

A  Аa  а
B  Вb  в
C  Сc  с
E  Еe  е
Ë  Ёë  ё
K  Кk  к
M  М   m м
   n  п
O  Оo  о
P  Рp  р
T  Т t   т
  u  и
X  Х x  х
Y  Уy  у

A few notes:
-  this won't look right unless your email client is Unicode-capable
-  no, I'm not saying that these letters are equivalent - some (T and Т, K
and К) basically are, others (E and Е, n and п) definitely are not - I'm
just saying that they are visually similar if not identical
-  just HOW similar they are depends on which typeface you use.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] unichr not working as expected

2013-07-23 Thread Marc Tompkins
On Tue, Jul 23, 2013 at 12:31 PM, Dave Angel da...@davea.name wrote:

 The three distributed version control systems I know of are:
git, mercurial, and bazaar


Not to overplay my Joel Spolsky fanboiism, but are you aware of Kiln from
Fog Creek?  It started out as an enterprise-friendly wrapper around
Mercurial (which is still Joel's favorite, apparently), but they decided to
make it agnostic: it now round-trips seamlessly between git and Mercurial,
with users of either not needing to know or care what other users prefer.

Of course, I haven't actually used it myself, so I only have the
developers' word to go by that it's the greatest thing since sliced bread -
but I thought I'd mention it.
http://www.joelonsoftware.com/items/2013/03/11.html
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] slashes in paths

2013-07-22 Thread Marc Tompkins
On Mon, Jul 22, 2013 at 10:47 AM, Jim Mooney cybervigila...@gmail.comwrote:

I forgot about TREE. But figured piping C:\Python27tree /f  pytree.txt
 might be illuminating. I piped since it took forever to print because I
 have python(x,y). Unfortunately, I got tiny numbers and A with umlauts
 instead of the nice path outlines in the dos box:

 ³   ³   ³   ³   ÀÄÄÄtests


That's an encoding problem; TREE is apparently not Unicode-aware, and uses
the old ASCII-US code page for values above 127.  I suspect that bringing
ancient command-line utilities into the
Notepad++ is my default text editor; I was able to see the line-drawing
characters properly after I selected Encoding/Character sets/Western
European/OEM-US.  No idea what you'd need to do in other text editors...

TREE /? displays the following:
Graphically displays the folder structure of a drive or path.

TREE [drive:][path] [/F] [/A]

   /F   Display the names of the files in each folder.
   /A   Use ASCII instead of extended characters.

Using /f /a will give you a readable file, no matter which text editor you
use.

I suspect that it hasn't been updated for Unicode for two reasons:
 1) updating TREE to use Unicode for line-drawing would break compatibility
for people who pipe its output into other CLI programs in the *nix style
 2) although Microsoft could get around that by adding another command-line
switch, there probably isn't an awful lot of demand - who uses TREE
anymore, except in the context of discussions like this?


If you haven't already read it, may I suggest Joel's intro to Unicode?
http://www.joelonsoftware.com/articles/Unicode.html
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] slashes in paths

2013-07-22 Thread Marc Tompkins
On Mon, Jul 22, 2013 at 11:30 AM, Jim Mooney cybervigila...@gmail.comwrote:

 On 22 July 2013 11:26, Marc Tompkins marc.tompk...@gmail.com wrote:




 If you haven't already read it, may I suggest Joel's intro to Unicode?
 http://www.joelonsoftware.com/articles/Unicode.html


 I had a bad feeling I'd end up learning Unicode ;')


It's not as painful as you might think!  Try it - you'll like it!
Actually, once you start getting used to working in Unicode by default,
having to deal with programs that are non-Unicode-aware feels extremely
irritating.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] slashes in paths

2013-07-22 Thread Marc Tompkins
On Mon, Jul 22, 2013 at 11:57 AM, Jim Mooney cybervigila...@gmail.comwrote:

 I had a bad feeling I'd end up learning Unicode ;')



 It's not as painful as you might think!  Try it - you'll like it!
 Actually, once you start getting used to working in Unicode by default,
 having to deal with programs that are non-Unicode-aware feels extremely
 irritating.


 I'll have to, to write a python program to translate the tree output. I
 tried More, but since I have Python(x,y) I gave up after holding down the
 enter key for five minutes. I tried piping More but that didn't work right.
 I probably forgot DOS. but since DOS isn't commonly used, a python program
 would be better anyway.


You'd be better off skipping TREE entirely and going pure-Python.  TREE -
being Unicode-naive - can't deal with any foreign-alphabet characters
beyond the few baked in alongside the box-drawing characters; they all get
turned into question marks.  I'm guessing that's not an issue on your own
computer, but if you ever want to deal with files from other people...
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] close, but no cigar

2013-07-22 Thread Marc Tompkins
On Mon, Jul 22, 2013 at 11:27 AM, Jim Mooney cybervigila...@gmail.comwrote:

 Okay, I'm getting there, but this should be translating A umlaut to an old
 DOS box character, according to my ASCII table, but instead it's print
 small 'u':

 def main():
 zark = ''
 for x in ÀÄÄÄ:
 print(unichr(ord(u'x')-3), end=' ')

 result: u u u u


When you type Ä in a Python string (without specifying which encoding
you're trying to represent), it doesn't necessarily have the same ordinal
value as the line-drawing character that gets mistakenly displayed as Ä
in your text editor.  Depending on which Python version you happen to be
using at the moment (and therefor depending on the default encoding), Ä
might be a Unicode Latin Capital Letter A With Diaeresis (U+00C4), or it
might be character code 0x8E, or it might be 0xC4...

For a quick visualization of what I'm talking about, just fire up the
Character Map program and find Ä in the following fonts: Arial, Terminal,
and Roman.  Float your mouse cursor over it each time to see the character
code associated with it.

If you insist on parsing the output of TREE (instead of letter Python do
things in a modern, Unicode-aware way), here's how I would do it:

inFileName = /Users/Marc/Desktop/rsp/tree.txt
with open(inFileName, 'r') as inFile:
inString = inFile.read().decode('cp437')
print inString

This printed out the line-drawing characters just fine; my test Cyrillic
filename remained a string of question marks, because TREE itself had
trashed that filename and there wasn't anything for .decode() to decode.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


  1   2   3   4   5   >