Re: [Tutor] List of tuples

2016-04-20 Thread Alan Gauld via Tutor
On 19/04/16 21:56, isaac tetteh wrote:
> I have a list like this 

> [
> ("name",2344,34, "boy"),("another",345,47,"boy", "last")
> ]

Assuming this is list_tuple...

> for row in list_tuple:
> for row2 in row:
> return row

This can't work because return needs to be inside a function.
So you obviously are not showing us all of your code.
Also the code above would not give the error you report.

So we need to see the whole code and the whole error message.

Also can you explain how you want the output presented.
Do you want values returned from a function or do you want
them printed on screen or do you want them represented
by a string? Your mail suggests you wanted them printed
but your code suggests you want them returned from a
function. Which is it?


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Fwd: List of tuples

2016-04-20 Thread Alan Gauld via Tutor
On 20/04/16 06:52, isaac tetteh wrote:

>> Thanks things are working good now. The only problem is 
>> i want to print the for loop output on one line instead of on each line.
>> Example [1,2,3,4,5]
>> Output 
>> 1 2 3 4 5 
>> I would to do this in Jinja 

I don;t know what Jinja is but...

When you say 'print', where do you want to print it?
It seems you are using Flask so presumably the output goes to a web
page? So presumably you really want to output a string? Or do you
literally want to print to the console?

If you want a string from a list of values you can use join():

s = ' '.join([str(n) for n in outputList])

If you want to print to console you can use

for n in outputList:
   print n, # note the comma

in Python v2 or

for n in outputList:
print (n, end=' '))

in Python v3

or just combine the techniques:

s = ' '.join([str(n) for n in outputList])
print(s)


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] The game of nim in python

2016-04-22 Thread Alan Gauld via Tutor
On 22/04/16 13:45, Henderson, Kevin (GE Aviation, US) wrote:
> Python to Jython.
> 
> Can you help me with a Jython code for the Nim game?
> 

There shouldn't be much difference between a Jython or Python
implementation - unless you are building a GUI of course!

> Removing 1-4 sticks out of 13, last player who picks up the last stick wins

Ive no idea how nim is played although I re,em,ber my math
teacher talking about it as being the only practical use
of binary outside computing...

But what kind of help do you need? Does your code work?
Is there an error (if so send us the full text)?
Do you want a general code review?
What exactly do you want from us?

> player1=str(input("Enter your name. "))
> player2="Computer"
> howMany=0
> gameover=False
> strawsNumber=random.randint(10,20)
> 
> if (strawsNumber%4)==1:
> strawsNumber+=1
> 
> def removingStrawsComputer():
> removedNumber=random.randint(1,3)
> global strawsNumber
> while removedNumber>strawsNumber:
> removedNumber=random.randint(1,3)
> strawsNumber-=removedNumber
> return strawsNumber
> 
> def removingStrawsHuman():
> global strawsNumber
> strawsNumber-=howMany
> return strawsNumber
> 
> def humanLegalMove():
> global howMany
> legalMove=False
> while not legalMove:
> print("It's your turn, ",player1)
> howMany=int(input("How many straws do you want to remove?(from 1 to 
> 3) "))
> if  howMany>3 or howMany<1:
> print("Enter a number between 1 and 3.")
> else:
> legalMove=True
> while howMany>strawsNumber:
> print("The entered number is greater than a number of straws 
> remained.")
> howMany=int(input("How many straws do you want to remove?"))
> return howMany
> 
> def checkWinner(player):
> if strawsNumber==0:
> print(player," wins.")
> global gameover
>gameover=True
> return gameover
> 
> def resetGameover():
> global gameover
> gameover=False
> return gameover
> 
> def game():
> while gameover==False:
> print("It's ",player2,"turn. The number of straws left: 
> ",removingStrawsComputer())
> checkWinner(player1)
> if gameover==True:
> break
> humanLegalMove()
> print("The number of straws left: ",removingStrawsHuman())
> checkWinner(player2)
> game()

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] python equivalents for perl list operators?

2016-04-23 Thread Alan Gauld via Tutor
On 23/04/16 01:15, Malcolm Herbert wrote:

>   @raw = (2, 1, 4, 3);
>   @grepped = grep { $_ >= 3 } @raw; # (4, 3)

grepped = [item for item in raw if item >= 3]

>   @mapped = map { $_ + 1 } @raw; # (3, 2, 5, 4)

mapped = [item +1 for item in raw]
or
mapped = map(lambda x: x+1, raw)

>   @sorted = sort { $a > $b } @raw; # (1, 2, 3, 4)

raw.sort()  # sorts in place
_sorted = sorted(raw)

You can add parameters to both functions to specify
sort characteristics, for example:

raw2 = [(1,'p'),(2,'e'),(3,'r'),(4,'l')]

lexical = sorted(raw2,key=lambda t:t[1])

You can use the interpreter to find out some of this
by using the help() function

help([])  # help on all list methods

help([].sort)  # help on the sort method

There are also some modules that might be of interest
to you such as itertools and functools.

You might also find the Functional Programming
topic in my tutorial useful (see below).

hth
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] XML and ElementTree

2016-04-25 Thread Alan Gauld via Tutor
On 25/04/16 17:24, Marco Soldavini wrote:
> I've a few questions about parsing XML. I wrote some code that works
> but I want to know which are the most intelligent data structures to
> parse data to

Answer: The ones that suit what you want to do with it.
But you haven't told us what you plan on using it for so
we can't tell you what is suitable.

> 
> 
> 1
> XXX
> 
>
>
>
>
>
>
> 
> 
> 
> 
> 
> 
> 
> So root element can have station child element from 1 to n
> Each station element have unique child elements apart from groups
> which may have more group child element each with a few tags
> 
> Now I want to parse this xml file and get the tag values into
> variables in python
> I could have 1 station element or 2 or 3

So you could have a list or a dictionary of Stations.
Each station might be simple values, or tuples, or dictionaries
or an instance of a Station class.

> I could append all data in a long list, but is this good?

It all depends on what you want to do.
If you just want to process all the stations sequentially then yes,
a long list is good. (Unless its too long in which case you may
be better with a database or a flat file.)

> If later in the program I want to access a variable value I want to do
> it with the xml tag name and not with an index like Settings[10] for
> example but something like Settings['tag']

That suggests a dictionary or class would be best. (Although
a named tuple or database may also be appropriate.)

> But what if I have more than one structure like station which has the same 
> keys?

Figuring out object identity is always tricky when the data
is similar. a Database solution offers row ids to disambiguate similar
entries. A class based solution has an id (usually the memory address),
a list has its index. Its really up to you to determine the best
option based on your needs.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Using a dictionary to map functions

2016-04-26 Thread Alan Gauld via Tutor
On 26/04/16 05:30, Colby Christensen wrote:

> import re
> from store_point import store_point
> 
> try:
> infile = open(raw_input("Enter input file name; name.txt:"),'r')
> except:
> print "Invalid filename"
> exit()
> 
> templist = []
> pt_table = {}
> cmd_table = {5:"store_point", 19: "line_line_int"}

Almost...

You need to store the actual function name not a string:

cmd_table = {
  5 : store_point,
 19 : line_line_int
 # etc...
}

Notice, no quotes.


> for line in infile:
> #print line
> line = line.rstrip()
> if re.search('^[0-9]+', line):
> a = line.split()
> templist.append(a)
> 
> for line in templist:
> #use dictionary to call and pass arguments to function

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] def __init__(self):

2016-04-26 Thread Alan Gauld via Tutor
On 26/04/16 08:01, Santanu Jena wrote:
> Hi,
> 
> Pls let me why
> "
> def __init__(self):
> 
> "
> declaration required, what's the use of this one.Pls explain  me in
> details.

It is used to initialise object instances.
For example if you define a class Rectangle that has a length and width
and a method to calculate the area:.

class Rectangle:
length = 0   # defaults in case we forget to add them
width = 0
def area(self):
   return self.length * self.width

That works after a fashion:

r = Rectangle()
r.length = 20
r.width = 10
print r.area()   # prints 200

But it is clumsy. It would be better to define the
length and width as part of the object creation. To
do that we add an __init__() method:


class Rectangle:
   def __init__(self, len, width):
  self.length = len
  self.width = width
   def area(self):
  return self.length * self.width

r = Rectangle(20,10)
print r.area()  # prints 200

So the init method allows us to initialise the values
of the data attributes of our objects at the time of
creation. (You can also call other methods inside init()
of course but that is less common)

You can read more about __init__() in my tutorial
at the end of the Raw Materials topic and again
in the OOP topic.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] XML and ElementTree

2016-04-26 Thread Alan Gauld via Tutor
Forwarding to tutor list.
Please always use "Reply All" or "Reply List" when responding to the
tutor list.

On 26/04/16 09:24, Marco Soldavini wrote:
> On Tue, Apr 26, 2016 at 2:05 AM, Alan Gauld via Tutor  
> wrote:
>> On 25/04/16 17:24, Marco Soldavini wrote:
>>> I've a few questions about parsing XML. I wrote some code that works
>>> but I want to know which are the most intelligent data structures to
>>> parse data to
>> Answer: The ones that suit what you want to do with it.
>> But you haven't told us what you plan on using it for so
>> we can't tell you what is suitable.
>>
> Let's say I would use the tag values as argument of function call in
> the subsequent part of the program.
>
> For example one tag will contain a server address. In the program I'll
> have a function which will use this address to perform a connection.
>


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos

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


Re: [Tutor] Is there a library which has this object?

2016-04-28 Thread Alan Gauld via Tutor
On 28/04/16 14:53, Yeh wrote:
> Hi,
> Is there a library which can return some numbers continuously? 

You probably want to look at the itertools module.

There you can find among others the count() generator function.
Others of possible interest include cycle() and repeat()

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Detect the folder of a file

2016-04-28 Thread Alan Gauld via Tutor
On 28/04/16 11:11, Steven D'Aprano wrote:

> You know, some day I must learn why people use virtual environments. 

Me too :-)

My co-author included a section in one of her chapters of our
recent book, and I duly played with them while reviewing that
chapter. But at the end I just deleted it all and
thought "H?"

I know why they are useful in theory, but I've never found
a practical use for them myself.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Is there a library which has this object?

2016-04-28 Thread Alan Gauld via Tutor
On 28/04/16 19:08, Yeh wrote:

> I just solved my first question by using numpy, as below:

You need to post in plain text otherwise the mail system mangles your
code, as you can see.


> import timeimport numpy as np
> start = input("please input the value of start: ")end = input("please input 
> the value of end: ")dur = input("please input the value of dur: ")array = 
> np.linspace(float(start),float(end),1000)dur = float(dur)/len(array)for i in 
> array:print(float(i))time.sleep(dur)


> But, how to make it become a function?
> I tried to:

> def myFunction(start,end,dur):...for i in array:return i
> time.sleep(dur)


> as you see, I failed...

We can't see. We don't know what the dots are, and we
don't know where the return is. Most of all we don't know
if you get an error, or what the error says.

The more specific information you give us the more chance
we have of helping you.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] vpython help

2016-04-29 Thread Alan Gauld via Tutor
On 29/04/16 00:27, Craig, Daniel Joseph wrote:

> I am writing a program where I have a ball with a position and velocity 
> reach a wall in 3D space.

Well done, but vpython is a bit off topic for this list which deals with
the core python language and libraries.

I notice there is a vpython user forum, you might get
more/better  answers there:

https://groups.google.com/forum/?fromgroups&hl=en#!forum/vpython-users

> I am able to drag the ball around after it is done moving
> but I would like to be able to move the ball prior to
> it moving towards the wall.

I'm not clear what you mean by that. I'm sure it will be possible
but it sounds very vpython specific.

If you ask on the vpython forum you should probably include
some code to show what you have done so far. And include
any error messages too.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] (no subject)

2016-04-29 Thread Alan Gauld via Tutor
On 29/04/16 14:10, Павел Лопатин wrote:
> Hello,
> I downloaded Python 3.4.3 from python.org, installed it, 
> but when I tried to run it on my notebook a message appeared

The error is about IDLE rather than about Python so
its probably worth checking whether python itself
runs first.

Open a CMD console

WindowsKey-R  (Or Start->Run)
Type cmd and hit ok.

In the window that appears type python3

You should see a prompt that looks something like

Python 3.4.3 (default, Oct 14 2015, 20:28:29) [GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

Except yours will say Windows rather than linux, etc.

If so then python is working OK and we can then look into
the IDLE issues.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] pytsk

2016-04-29 Thread Alan Gauld via Tutor
On 29/04/16 14:15, Tees, Peter (EthosEnergy) wrote:

> Now I want to put what I've learned to good use, based on the 
> articles by David Cowen at the Hacking Exposed blog
> and in particular his series "Automating DFIR - How to series
> on programming libtsk with Python"

> Can anyone point me to a Windows 32-bit installer 

Nope, I can only find the Github site which requires you to
build it from source. And given it appears to be written in
C that may be too advanced a topic for you just now.

Maybe you should start with something simpler? Or find
a different library to do what you want to do...

> for a pytsk library that will work with Python 2.7?

I did find a v3 pytsk, which presumably is for Python v3.
I didn't notice a Win32 installer for it though.

Normally I'd refer you to the pytsk community for further
support since its really outside the scope of this list,
but I didn't see any links to such a group. You may be best
emailing the author (or the author of the tutorial you
were reading)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Sorting a list in ascending order [RESOLVED]

2016-04-29 Thread Alan Gauld via Tutor
On 29/04/16 23:58, Ken G. wrote:

>> print ''.join(list1) #making it again as a single string
>>
> 
> Thanks, Meena, that is great! I changed your last line to:
> 
>  print "".join(list1)  and it came out as below:
> 
>  0511414453
> 
> Another quotation mark was needed.

No it wasn't. Meena used two single quotes, you used
two double quotes. Both will work. But the two single
quotes can look like a single double quote depending
on your font choices. So double quotes in this case
are probably less ambiguous.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Sorting a list in ascending order [RESOLVED]

2016-04-29 Thread Alan Gauld via Tutor
On 30/04/16 00:05, Ken G. wrote:

> been able to change over to Python3. I am not together sure if Python3 
> is now more stable to use and more commonly use. 

It is definitely stable and most libraries are now converted (although a
few remain v2 only). Availability of libraries is now the only real
reason to stick with v2 IMHO.

> change over but do realize there is a learning curve to learn. 

The main learning is in the libraries rather than the core language.
Quite a lot of modules got changed/moved/renamed etc. Also the
return values of a lot of functions changed to iterators and the like.
Those are the things that tend to catch you out, not the core language.

> there is a script to translate my Python2 programs to Python3 format. 

Yes there is, although it's not foolproof, you often have to manually
tweak things. It comes with v3 in, I think, the scripts folder.

There is also something called six that you should investigate
if you have a significant amount of v2 code to manage alongside v3.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Extracting bits from an array

2016-04-29 Thread Alan Gauld via Tutor
On 29/04/16 20:47, Anish Kumar wrote:

>> Is the number of bits fixed to four? If so you can shift the bits to the 
>> right:
>>
> y = [v>>2 for v in x]
> 
> Right shifting is well defined in Python?

Yes, Python has good support for all the common bitwise
operations, including the shift right/left operators.
Read the documentation for the limitations.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Issue with Code

2016-04-30 Thread Alan Gauld via Tutor
On 30/04/16 16:30, Olaoluwa Thomas wrote:

> I've attached the scripts in question (created via Notepad++).

attachments often get stripped by the mail system as a security risk.
Since your code is very short just post it in the mail message
as plain text.

> The problem with this script is that the "else" statement (which is
> equivalent to the 1st script) does not compute gross pay accurately as seen
> in the attached screenshot.

The screenshot seems to have been stripped so we can't see it.
Just tell us what happened and what you expected. Or better
still cut 'n paste the output into the message.

> I would appreciate a logical explanation for why the "else" statement in
> the 2nd script isn't working properly.

It almost certainly is working properly, just not as you expected
it to :-)

When dealing with floating point numbers remember that they will
always be approximations to the whole number so calculations will
similarly result in approximations. Usually if you round the
results the figures will look ok.

I can't see anything obviously wrong in your code although
it could be simplified. Please post a sample including the
inputs and outputs. Tell us what you expect to see as well
as showing us what you do see.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Fwd: Issue with Code

2016-04-30 Thread Alan Gauld via Tutor
On 30/04/16 22:32, Olaoluwa Thomas wrote:

> I sent this forwarded email earlier but hadn't subscribed to the mailing
> list so I guess that's why I didn't get a response.

When you first subscribe all messages are moderated so there
is a delay. Plus remember that email is pretty much the lowest
priority message type on the internet so mail can be delayed
for up to 24 hours, so you may not always get an instant
response even when everything is working as it should.

I have now taken you off moderation which should speed
things up a bit...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Is there a library which has this object?

2016-04-30 Thread Alan Gauld via Tutor
On 30/04/16 08:48, Yeh wrote:

> start = input("please input the value of start: ")
> end = input("please input the value of end: ")
> dur = input("please input the value of dur: ")
> array = np.linspace(float(start),float(end),1000)
> dur = float(dur)/len(array)
> for i in array:
> print(float(i))
> time.sleep(dur)

Since you say it works I assume you are still not posting
in plain text since it would need indentation after
the for loop.

> and it worked, then, I was trying to make it as a function:
> 
> def myFunction(start,end,dur):
> ...

I don;t know what the dots are. They should give you an error!

> for i in array:
> return i
> time.sleep(dur)
> 
> there is no errors. because it just post the first number in the array, 

Your problem is that return always returns the value and
exits the function. Next time you call the function it
starts again from the beginning.

I think you are looking to create a generator which is
a function that returns a value but next time you call
the function it carries on where it left off.
The good news is that this is easy, just substitute
yield for return. The next problem is to make the function
increment the value each time and for that you need a loop.

def make_numbers(start, end):
while start <= end:
   yield start

Notice I've removed the duration parameter because that's
better done outside the function (a function should do
only one thing, in this case generate numbers).

We can access the numbers and introduce a delay with:

for n in make_numbers(float(start),float(end))
print (n)
time.sleep(float(dur))

But of course that's pretty much what the built in
range() function does for you anyway.

for n in range(float(start), float(end)):
print(n)
time.sleep(float(dur))

> I have checked the cycle(), and yes, that is what I'm searching! 

> how to stop cycle() by manual?
> such as press "q", then break the cycle(). 

You will need to include a command to read the
keyboard during your loop. How you do that depends
on your needs and maybe your OS. You can use input()
but the user then needs to hit a key every loop iteration.
Or you can use getch() from curses on Linux or from
msvcrt on Windows if you don't want the user to  have
to hit enter each time.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Issue with Code

2016-04-30 Thread Alan Gauld via Tutor
On 01/05/16 01:16, Alan Gauld via Tutor wrote:

> I can't see anything obviously wrong in your code

I was too busy focusing on the calculations that
I didn't check the 'if' test closely enough.
You need to convert your values from strings
before comparing them.

hours = float(raw_input ('How many hours do you work?\n'))
rate = float(raw_input ('What is your hourly rate?\n'))
if hours > 40:
   gross = (hours-40)*(rate*1.5) + (rate*40)
else:
   gross = hours*rate


Sorry,

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Issue with Code [SOLVED]

2016-05-01 Thread Alan Gauld via Tutor
On 01/05/16 05:20, Olaoluwa Thomas wrote:
> Thank you so much, Alan. That fixed it (See Script 2[SOLVED] below).
> 
> For the purpose of record-keeping, I'm pasting the entire code of all
> scripts below as I should have done from the very beginning.
> 

thanks :-)

> P.S. How were you able to open attachments with the restrictions on this
> mailing list?

The two code attachments made it to my reader.
But that seems to be a fairly arbitrary occurence.
The screen shot didn't make it.

Some make it, others don't. I don't know the exact
set of rules that determine when an attachment
gets through!

> Script 2 [SOLVED]
> hours = float(raw_input ('How many hours do you work?\n'))
> rate = float(raw_input ('What is your hourly rate?\n'))
> if hours > 40:
> gross = ((hours - 40) * (rate * 1.5)) + (40 * rate)
> elif hours >= 0 and hours <= 40:
> gross = hours * rate
> print "Your Gross pay is "+str(round(gross, 4))

You could have left it as else rather than elif,
but otherwise that's fine.

> I'm gonna add Try and Except to make it more responsive.

I'm not sure what you mean by responsive? The only
place try/except could/should be applied is round
the float conversions. But it only makes sense if
you put them inside a loop so you can force the
user to try again if the input is invalid.

Something like:

while True:
   try:
 value = float(input(...))
 break
   except ValueError:
 print 'warning message'
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] META: Moderation and subscription to the tutor list

2016-05-01 Thread Alan Gauld via Tutor
On 01/05/16 05:18, Steven D'Aprano wrote:

> What's your policy here on the tutor list? 

I don't really have a policy. The list policy, set by
my predecessors, is to allow anyone to send mail and
encourage them to subscribe. All unsubscribed mail
goes to moderation (and there is not very much of it).

New subscribers are automatically put on moderation.
They are manually removed from moderation when they
post often enough that I recognize their ID and have
enough time/energy to visit the members page...

Replies can be seen by non subscribers in several
places including python.org, activestate.com and gmane.

> I think we should require 
> subscription before people can post. 

That doesn't achieve much since several lists servers
like gmane are subscribed so anyone on gmane etc can post
(albeit they go into the moderation queue). And the hassle
of subscribing may put some newbies off posting at all,
which we don't want.

> (And I think we should default to individual emails, 
> not daily digest.)

Quite a lot of people use the digest service, especially lurkers.
(A quick scan of the members lists suggests around 35-40%
of all members use digest). I'd be reluctant to remove a
service that is so widely used.

While modern mail tools generally have filters that can do
a similar job I do sympathise with digest users since I used
to be one of them and it was a useful way to keep the mail
count down. But they should take the time to post replies
'nicely'...


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] META: Moderation and subscription to the tutor list

2016-05-01 Thread Alan Gauld via Tutor
On 01/05/16 06:35, c...@zip.com.au wrote:

> There seems to me a subjectly large number of very short threads with a 
> question from someone, a couple of responses from list members, and no 
> further 
> reply.
> 
> To me this argues that either newcomers are not subscribed and probably do 
> not 
> see any responses, or that sufficient are discourteous enough or naive enough 
> to nothing bother to acknowledge help.

I suspect the latter...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] META: Moderation and subscription to the tutor list

2016-05-01 Thread Alan Gauld via Tutor
On 01/05/16 10:06, Alan Gauld via Tutor wrote:

> Quite a lot of people use the digest service, especially lurkers.
> (A quick scan of the members lists suggests around 35-40%
> of all members use digest). I'd be reluctant to remove a
> service that is so widely used.

I've just had a look at the digest options and one possible option
is to send a Mime format digest rather than plain text. I'm not sure
what that would mean in practice but from experience on other
lists it may mean users see individual messages that they can reply to.
This would potentially avoid the long multi-message replies we currently
see. I don't know how it would affect threading.

I therefore propose to switch on MIME digest mode as a trial
at the end of next week if I don't hear a compelling reason
not to...

Hopefully most modern mail tools can handle MIME digests nowadays.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] META: Moderation and subscription to the tutor list

2016-05-01 Thread Alan Gauld via Tutor
On 01/05/16 07:23, boB Stepp wrote:

> I am in agreement with this as well.  I have often wondered if
> newcomers are subscribed or not

Most are. Several who are not, subscribe very soon
after - presumably in response to the intro message.

>  as after subscription one receives a
> very helpful email which addresses most of the common post formatting
> issues that we seem to endlessly rehash.  Or perhaps I am one of the
> few who actually read it upon subscribing?

Probably most don't read it (all). But many simply are not
technically savvy enough to know how to post in plain text,
or avoid top posting etc. There are foreign concepts to many
of the modern generation of internet users.

> I wonder no matter which way the current matter gets decided, if it
> might be time to rewrite the automated response email.  

I'm open to suggestions on this. It has gradually grown over
the years as new caveats get added. A rewrite is something
that is within our remit and abilities without involving
the list admins.

> mentioned.  It probably should be added.  I feel that the interleaved
> writing style employed by many lists is completely foreign to
> newcomers to programming.

Absolutely. In fact even some programmers have never come
across it because it's not how most web forums (fora?) work.
And business email is now almost universally on Outlook/Exchange
and top posting is the norm.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Issues converting a script to a functioin (or something)

2016-05-01 Thread Alan Gauld via Tutor
On 01/05/16 12:55, Olaoluwa Thomas wrote:

> It computes total pay based on two inputs, no. of hours and hourly rate.

While you do specify two inputs you immediately throw them away
and ask the user to provide the information. In general it is good
practice to separate calculation from input/output operations.
So in your case write the function to take the values provided by the
user and return(not print) the result.

Then when you call the function you pass in the values from the
user and print the function output. This makes the function more
likely to be reusable in other scenarios and easier to debug/test.

def computePay(hours, rate):
   # an exercise for the reader...

hours = float(raw_input ('How many hours do you work?\n'))
rate = float(raw_input ('What is your hourly rate?\n'))
print computPay(hours, rate)

> Something seems to be broken.

You must learn to provide more specific comments.
Define what is broken. Do you get an error message?
If so send it (all of it, not just a summary)
If no error message what output did you get?
What did you expect?

Otherwise we wind up just guessing at what is going on.
(And only a fool would run allegedly faulty code from
  an unknown source! :-)

> Here's the code:
> def computepay(hours, rate):
> hours = float(raw_input ('How many hours do you work?\n'))
> rate = float(raw_input ('What is your hourly rate?\n'))
> if hours > 40:
> gross = ((hours - 40) * (rate * 1.5)) + (40 * rate)
> elif hours >= 0 and hours <= 40:
> gross = hours * rate
> print "Your Gross pay is "+str(round(gross, 4))
> 
> computepay()

In this cae I'll guess it's the fact that you tell Python that
computePay is a function that takes two arguments (hours, rate)
but then call it with no arguments. But you should have got
an error message saying something very like that?
Here is what I get:

>>> def f(x,y): pass
...
>>> f()
Traceback (most recent call last):
  File "", line 1, in 
TypeError: f() missing 2 required positional arguments: 'x' and 'y'
>>>

That's why including the error message helps  so much...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Issues converting a script to a functioin (or something) [SOLVED]

2016-05-01 Thread Alan Gauld via Tutor
On 01/05/16 14:38, Olaoluwa Thomas wrote:

> Thanks for your feedback. Please do not hesitate to provide more as I shall
> email you personally in the future.

Please don't do that.
a) Bob is a busy man who volunteers his time here, but may
   have other things to do too.
b) The list is here so that everyone can benefit from the
   discussions not only the people actively involved.


> The problem was that running the code gave an error which I now do not
> remember in detail as I have moved on after having fixed it.

But the answer is nearly always in the detail. And as you get
more advanced in coding the errors get harder to spot. That's
why it is important to supply us (or any other forum) with
as much detail as you can.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] simple regex question

2016-05-01 Thread Alan Gauld via Tutor
On 01/05/16 17:49, bruce wrote:
> Hi. I have a chunk of text code, which has multiple lines.

>   s='''
>  id='CourseId10795788|ACCT2081|002_005_006' style="font-weight:bold;"
> onclick='ShowSeats(this);return false;' alt="Click for Class Availability"
> title="Click for Class Availability">ACCT2081'''

That looks like HTML. regex won't work reliably on HTML.
You would be better using an HTML parser like BeautifulSoup
or even the standard library's html.parser(Python v3).
That will give more precise and reliable results for only
a little more effort.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] simple regex question

2016-05-01 Thread Alan Gauld via Tutor
On 01/05/16 20:04, bruce wrote:
> Hey all..
>
> Yeah, the sample I'm dealing with is html.. I'm doing some "complex"
> extraction, and i'm modifying the text to make it easier/more robust..
>
> So, in this case, the ability to generate the line is what's needed
> for the test..
>

But as Peter explained HTML has no concept of a "line". Trying to extract a
line from HTML depends totally on how the HTML is formatted by the author
in the original file, but if you read it from a web server it may totally
rearrange the content(while maintaining the HTML), thus breaking your code.
Similarly if it gets sent via an email or some other mechanism.

What you really want will be defined by the tags within which it lives.
And that's what a parser does - finds tags and extracts the content.
A regex can only do that for a very limited set of inputs. and it certainly
can't guarantee a "line" of output. Even if it seems to work today it
could fail completely next week even if the original HTML doesn't change.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos

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


Re: [Tutor] Dictionary Question

2016-05-02 Thread Alan Gauld via Tutor
On 02/05/16 22:55, isaac tetteh wrote:
> 
> For some reason i cant find reply all . But try this 
> for key, value in mydic.items():
>   If A==value:
>Print key

or as a function:

def findKey(dct, val):
   for k,v in dct.items():
  if v == val:
 return k

mydic = {"A: "Apple", "B": "Banana"}

print( findKey(mydic,'Apple') )   # -> 'A'

The problem is that while keys are unique, values
might not be, so what do you do if multiple keys
share the same value?

You could use a comprehension:

def findKeys(dct,val):
keys = [k for k,v in dct.items() if v == val]
return keys

But if you are only interested in one of them then
it's down to you to figure out which!

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] sqlite

2016-05-03 Thread Alan Gauld via Tutor
On 03/05/16 10:09, Crusier wrote:

> I am just wondering if there is any good reference which I can learn how to
> program SQLITE using Python
> 
> I can not find any book is correlated to Sqlite using Python.

You can try my tutorial below.

http://www.alan-g.me.uk/tutor/tutdbms.htm

If you want very similar information in book form then
our book 'Python Projects' contains a chapter on databases,
half of which is SQLite based.

If you want a good book on SQLite itself I can recommend:

Using SQLIte by Kreibich.

hth
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


[Tutor] Digest format changed to MIME

2016-05-05 Thread Alan Gauld via Tutor
As mentioned earlier I've changed the digest format to MIME.
If anyone has problems receiving that please let me know
offline and we'll try to resolve it.

Hopefully this will allow digest users to reply to individual
messages and avoid the frequent resending of entire digests.

It may even fix the subject line and maintain threading,
although I'm less confident on that last one.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] META: Moderation and subscription to the tutor list

2016-05-08 Thread Alan Gauld via Tutor
On 01/05/16 05:18, Steven D'Aprano wrote:

> ...(And I think we should default to 
> individual emails, not daily digest.)

It took me a little while to find this one, but I've checked
and the default is to receive individual emails. You need to
opt-in to get the digests and opt-out to stop getting emails.

This means you can get
- single emails (default)
- emails plus digest
- neither (this is my choice because I read via gmane)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] META: Moderation and subscription to the tutor list

2016-05-08 Thread Alan Gauld via Tutor
On 08/05/16 08:59, Alan Gauld via Tutor wrote:

> This means you can get
> - single emails (default)
> - emails plus digest

- digest and no emails

> - neither (this is my choice because I read via gmane)

Sorry, I missed an option...


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Best Practices with JSON Data

2016-05-08 Thread Alan Gauld via Tutor
On 08/05/16 14:07, Hunter Jozwiak wrote:

> I am intending to start work on a Python program that will allow me to
> better manage my Digital Ocean droplets, due to the fact that the website
> can be at times a bit overkill for some of the basic tasks I want to do. 

OK, but I have absolutely no idea what Digital ocean is, nor
what a droplet is. So we may need more background later.

> have a question in regards to the best practice of manipulating JSON data.
> Would it be better to just parse the data that Digital Ocean returns as a
> result of doing such things as a Get command, or would it be better to
> create a Droplet class with functionality specific to Droplets? 

That really depends on what you plan on doing.
If you need to do a lot of processing of the data or using it
in interaction with other objects/data then a class might make
sense.  But if you just want to collect data into a data store
(file or dbms) or filter out some reports then just reading
the JSON is probably fine.

> am asking is due to the fact that I haven't found any good information on
> the topic, so am not sure of the Pythonic or standard way to do this.

There's probably no information about droplets except on the Digital
Ocean forums (assuming such things exist!). But the general approach
in Python is to do whatever makes most sense. Don't over complicate
things but don't over simplify either. It all depends on what you
need to do.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Practice python

2016-05-08 Thread Alan Gauld via Tutor
On 08/05/16 18:14, monik...@netzero.net wrote:

> Can you please recommend a free web class or site that offers 
> lots of coding  exercises in python,

Have you tried the Python Challenge web site?

> ... intermediate and advanced AND provides solutions. 

The challenge site gets pretty advanced as you progress but
there is usually an easy(ish) and a hard solution and you
don't get shown a "correct" one - because correct doesn't
make any real sense - you just know you got the right
answer when you make it to the next level.

But it certainly helps you grow as a Python programmer
and it especially gets you familiar with the library.

> I need more practice. 

Often the best practice is to do.
Just pick a real project and wade in.

> All the classes I have taken or looked at do not provide 
> enough exercises (with solutions) to retain the info.

I'm always wary of "solutions". They can only ever be the
authors best attempt but there will always be other,
equally legitimate solutions. In my recent book I took
pains to make the point that the "solutions" were only
one possible way of doing it and if a reader did it
another way that was probably fine too.

I know a lot of people like exercises (and solutions)
in books and tats why I provide them, but personally
I've never done them in any programming book I've
read (and that means dozens), instead I solve my
own problems, even ones I've already solved in
other languages...

You will always learn far more from real world problem
solving than from, any artificial exercise/solution.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] How to make object disappear?

2016-05-09 Thread Alan Gauld via Tutor
On 09/05/16 16:55, boB Stepp wrote:

>> class dot:
>> def __init__(self, canvas, color):
>> self.canvas = canvas
>> self.id = canvas.create_oval(15, 15, 30, 30, fill='Blue',
>>  tags='dot1')
>>
>> this = dot(canvas, 'blue')

You create an instance of your class called this.
But you never refer to it again.

>> def ball(n, x, y):
>> canvas.move(n, x, y)
>>
>> def restart():
>> if (canvas.find_overlapping(x, y, x2, y2) == (1, 2)) or
>>(canvas.find_overlapping(x, y, x2, y2) == (1, 3)) or
>>(canvas.find_overlapping(x, y, x2, y2) == (1, 4)) or
>>(canvas.find_overlapping(x, y, x2, y2) == (1, 5)) or
>>(canvas.find_overlapping(x, y, x2, y2) == (1, 6)) == True:
>> canvas.delete('dot1')

Here you delete the shape that your object, this, drew on
the canvas but you do not delete the object. 'this' is
still there.

The normal way to do this kind of thing in a GUI program
is to have the class have a paint/draw method that makes
it visible and a hide/erase  method that makes it invisible
(by drawing itself with the background colour). You probably
need a move() method too. You can then manipulate the "dot"
(although Ball is probably a more suitable name?) by
calling move() draw() and erase() on the object itself.
You might want an isOverlapping() method too, that simply
returns a boolean. That will hide all that horrible if/else
nastiness (or even the dictionary lookup if you adopt
Bob's (excellent) option.

You then wind up with something like

ball.move(x,y)
if ball.isOverlapping(X,Y,X1,Y1):
ball.erase()
else:
ball.draw()

Which is a lot more readable IMHO.

A more indirect solution to your problem would be to use
pyGame to build the game where sprites etc come as standard.
But pyGame itself does not of course come as standard... :-(

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] is there a better way to do this?

2016-05-09 Thread Alan Gauld via Tutor
On 09/05/16 22:03, Ondřej Rusek wrote:

> but for 'tuples in list'... simple:
> 
> data = []
> for record in curs:
>data += [record]

Couldn't that be abbreviated to:

date = list(curs)


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] postgreSQL + psycopg2

2016-05-09 Thread Alan Gauld via Tutor
On 09/05/16 22:14, nitin chandra wrote:

> for line1 in smallLIST1:
> design1 = line1[3]
> print design1
> nextRow=cursor1.execute("SELECT designation_name FROM designation
> WHERE designation_id = %s;", (design1))
> print nextRow
> print ""
> for row in line1:
> print ""+str(row)+""
> print ""
> 
> 1st "print" shows values 1 , correctly.

I assume you mean design1?

> 2nd "print" shows "None".

I don't know postgres API so i'll assume the %s is  the correct
marker. In SQLite we'd use ?...

Also to get the results row by row I'd expect to have
to call fetchone() on the cursor:

query = """
SELECT designation_name
FROM designation
WHERE designation_id = %s;"""

nextrow = cursor1.execute(query, (design1,)).fetchone()

But Postgres DBAPI may be different...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Rate transition from 60hz to 1000hz

2016-05-10 Thread Alan Gauld via Tutor
On 10/05/16 04:08, David Wolfe wrote:

> I'm collecting both video and force plate data, and I need to be able to
> synchronize the two, so I can make some calculations.  The video data is at
> 60hz, and the force plate data is at 1000hz.  I don't want to truncate the
> force plate data.

I have no idea what force plate data is but assuming it's nothing
special you have two sets of data, one at 1000Hz and one at 60Hz.
And you want to join them together at the appropriate points.

The problem is that 60 is not an exact factor of 1000 so you
will need to decide how you align the samples.

> So, how do I perform a rate transition (or interpolation, or whatever) to
> expand the data that is captured at 60hz to be able to synchronize it with
> the data that has been captured at 1000hz?

Interpolation over such a large sample range is tricky and risky.
The simplest way is to assume a straight line between samples.
So each interpolated value is just S2-S1/17 higher than the
previous value(S1).

A better way is to try to determine the current curve shape and apply
that. But it's much harder to do unless you know what kind of data to
expect!

> Also, if I'm not using the correct terms, please let me know.  I'm new to
> Python and programing, and I'm trying to learn as fast as i can.

This has nothing to do with Python or even programming per se.
Its really a math question. The same issues would apply if you
were tabulating the data by hand on paper.

That having been said, there may be some math libraries around
that you could use to do the sums for you. But it's not my area of
expertise so maybe some of the other tutor members will suggest
something in numpy or pandas or whatever.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] postgreSQL + psycopg2

2016-05-10 Thread Alan Gauld via Tutor
On 10/05/16 08:33, nitin chandra wrote:

> here is the result.
> 
> 1
> ('Supervisor',)
> 
> 1
> Vinayak
> Salunke
> 1
> 
> Now I need to remove the braces and quotes .. :)

No you don't. Those are just part of the string representation
that Python uses when printing a string inside a tuple.

If you print nextRow[0] instead of nextRow you
will get the bare string.

BTW Why are you using triple quotes? You only need them if
your string wraps over multiple lines. Single quotes (" or ')
will be fine for your purposes and are easier to type...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] sqlite

2016-05-13 Thread Alan Gauld via Tutor
On 13/05/16 21:25, Neil D. Cerutti wrote:

>  From your tutorial:
> 
> query = '''INSERT INTO Address
> (First,Last,House,Street,District,Town,PostCode,Phone)
> Values ("%s","%s","%s","%s","%s","%s","%s","%s")''' %\
> (first, last, house, street, district, town, code, phone)
> 
> I am not an expert on SQLite, but that doesn't appear to be a wise way 
> to call SQL from Python. Are the double-quotes enough to protect you 
> from malicious data?

No, and if you carry on reading you will find:

--
A Word about Security

While the code above works and demonstrates how to call SQL from Python
it does have one significant flaw. Because I used string formatting to
construct the queries it is possible for a malicious user to enter some
rogue SQL code as input. This rogue code then gets inserted into the
query using the format string and is executed, potentially deleting
vital data. To avoid that, the execute() API call has an extra trick up
its sleeve

-



-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Curses Module

2016-05-16 Thread Alan Gauld via Tutor
On 15/05/16 22:45, Rosen, Brian - 2016 wrote:

>...In my current assignment, I would like to import the curses module
> into either Python 2.7 or Python 3.4. However,
> whenever I attempt to import it, there is an Import Error

Curses is only available in the standard library on Unix-like
operating systems: Solaris, Linux, MacOS etc.

If you use Windows you can get third party versions although I've had
very mixed results using them. I usually prefer to install Cygwin and
use the Python/curses combination for that.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Adding to a dict through a for loop confusion.

2016-05-17 Thread Alan Gauld via Tutor
On 17/05/16 09:28, Chris Kavanagh wrote:

> # Example #1
> cart_items = ['1','2','3','4','5']
> 
> cart = {}
> 
> for item in cart_items:
> cart['item'] = item

'item' is a literal string. It never changes.
So you keep overwriting the dict entry so that
at the end of the loop the dict contains the
last value associated with your literal key 'item'

> #output
> {'item': 5}
> 
> 
> # Example #2
> cart_items = ['1','2','3','4','5']
> 
> cart = {}
> 
> for item in cart_items:
> cart[item] = item

here you use the actual item from your data as both
the key and the value. So you wind up with a dict
containing a key/value pair for each value in your
data list.

> # output
> {'1': '1', '3': '3', '2': '2', '5': '5', '4': '4'}

That's not a very common requirement though, usually
you would have different values from the keys.

Maybe something like:

for item in cart_items:
cart[item] = int(item)

which stores an integer value against the string
representation:

{'1': 1, '3': 3, '2': 2, '5': 5, '4': 4}

Notice also that dicts don't usually print out
in the same order as you created them. In fact
the 'order' can even change over the life of your
program, as you add/remove elements.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Adding to a dict through a for loop confusion.

2016-05-17 Thread Alan Gauld via Tutor
On 17/05/16 23:56, Chris Kavanagh wrote:

> So, by putting quotes around a dict key, like so dict["key"] or in my case
> cart["item"] this makes the dict have ONE key. The loop assigns the
> cart_items to this ONE key until the end of the loop, and I'm left with
> {'item': 5}. . .
> 
> Where as if you do NOT put the key in quotes, dict[key] or cart[item], this
> basically means the dict has as many keys as you're iterating through. In
> other words it assigns the cart_item as a key and a value, and saves them
> all to the dict.
> 
> Is that correct?

Sort of, but not for the reasons you give.
Putting the key in quotes makes it a literal string.
That is, a fixed value, just like 2 or 5.5 or True.
These are literal integer, float and boolean values
respectively.

So you could just as well have done:

for item in cart_items:
cart[2] = item

And everything would be stored under a key of 2.

Or

for item in cart_items:
cart[True] = item

And everything would get stored on a key of True.

The quotes turn the sequence of characters 'i','t','e','m'
into the string value 'item'. The fact that the string is
the same as the variable name in your for loop is completely
coincidental. Python doesn't recognise them as in any way
related.

So in the first case the issue is that you stored your
values in a single unchanging key.

Whereas in the second loop you stored your values against
a key which was a variable that changed in each iteration.

The fact you used quotes is only significant in that quotes
are what you use to create a literal string value. But it
was the fact that it was a fixed value that made everything
appear in the same place (and hence be overwritten), not the
quotes per se.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] genfromtxt and dtype to convert data to correct format

2016-05-17 Thread Alan Gauld via Tutor
On 17/05/16 18:11, Ek Esawi wrote:

> output comes out in the correct format (the desired output as shown below).
> I used converters to covert time and date values, but all came out in
> string format (output below).

What makes you think they are strings? I would expect to see quote signs
if they were strings but there are no quotes...

> CF = lambda date: datetime.strptime(bytes.decode(date),
> %m/%d/%Y).strftime(%Y-%m-%d)  # convert data
> 
> CF1 = lambda time: datetime.strptime(bytes.decode(time),
> %H:%M).strftime(%H:%M:%S)   # convert time

But both of these lambdas return strings (strftime)
You parse the date/time from the bytes then call strftime
on the result which returns a string.

But also you don't have quotes around your format strings
so you should get a syntax error. Please post the actual
code you are using.

> 
> MyFile=New_file
> CRNs={Date: CF,Time:CF1,In:CF1,Dur:CF1,PP:CF1,Pre:CF1}
> data = np.genfromtxt(MyFile,
>names=True,delimiter=,,converters=CRNs,dtype=None)
> 
> Input
> ODateName   TimeInt
> Dur   PP   H  Pred
> 
> 312171   7/1/1995  Old  13:37   1:434:42
> 13:16  162   13:19
> 
> Output
> [ (312171, 1995-07-01, bOld, 13:37:00, 01:43:00, 04:42:00, 13:16:00, 162,
> 13:19:00)
> 
> 
> Desired output
> [ (312171, 1995-07-01, bOld, 13:37:00, 01:43:00, 04:42:00, 13:16:00, 162,
> 13:19:00)

Your desired output looks exactly like the real output so it's
not clear what exactly you want to be different?


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] genfromtxt and dtype to convert data to correct format

2016-05-18 Thread Alan Gauld via Tutor
On 18/05/16 14:14, Ek Esawi wrote:
> OPS! Sorry, I made a mistake on the posting. My output is in a string
> format as shown below. I want the 1st and 8th integers, the 3rd string
> which is OK as, the 2nd date and the rest time. 

You will need to convert the integers manually I suspect
with int(row[0]) and int(row[7]).

For the dates and times, what happens if you simply remove
the strftime() functions from your lambdas?

Things are complicated slightly by your use of genfromtxt since
it's part of numpy and not in the standard library. I have
no idea what it does so there may be tricks you can do with
it.

> [ (b'312171', '1995-07-01', b'Old', '13:37:00', '01:43:00', '04:42:00',
> '13:16:00', b'162', '13:19:00')


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] genfromtxt and dtype to convert data to correct format

2016-05-19 Thread Alan Gauld via Tutor
On 19/05/16 01:31, Ek Esawi wrote:
> Thanks Alan!
> 
> Taking the strtime off did not work either and printed dattime.dattime(very
> long date format). 

But isn't that just the representation of a datetime object (which is
what strptime produces)? In other words it's an object not a string.

Can you show us what you get back?
Or try printing the type() of the object:
eg.
print (type( row[1])
print (type( row[3])

You may be getting confused between the representation of the
object and the actual data. But until we see some actual code
and the actual output it produces it is hard to be sure.

Can you send us a cut 'n paste of an actual python session
so that we can see the parameters to genfromtxt and how
you are producing the output?

For example I'd expect something like:

>>> import datetime as dt
>>> d = dt.datetime.strptime("07/05/2015","%m/%d/%Y")
>>> t = (1,d,'foo')
>>> print(t)
(1, datetime.datetime(2015, 7, 5, 0, 0), 'foo')
>>>

Notice the middle entry is a datetime object, which is,
I think, what you want? You can get just the date (or time)
portion if you want by calling the appropriate method.
You could do that in your lambdas:

>>> CF = lambda datestr: dt.datetime.strptime(datestr,
  '%m/%d/%Y').date()
>>> d2 = CF('11/08/2012')
>>> data = (1,d2,'My string')
>>> print(data)
(1, datetime.date(2012, 11, 8), 'My string')
>>>

hth
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] genfromtxt and dtype to convert data to correct format

2016-05-19 Thread Alan Gauld via Tutor
On 19/05/16 12:51, Ek Esawi wrote:
> Thanks again!
> 
> I tried a combination of the suggestions and still not getting what i want.
> 
> Here are the original code, file, and output.
> 
> CODE
> 
> mport csv; import numpy as np; from datetime import datetime, date, time
> 
> CF = lambda date: datetime.strptime(bytes.decode(date),
> '%m/%d/%Y').strftime('%Y-%m-%d')

Again you have strftime at the end so it will result in a string
output. You need to remove that if you want a date/time/datetime
object as a result.

That's assuming that it is a datetime style object that you want.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] SQLite

2016-05-19 Thread Alan Gauld via Tutor
On 19/05/16 10:03, Crusier wrote:

> c.execute('''CREATE TABLE stocks
>  (code text)''')
> 
> # Insert a row of data
> List = ['1', '2', '3', '4', '5', '6', '7',
> '8', '9', '00010', '00011', '00012']
> 
> c.executemany('INSERT INTO stocks VALUES (?)', List)

Peter has already given you one answer, I'll repeat it in a slightly
different form. Between the two of us you will hopefully
understand... :-)

the SQL statement

INSERT INTO stocks VALUES (?)

Has a placemarker (?) that execute() or executemany()expect
a sequence to fill.  This is more obvious if you had more
than one variable:

INSERT INTO stocks VALUES (?, ?)

Here it would expect a sequence of two values.

But although you only have one value, execute() still
expects a sequence, but one that contains a single value.
You are providing strings which are sequences of 5 characters,
so exec tries to process the 5 characters but has only 1
placemarker so it fails. So you need to pass a sequence
(usually a tuple) of one value like:

('12345',)  # note the comma at the end.

execmany() is exactly the same but expects a sequence of
sequences. So you need your list to contain tuples as above

stock_codes = [('12345',), ('23456',), ...]


HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] FTP file transfer stops, no error given

2016-05-19 Thread Alan Gauld via Tutor
On 19/05/16 15:11, Craig Jackson wrote:

> ftp. In a nutshell the problem is that if the two objectives are
> combined into one Python script, ftp stops uploading in the middle of
> the file, but if the same code is split into two files, web page
> creation in one script and ftp in another, and they are run
> separately, ftp uploads the entire file and it all works. Below are
> the details.

Unfortunately you seem to have sent the variation that works.
We cannot really tell what is going on unless we can see the
code that fails.

There is one possibility based on the code below...

> htmlpage.write(' charset="UTF-8">Peckerwood Garden Docent Notes\n')
> htmlpage.write('')
> htmlpage.write('')
> htmlpage.write('\n')
> htmlpage.write('\n')
> htmlpage.write('\n')
> htmlpage.write('\n')
> htmlpage.write('Unique ID\n')
> htmlpage.write('Location\n')
> htmlpage.write('Name\n')
> htmlpage.write('Family\n')
> htmlpage.write('Common Name\n')
> htmlpage.write('Nativity\n')
> htmlpage.write('Photographs\n')
> htmlpage.write('Description\n')
> htmlpage.write('\n')

Consider using triple quoted strings to save yourself a lot of typing
and to make the html easier to read.

> ...
> htmlpage.write('')
> htmlpage.write('' + description +'\n')
> htmlpage.write('')
> htmlpage.close

Note that there are no parens after close. So you do not execute the
function and the file is not closed.

If you then try to ftp the still open file that could explain the
problems you are having. Whereas if you run this as a separate script
the file will be auto-closed at the end of the script so running the
ftp separately will work..


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] FTP file transfer stops, no error given

2016-05-19 Thread Alan Gauld via Tutor
On 19/05/16 19:01, Craig Jackson wrote:
> Adding the parentheses worked. So sorry for taking your time. I'm new
> to Python and not at all a programmer. Thanks for your help.

No trouble, that's what the list is here for.

Just remember next time to post the code that fails
rather than the code that works, it saves us guessing :-)

And if you do get error messages always post the entire
message, don't summarize it.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Getting started in testing

2016-05-19 Thread Alan Gauld via Tutor
On 19/05/16 20:34, Terry Carroll wrote:
> Is anyone aware of any good tutorials on testing one's Python code?

I'm not a big fan of video tutorials but I recently had to teach
myself Junit testing (and mockito) in Java and I found that
Youtube videos really helped. I know there are similar videos
on Python's unittest (as well as alternatives such as nose).

So a Youtube search might be a good start.
And since most are only 10 minutes or so long you won't
waste much time if you decide they aren't working for you.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] What these Python user-defined functions do?

2016-05-21 Thread Alan Gauld via Tutor
On 21/05/16 02:21, Max Jegers wrote:

> class View:
>   def __init__(self):
>   self.handle = None
> 
>   def order(self, n):
>   return hostviewOrder(handle, self.handle, n)
> 
>   def put(self, fieldName, value, verify=1):
>   if verify == True:
>  verify = 1
>   elif verify == False:
>  verify = 0
>   return hostviewPut(handle, self.handle, fieldName, value,
> verify)


This is a very odd function.
The if/else bit at the top makes no sense at all.

>   def read(self):
>   return hostviewRead(handle, self.handle)
> 
>   def browse(self, filter="", ascending=1):
>   if ascending == True:
>  ascending = 1
>   elif ascending == False:
>  ascending = 0
>   return hostviewBrowse(handle, self.handle, filter, ascending)

Same comment regarding the if/else here.

>   def fetch(self):
>   return hostviewFetch(handle, self.handle)

Other than the if/else issues above the methods are just
wrappers around the hostview library, which we obviously
can't see so can't comment on.

I also notice that self.handle never gets set to anything
other than None, which is odd unless there are other methods
you are not showing us? Also a handle argument is passed to
the hostview functions but its not clear where that is defined...

> Here is a part of the script I am trying to understand:
> 
> def ExportShipment():
>  f = open("c:\\" + me.get("SHN") + ".txt", "w")
>  h = View("Header", *1*)
>  d = View("Details", *1*)
>  h.*order*(1) # SHN
>  h.*put*("SHN", me.get("SHN"), 1)
>  h.*read*()
>  f.write("H," + h.get("LOCATION") + "," + h.get("ADDR1") + "\n")

I'm not sure where all the * characters are coming from,
I assume they are not part of the code?
But the code above opens a file and creates two View objects, one for
the header and one for the details. However the View init() function
above does not have any paramaters so this should fail. Also there is
reference to a get() method which is not part of the class definition
above. And there is reference to a me object but its not defined above
either.


>  d.*browse*("SHIUNIQ=" + "{:.0f}".format(h.get("SHIUNIQ")), 1)
>  while (d.*fetch*() == 0):
>  f.write("D," + d.get("ITEM") + "," +
> "{:.0f}".format(d.get("QTYSHIPPED")) + "\n")
>  f.close()

Again this code does not match the code above. There is no View.get()
method. And View.browse() does not change the View's state so its hard
to see what the get() method could return. It could only work if there
were either a lot of global variables being used in the background(by
listview) or if thee is a lot more to the View definition than we have seen.

> I understand what file operations do. However I can’t get what these
> functions do:
> 
> *order(), put(), read(), browse(), fetch()*.

They are trivial wrappers around the listviewXXX functions
that are presumably defined in another library somewhere.
But the code is generally inconsistent and definitely
not good Python on any level.

> Function definitions in the library are of little help for now, as all
> functions feature handle and self.handle in their returns; however I cannot
> find out what handle and self.handle may mean in this context.

> Please let me know if I should provide more info for my question to make
> sense.

Apart from the issue over handle its not clear what you don't
understand. However until you get the two code segments
harmonised you will never make sense of it. The code as it
stands is inconsistent and could never work.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Python 3: string to decimal conversion

2016-05-22 Thread Alan Gauld via Tutor
On 22/05/16 14:19, US wrote:

>>with open(file) as csvfile:
>>records = csv.reader(csvfile, quoting=csv.QUOTE_NONE)
> [...]
>>for row in records:
> [...]
>>try:
>>expenses[ts.Date(row[0]).month] +=
> decimal.Decimal(row[4])
>>except ValueError:
>>pass

> I think the problem may be caused by an empty string value that is
> passed to decimal.Decimal function. The csv file contains some empty
> cells and I wanted the code to ignore them. That's why I had the
> ValueError exception.

If you know you are going to get some invalid data in your loop you
should test for it before the operation and use 'continue' to force the
loop to start the next iteration.  You could still catch the invalid
operation  error, just in case... Although, if you don't expect it and
don't know how to handle it then it's probably better to let Python just
do  its thing and give you the traceback.

Like this:

  with open(file) as csvfile:
 records = csv.reader(csvfile, quoting=csv.QUOTE_NONE)
   #...
   for row in records:
 if not row[4]:
 continue# coz its empty
 else:
 expenses[ts.Date(row[0]).month] += decimal.Decimal(row[4])

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Python 3: string to decimal conversion

2016-05-23 Thread Alan Gauld via Tutor
On 23/05/16 02:45, US wrote:

> I tried the float() function instead of decimal.Decimal and got an
> error message: could not convert string to float: '($75.59)'.

The problem is that the functions don;t recognize the parens as a
negative sign. You will need to convert them yourself. I suggest you
write a function that takes a string and if it starts with parens then
strip them off and prepend a negative sign, otherwise return the
original. You will also need to get rid of the $ sign...
Something like:

def normalizeValue(val):
if amt.startswith('(') and amt.endswith(')'):
   amt = '-' + amt[1:-1]
return amt.replace('$','')

Then call that when you try to convert to Decimal


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] which is best python 2 or python3

2016-05-23 Thread Alan Gauld via Tutor
On 23/05/16 08:54, Palanikumar Gopalakrishnan wrote:
> Hi buddies,
> I read one article on internet which is said python 2
> and python3 is totally different in programming.
> As a beginner which i prefer for my learning,  python 2 or python3 ?

Nowadays the only real justifications for a learner using Python2
are: 1) It's all they can access on their computer or 2) they know
they need a library that is only available on 2.

Otherwise it makes more sense to learn Python 3

Just make sure the tutorial you follow is also Python 3!

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] I've subscribed to your service, no confirmation yet. I'm looking for a tutor and I need help with some code.

2016-05-24 Thread Alan Gauld via Tutor
Re your subject...
This is a mailing list. You subscribe and you should receive
mails sent to the list.
If you have a question send it to the list (like you did here)
and one or more of the list members will hopefully respond.
The more specific your question the more precise will be the response.
Try to include OS, Python version, any error messages(in full)

Now to your message...

On 24/05/16 18:06, Angelia Spencer via Tutor wrote:
>  I'm trying to telnet to my box. 

What is your "box"? A server somewhere? Running what OS?
Where are you telnetting from?

> When I do this in DOS it's simple, I even have a blinking cursor 
> for me to type in commands for each response.

I assume you mean you telnet from a Windows PC and login to your server
and get an OS command prompt? (Possibly running bash?)

> Not so for python. 

What does this mean? If you run the python command on your DOS
console you should get a prompt like

>>>

at which you can type in commands.

If python is installed on your "box" then telnet to the box
and at the OS prompt type python.

If that doesn't work for you, you will need to give us a lot more
information about how you installed Python, which version, how
you are trying to run python etc.

> I have a dictionary "user_acct" which has the username
> and password in it. 

> My box is interactive, I must be able to type in commands 

Again we have no idea what your "box" is. What do you mean
its interactive, nearly all computers are to some extent?

> and I don't know how to do this in python.

While python does have an interactive mode (the >>> prompt) it's not
normally used that way. Usually you put your code in a script file
(ending .py) and run it from an OS prompt (or file manager) like

C:\WINDOWS> python myscript.py

> 1st prompt = Username:2nd prompt = Password:
> 
> After this my box's output looks like this:Last Login Date  : May 24 2016 
> 09:42:08
> Last Login Type  : IP Session(CLI)
> Login Failures   : 0 (Since Last Login)
>  : 0 (Total for Account)
> TA5000>then I type en and get
> TA5000# then I type conf t and getTA5000(config)#

OK, I'm guessing that's a Unix like system but I'm not sure.

> My code is below:

How are you trying to run this?
Where is it stored?
Where is python installed?

> import getpass
> import sys
> import telnetlib

username = input()

> password = input()
> tid = 'TA5000'
> first_prompt = '>' # type 'en' at this prompt
> second_prompt = '#' # type 'conf t' at this prompt
> third_prompt = '(config)'
> prompt1 = tid + first_prompt
> prompt2 = tid + second_prompt
> prompt3 = tid + third_prompt + second_prompt
> user_acct = 
> {'ADMIN':'PASSWORD','ADTRAN':'BOSCO','READONLY':'PASSWORD','READWRITE':'PASSWORD','TEST':'PASSWORD','guest':'PASSWORD','':'PASSWORD'}
> host = "10.51.18.88"
> #username = "ADMIN" + newline
> #password = "PASSWORD" + newline
> tn = telnetlib.Telnet(host,"23")
> open()

That calls the builtin open() function without arguments which should
cause an error. Do you get an error message?

You probably wanted

tn.open()

> tn.read_until("Username: ")
> tn.write(username)
> tn.read_until("Password: ")
> tn.write(password)


if username in user_acct and password == user_acct[username]:
>  print(prompt1 + "Enter en at this prompt" +"\n")
>  print(prompt2 + "Enter conf t at this prompt" + "\n")
>  print(prompt3 + "\n")
> else:
>  
>  print('Invalid Login... Please Try Again')close()

Shouldn't you check the login details before passing it
to the telnet host?

Also note you are not storing anything you get from the
host so you are just checking your own local data.

I don't really know what this is supposed to be doing.


I'd suggest starting slow. Create a script that simply
logs in with a hard coded name/password and then prints
a succcess/fail message and logs out again.

Once you know you can connect and login then you can start
to think about extra features.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Learning Regular Expressions

2016-05-24 Thread Alan Gauld via Tutor
On 23/05/16 23:08, Terry--gmail wrote:

> scripted worked great without the notes!  I'd like to know what it is in 
> the below Tripple-Quoted section that is causing me this problem...if 
> anyone recognizes. In IDLE's script file..._it's all colored green_, 
> which I thought meant Python was going to ignore everything between the 
> tripple-quotes! 

Its all green forv me too and it runs perfectly - as in it does
absolutly nothing.


And if I add print('hello world') at the end it prionts ok too.

I even tried assigning your docsstring to a variable and printing
that and it too worked.

Linux Mint 17
Python 3.4.3
IDLE 3

So I don't think this is your entire problem. Maybe you should
show us some code that actually causes the error?

> But if I run just the below portion of the script in 
> it's own file, I get the same While Scanning Tripple-Quotes error.

As above, it runs silently for me.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


[Tutor] Fwd: Re: I've subscribed to your service, no confirmation yet. I'm looking for a tutor and I need help with some code.

2016-05-24 Thread Alan Gauld via Tutor
Forwarding to list...



 Forwarded Message 

The box is my controller with and IP address, I'm doing all this from my
windows 7 PC. 
As I said I can type telnet 10.35.56.90 in the dos cmd prompt and get to
my controller. I wrote a python script with the user_acct dictionary.

I do get the >>> in the python IDLE but within my python script/file can
I telnet to my controller? Keep in mind when I do log into my controller
it's command line driven.

I have python 2.7 and 3.5 installed on my windows 7 pc.

So you're saying open the python IDLE and import the telnet lib and just
type; telnet 10.45.34.80 and I'll be able to get to my controller???

Thank you for helping me :)
 
...you cannot direct the wind but you can adjust your sails...
 
 
*Angelia Spencer (Angie)*


--------
*From:* Alan Gauld via Tutor 
*To:* tutor@python.org
*Sent:* Tuesday, May 24, 2016 2:38 PM
*Subject:* Re: [Tutor] I've subscribed to your service, no confirmation
yet. I'm looking for a tutor and I need help with some code.

Re your subject...
This is a mailing list. You subscribe and you should receive
mails sent to the list.
If you have a question send it to the list (like you did here)
and one or more of the list members will hopefully respond.
The more specific your question the more precise will be the response.
Try to include OS, Python version, any error messages(in full)

Now to your message...

On 24/05/16 18:06, Angelia Spencer via Tutor wrote:
>  I'm trying to telnet to my box.

What is your "box"? A server somewhere? Running what OS?
Where are you telnetting from?

> When I do this in DOS it's simple, I even have a blinking cursor
> for me to type in commands for each response.

I assume you mean you telnet from a Windows PC and login to your server
and get an OS command prompt? (Possibly running bash?)

> Not so for python.

What does this mean? If you run the python command on your DOS
console you should get a prompt like

>>>

at which you can type in commands.

If python is installed on your "box" then telnet to the box
and at the OS prompt type python.

If that doesn't work for you, you will need to give us a lot more
information about how you installed Python, which version, how
you are trying to run python etc.

> I have a dictionary "user_acct" which has the username
> and password in it.

> My box is interactive, I must be able to type in commands

Again we have no idea what your "box" is. What do you mean
its interactive, nearly all computers are to some extent?

> and I don't know how to do this in python.

While python does have an interactive mode (the >>> prompt) it's not
normally used that way. Usually you put your code in a script file
(ending .py) and run it from an OS prompt (or file manager) like

C:\WINDOWS> python myscript.py

> 1st prompt = Username:2nd prompt = Password:
>
> After this my box's output looks like this:Last Login Date  : May
24 2016 09:42:08
> Last Login Type  : IP Session(CLI)
> Login Failures  : 0 (Since Last Login)
>  : 0 (Total for Account)
> TA5000>then I type en and get
> TA5000# then I type conf t and getTA5000(config)#

OK, I'm guessing that's a Unix like system but I'm not sure.

> My code is below:

How are you trying to run this?
Where is it stored?
Where is python installed?

> import getpass
> import sys
> import telnetlib

username = input()

> password = input()
> tid = 'TA5000'
> first_prompt = '>' # type 'en' at this prompt
> second_prompt = '#' # type 'conf t' at this prompt
> third_prompt = '(config)'
> prompt1 = tid + first_prompt
> prompt2 = tid + second_prompt
> prompt3 = tid + third_prompt + second_prompt
> user_acct =
{'ADMIN':'PASSWORD','ADTRAN':'BOSCO','READONLY':'PASSWORD','READWRITE':'PASSWORD','TEST':'PASSWORD','guest':'PASSWORD','':'PASSWORD'}
> host = "10.51.18.88"
> #username = "ADMIN" + newline
> #password = "PASSWORD" + newline
> tn = telnetlib.Telnet(host,"23")
> open()

That calls the builtin open() function without arguments which should
cause an error. Do you get an error message?

You probably wanted

tn.open()

> tn.read_until("Username: ")
> tn.write(username)
> tn.read_until("Password: ")
> tn.write(password)


if username in user_acct and password == user_acct[username]:
>  print(prompt1 + "Enter en at this prompt" +"\n")
>  print(prompt2 + "Enter conf t at this prompt" + &qu

[Tutor] Fwd: Re: I've subscribed to your service, no confirmation yet. I'm looking for a tutor and I need help with some code.

2016-05-24 Thread Alan Gauld via Tutor
Forwarding to the list.
Please use reply-all to respond to list messages.

Also please use plain text as HTML messages often result in
code listings being corrupted, especially the spacing, which
is very important in Python.


 Forwarded Message 

> I just opened the python IDLE 3.5 on my MAC and I imported telnet.lib.
> On the next line I typed telnet 192.09.168.55 and I got an error. It said
> invalid syntax. I'm trying to telnet to my other MAC here at home, just
> to see if I can connect.

You cannot just type telnet commands into Python you need to use
the telnet API. (Type help(telnetlib) at the >>> prompt or visit the
modules documentation page)

A typical session might look something like:

>>> import telnetlib
>>> tn = telnetlib.Telnet('myhost.com')
>>> response = tn.read()
>>> print(response)
. some stuff here 
>>> tn.close()

That's assuming you have telnet access to myhost.com of course, many sites
don't allow it because of the security issues associated with telnet.
ssh is
probably a better bet.

But in either case don't expect a telnet interactive session - that's
what the
telnet command (or ssh) is for. Python gives you the ability to automate a
session, with no human interactivity required. If you want to interact
you'll
need to read the output and check for prompts from the host then relay
those prompts to your user from Python.
 

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Fwd: Re: I've subscribed to your service, no confirmation yet. I'm looking for a tutor and I need help with some code.

2016-05-25 Thread Alan Gauld via Tutor

> I do get the >>> in the python IDLE but within my python script/file can
> I telnet to my controller? Keep in mind when I do log into my controller
> it's command line driven.

One thing that occurred to me is that you may be better off using the
subprocess module to start an interactive telnet process. It's less easy
to control the session programmatically than with telnetlib
but it would give you the interactive element you seem to want.

It just depends on what you are trying to achieve...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Fwd: Re: I've subscribed to your service, no confirmation yet. I'm looking for a tutor and I need help with some code.

2016-05-25 Thread Alan Gauld via Tutor
On 25/05/16 14:11, Angelia Spencer wrote:
> in your code below you're telnet-ing to a website,

No, I'm telnetting to a server with the IP address mysite.com
(which is obviously fictitious, but could be any valid IP address).
There is nothing that says it's a web site. (And even some web
sites might allow telnet access, that's just an admin thing)

> I am not and when I type, >>> response = tn.read(). I get an error.
>
> >>> response=tn.read()
> Traceback (most recent call last):
>   File "", line 1, in 
> AttributeError: Telnet instance has no attribute 'read'
> >>>

Sorry, I misremembered the method name.
Here is an actual session using a public telnet site:

>>> import telnetlib
>>> tn = telnetlib.Telnet('telehack.com')
>>> response = tn.read_some()
>>>b'\r\nConnected to TELEH'
b'\r\nConnected to TELEH'
>>> tn.close()
>>>


There are a bunch of other read_() methods, you
need to read the help page to find out how they differ.
-- Alan G Author of the Learn to Program web site
http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow
my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Baffling problem with a list of objects sharing a property

2016-05-25 Thread Alan Gauld via Tutor
On 25/05/16 17:05, Alex Hall wrote:

> Python for a while so eventually unsubscribed.

Welcome back Alex :-)

> Now I'm using Python for work, and have run into a problem that has me
> baffled. It's as though a bunch of class instances in a list are sharing a
> single property. 

They are. You've stiumbled on one of those Python peculiarities of
implementation that can be useful and annoying in equal measure.

> class Test(object):
>  def __init__(self, name, paths=[]):
>   self.name = name
>   self.paths = paths

When you give a function/method a default value that same object is used
for *every* invocation of the method where the default applies.
So that list you create is shared and if any instance adds anything
to it, it will appear in every other instance too! So unless you
want that behaviour its usually better to make default values
immutable or None, then in the code assign the actual value,
like:

def foo(v = None):
if not v: v = []  # or whatever mutable value you need.

HTH

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Fwd: Re: I've subscribed to your service, no confirmation yet. I'm looking for a tutor and I need help with some code.

2016-05-25 Thread Alan Gauld via Tutor
On 25/05/16 17:19, Alan Gauld via Tutor wrote:

> Here is an actual session using a public telnet site:
> 
>>>> import telnetlib
>>>> tn = telnetlib.Telnet('telehack.com')
>>>> response = tn.read_some()
>>>> b'\r\nConnected to TELEH'

Oops! a cut n paste error. That line should be:

>>> print(response[:20])
b'\r\nConnected to TELEH'


>>>> tn.close()


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Logging exceptions, but getting stderr output instead

2016-05-25 Thread Alan Gauld via Tutor
On 25/05/16 19:11, Alex Hall wrote:

> As a quick aside, is there an easy way to halt script execution for some
> exceptions? Right now, catching them means that execution continues, but I
> sometimes want to log the problem and then abort the script, as the error
> means it shouldn't continue. Thanks.

I'm not sure what the issue is here.
Can't you just exit in the normal fashion using

sys.exit()
or
raise SystemExit?

I feel I must be missing something?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Newcomer with organizational questions

2016-05-26 Thread Alan Gauld via Tutor
On 26/05/16 23:34, Max Jegers wrote:

> that I wrote a reply with a thank you and a follow-up question, only to
> discover that I don’t see a way to send it.

A mailing list works by email, so you reply as you would to any email.
If you use Reply it goes to the person who sent the email.
If you use Reply All it goes to everyone who received the original
email, including the sender. In the case of a list it also includes the
list(and everyone on it.)

So the simplest solution is to always use Reply All (or if
you have the option, Reply List) and it will go to the list.

> I reread *tutor-**bounces* auto-response, then did some googling and
> realized that I may need to subscribe. So I did on Sunday May 22, and the
> webpage said: “*Your subscription request has been received, and will soon
> be acted upon. Depending on the configuration of this mailing list, your
> subscription request may have to be first confirmed by you via email, or
> approved by the list moderator. If confirmation is required, you will soon
> get a confirmation email which contains further instructions.*”
> 
> Main question: Should I wait more or I am missing something I need to do at
> my end?

Nope, you are now subscribed.
However the default behaviour is to put new subscribers on a moderation
mode whereby all your early posts get caught in a queue and have to be
manually approved by a moderator. There are 3 of us but usually its me
:-) So I approved your post, it appeared on the list and I am now
replying to it.

> My purpose is to post a reply in a particular subject I initiated.

Find the mail and reply to it using Reply All.

A couple of important extra requirements
- Set your email to be plain text not HTML because HTML tends
  to mess the formatting which is critical for Python code.
  (You might be able to configure your mail tool to always
   use plain text for python.org posts.)
- Always include the code that's causing the problem
- Always include the full text of any errors you get
- Tell us your OS and Python version


> Please note that I did not receive anything from a tutor in my email other
> than *tutor-bounces* auto-response. I use Gmail.

That's just the server automated response.
Hopefully you receive this :-)

> -   -   May I attach a file to a message? Some Python libraries are
> quite big (50 pages in my case), however it may be not difficult for an
> expert to answer a question if he/she has a full library. At the same time,
> it seems inconsiderate and impractical to paste 50 pages into a message.

50 pages (how big is a page?)... probably too much.
Try to condense it by removing irrelevant bits.
My rule of thumb is up to 100 lines can goi in the message, bigger than
that [put it on a public pastebin and send a link.

Attachments are a bad idea because they often (but not always)
get stripped out for security reasons by the server.

> -   -   Can I paste not in plain text – using fonts etc?

No, see above. HTML loses spaces etc and destroys formatting

You can use plain text mark ups such as _underline_ or *bold*

> -   -   May I ask a follow-up question in the same thread, or should I
> start a new one?

If its a new topic start a new thread.
If its a follow up on the same topic keep it in the same thread

> -   -   Is this ok to post a message that contains thank you only, or
> these messages have to be deleted by moderators (like on stackoverflow.com?)

It's not necessary every time but I certainly don't delete them
and if the response took a lot of work, maybe by multiple
contributors its good to let us know when you finally solve
the problem.

> I believe first I was able to see a tutor’s response on external website:
> https://code.activestate.com/lists/python-tutor/107992/  - and much later
> on mail.python.org. Is this persistent behaviour?

The list archives are available in several places including
python.org and activestate.com.

You can also receive (and reply to) list messages using usenet(NNTP) via
gmane. (Thats actually how I read the list.) They also provide
an archive of old posts.

Feel free to ask any more questions about the list or about Python
or programming in general.

-- 
Alan G
Python tutor list moderator

Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Correct use of model-view-controller design pattern

2016-05-29 Thread Alan Gauld via Tutor
On 29/05/16 05:33, boB Stepp wrote:
> I am currently mulling over some information Alan passed along a while
> back on using the model-view-controller design pattern (Would
> 'architectural pattern' be a better choice of phrase?).  

Either is appropriate. Design Pattern is more usual, largely because
it ws one of the first OOP patterns to be formally documented (in
the SmalltTalk world) and is included in the original Design
Patterns book by the GoF.

> My current understanding is that the model contains program logic and
> the data which the program logic manipulates.  

Correct, all the core entities which make up the program are represented
by models. Most things stored in a database will
have a corresponding model.

> The view is just the interface with which the user interacts.  

Specifically the visible part of the interface. the "presentation layer".

> The controller ties things together, refreshing the view appropriately, 
> receiving messages from the view when something there has
> been changed by the user, interrogating the model when needed,
> and receiving the model's results and refreshing the view
> appropriately.

The controller is where the confusion starts. Every implementation of
the MVC pattern seems to change the way the controller is defined. You
are broadly correct but some frameworks have a more view focussed
interpretation, others more model focused. For example some GUI
frameworks combine the view and controller concepts into a single Window
object (the Delphi/VB/MFC/OWL Windows GUI frameworks all
take that approach). The JSP type 1 framework is similar in that
the JSP page does both roles. But in the JSP type 2 framework the
controller is separated out into a distinct entity.

What everybody(?!) seems to agree on is that events generated by the
view are forwarded to a controller(*) which determines whether a model
needs to be involved and is so what method of which model needs to
be invoked.

(*)If the controller is embedded in the view object then that is
probably handled by an internal  superclass method of the framework
and based on an event table (similar to Tkinter's binding mechanism)

The model responds, but how the view is notified varies. In some cases
the views register with models and the model automatically sends
notification messages to all registered views (by-passing the
controller). In other cases the model si8mply sends a reply to the
controller that invoked it and the controller decides which views should
be updated.

Thee is a modern twist on the whole thing too, where a View-Model is
introduced. This is a model object that represents an aggregated view of
lower level models and is closely aligned to the fields on a view.
(Think of it being like a view table in a SQL database, an aggregation
of multiple tables via a SELECT statement) In this case the controller
may simply update the view-model and the view model will notify its
associated view(s) directly. This is most commonly seen in the
Web/Javascript world where the browser holds a View-Model in memory
which is updated based on JSON queries back to the server which
hosts the real models. This architecture allows rich web clients
to do things like sorting or filtering the data without going back
to the server.

Another common use of a view-model is for collections. You may have many
foo objects (each one a model in its own right) but a list
view of them only wants a single model to work with so you create a
view-model representing the collection of foo. Each foo is persisted
in the database but the collection is a more abstract entity being in
effect the table as a whole.

> In my simple code to follow, I have the contents of three files, which
> I have named model.py, controller.py and view.py.  controller.py
> starts program execution.  My intent is to keep each of the three as
> independent of the others as I can manage, so that ideally, I could
> modify one of them and not need (or minimally need) to modify the
> other files.  

In practice it's hard to separate the controller and view
entirely (which is why some frameworks combine them) but
it should definitely be possible to separate the models
from the more UI elements. What the controller does do
is allow you to swap different views within a single UI.
For example a list view, versus a form view versus a
graphical view, all of the same object or set of objects.

> controller.py:

> def main():
> '''Start and run the program.'''
> 
> option_num = view.main_menu()
> while True:
> if option_num == '1':
> diameter = float(view.diameter_prompt())
> circumf = model.circumference(diameter)
> view.display_circumference(str(diameter), str(circumf))
> option_num = view.main_menu()
> 
> elif option_num == '2':
> view.display_exit_msg()
> sys.exit()
> 
> else:
> title = 'WARNING!\n'
> msg = ('That is not a valid option number.\nP

Re: [Tutor] Correct use of model-view-controller design pattern

2016-05-30 Thread Alan Gauld via Tutor
On 29/05/16 05:33, boB Stepp wrote:

As promised I'm back so will try to answer these...

> Some other questions:
> 
> 1)  If I were to add code to filter user inputs, which file is the
> logical place to place such code?  My current impression is that it
> should go in the controller, but I could see it being in the view.
> However, if I were to write a Validation class, I could see that as
> having uses beyond checking just user input.

Filtering user input is one type of validation (others include
type and value checking) Usually the view (especially in a GUI)
will control the type checking and in  some cases the value
checking too (think calendar pickers). But the controller may
also do some data adjustment (such as reformatting a date
to suit a particular model). But mostly I expect the view
to collect the correct data in terms of primitive type/value.

An example where more complex validation might be required is
where you want to validate a credit card or an account number.
In that case the controller may call a business service before
passing the validated details onto the appropriate model(s)
to process.

Models should usually expect to be given good data. In some
cases you might want to do a belt n' braces data check in
the model too, but mostly you assume your front end is
catching the bad stuff (see file processing below).

> 2)  Currently I am using a while loop in the controller to keep the
> view 'alive'.  If I were to convert the view to a tkinter GUI, where
> would the root.mainloop() statement go?  In the controller's main()
> method?  What GUI-related stumbling blocks might I easily run into in
> going from CLI to GUI with this existing code?

See previous post. The main loop is almost always in the view.

> 3)  If I were to add data files in place of (or in addition to) user
> input, in which aspect of MVC would file I/O be handled?

This is where things get interesting. When processing files the
view/controller are only likely to be validating the filename and
initiating the process. This means that there needs to be a model object
somewhere that processes the file. But the content of the
file is unsafe  so that model needs to do all the data
validation that would normally be done in the view/controller.

Its not unusual to have a dedicated model for such batch processing
and it will then call the other model methods for each record processed,
effectively becoming a controller of sorts. There may
be opportunities for code reuse between the UI controller and
the batch controller.

> BTW, I did not attempt to write any classes as things seemed simple
> enough that functions seemed more appropriate and straightforward to
> me.  If that is a bad choice, please let me know!

At this level of simplicity its hard to see the advantages of the MVC
paradigm. (A bit like OOP itself!) Its only when things start to get
complicated that MVC starts to simplify things rather than add noise.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Learning Regular Expressions

2016-05-30 Thread Alan Gauld via Tutor
On 30/05/16 18:21, dirkjso...@gmail.com wrote:

> I moved my notes that contained any '\'s to a different python file.
> However, if we run it, we get the error I was having. Here's the
> script:

Runs fine for me.

Can you run it using the python command line interpreter rather
than IDLE? Do you still get errors? If so cut n paste the full
error to the list.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Study Tips

2016-05-30 Thread Alan Gauld via Tutor
On 30/05/16 06:45, Steve Lett wrote:

> Out of a long list of books that I have collected ( python, Blender, etc )
> I have decided to start on Introducing Python (hard copy 2nd Ed, ebook 3rd
> ed) by Bill Lubanovic. Before that I was going to start with Python
> Programming for the Absolute Beginner, Michael Dawson.

Bob has mentioned many useful bits of advice.

I'd just emphasise one thing:

write code., lots of it.

Don't just settle for the examples/exercises in your book.
Use them as a start but extend them. Add extra features.
Change the output format or the sort order.
Combine examples to make bigger programs.

Writing code means making mistakes and, in finding the solution,
you learn far more than from just reading code.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Correct use of model-view-controller design pattern

2016-05-31 Thread Alan Gauld via Tutor
On 31/05/16 02:25, boB Stepp wrote:

> This "views register with models" and "registered views" terminology
> is unfamiliar to me.  Googling suggests registered views is referring
> to a dynamically generated presentation, perhaps in the sense of a db

No, this is different.
Try googling publish-subscribe instead.

The pattern is that something has data to publish (the model)
and other things want to know about when the data changes
(the associated view(s)). So when a view is created it knows which
model(s) it wants updates from and registers with them. (The model
has a register() method that adds the new view to a list of subscribers.)

When something changes on the model it calls its publish() method
which simply traverses the subscriber list and sends an update() message
to each (usually with itself as the argument).

The view can then interrogate the model to see if any of the
data changes affect its display and, if so, make the
corresponding updates on the UI.

When a view is deleted it unregisters from the model.

In summary:

- A view constructor must have a model parameter
  and register with the model.
- A view must implement an update() method
- A view destructor must unregister itself from the model

- A Model must have a register() method
- A Model must have an unregister() method
- A model must have a publish() method

This mechanism is most commonly used where the view/controller
are combined into a single implementation entity.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Correct use of model-view-controller design pattern

2016-05-31 Thread Alan Gauld via Tutor
On 31/05/16 02:16, boB Stepp wrote:

> I perhaps see a general principle developing here:  Before passing
> data elsewhere, the data should be validated and in a form suitable
> for where it is being sent.  

Correct.

> By "business service" are you intending this to mean a totally
> different application, or just a different model within the same
> overall program?

Either. It could even be a web service provided by a different
organisation altogether. This is quite common for credit checks
and the like. (Although a credit check would almost certainly
be done by a model rather than a controller... That falls into
business logic territory not presentation.)

> I take it "braces" are what we call "suspenders" in the US?  

I believe so. Suspenders in the UK are used to hold up your socks :-)

> you are talking about is redundant validation?  When would this be
> actually called for as it seems to contradict DRY principles?  

Correct. The file handling example is a case where it might be valid
since the model may use the same method to process a line from a file as
a record from the UI. However some OOP practitioners like to build some
validation into models anyway because models are often reusable in non
UI context - eg batch processing jobs - where there is no front end
validation.

Another case is where an organisation publishes its model API behind a
web service. Can you trust your web clients to validate? Maybe not. So
you either validate in the web service code or in the model.

Yet another case is where you handle mission critical shared data. If
you are writing that data into a central database shared with multiple
applications you need to be sure you don't corrupt it so you may add
some validation, just in case...

> only thing that is coming to my mind now is code for something where
> failure is not an option and the source of the incoming data (Which
> should be doing proper validation.) was coded by someone else.  If I
> were coding both myself, then I would think that I should be able to
> trust that I did the job correctly the first time!

Absolutely right.

> I guess what I am getting out of this discussion of MVC, is to not be
> too rigid in my thinking, but try to decouple these three broad areas
> of responsibility as much as is practical, so as to make the resulting
> code more maintainable and scalable.  Is this the correct big picture
> idea?

Yes, although for any given implementation you should decide the
responsibilities and stick to them. I'm currently doing a lot of Java
coding and the Java Swing UI framework has a very specific and rigid
take on MVC and you have to use that definition of the UI simply won't
work! So the framework you choose will often determine how you use MVC.
But in the bigger picture it is a set of principles.

MVC is one specific version of the more general programming rule to
separate presentation from business logic.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Help with 'if' statement and the concept of None

2016-05-31 Thread Alan Gauld via Tutor
On 31/05/16 16:16, marat murad via Tutor wrote:

> program  whose code I have pasted below. The author introduced a new way of
> coding the Boolean NOT operator with the 'if' statement I have highlighted
> the relevant area,apparently this if statement actually means if money !=
> 0,which I understood,

Boolean values are either true or false.
Other values are given boolean equivalent values by Python.
eg. For strings an empty string is False, anything else is True.
For numbers 0 is False anything else is True.

So in your example:

> *if money:*
> print("Ah I think I can make something work")
> else:
> print("Please sit ,it may be a while")
>

The first 'if' test is saying

'if money is equivalent to True' (anything other than zero)

In effect that's the same as you said (it's like testing for != 0)
but the important difference is that it is relying
on the boolean *equivalence* of an integer value.
The same is true in your second example:

> idea of slicing also has a if statement similar to the first one,except the
> second one accepts  0 value but the first one doesn't.
> 

> start=input("\nStart: ")
> 
>* if start:*
> start=int(start)

Again this is really saying if start is True and for a string
(which is what input() returns), as I said above, True means
not empty. So the string '0' is not empty and therefore True.
It's not the value of the character that matters it's the fact
that there is a character there at all.

All objects in Python have these boolean equivalent values,
for example an empty list, tuple,set or dictionary is also
considered False. As is the special value None.

> I hope i made sense.

Yes, although your subject also mentions the concept of None?
Did you have another question about that?

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Python OLS help

2016-05-31 Thread Alan Gauld via Tutor
On 31/05/16 16:30, Vadim Katsemba wrote:
> Hello there, I am having trouble running the Ordinary Least Squares (OLS)
> regression on Spyder. 

I had no idea what Spyder was but a Google search says its an IDE
somewhat akin to matlab or IPython... It also has a discussion group:

http://groups.google.com/group/spyderlib

You may find someone on this list who knows it but you will likely
get a better response on the spyder forum. This list is really
for core python language questions and although we try to be
helpful on other matters a dedicated forum is usually better.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Study Tips

2016-06-01 Thread Alan Gauld via Tutor
On 01/06/16 20:06, Anindya Mookerjea wrote:
> Hi experts,
> 
> I am going to start learning Python and have got no coding
> experience/knowledge whatsoever . So Python would be my first programming
> language

Start with one of the tutorials on the non-programmers page of python.org

http://wiki.python.org/moin/BeginnersGuide/NonProgrammers

If you are comfortable with IT things in general (editing files,
navigating directories etc) then you could try mine(see below)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] OrderedDict?

2016-06-01 Thread Alan Gauld via Tutor
On 01/06/16 16:36, Alex Hall wrote:

> I'm trying to find the OrderedDict documentation. I found one page, but it
> wasn't very clear on how to actually make an OrderedDict. Plus, an empty
> constructor in Python's interpreter returns an error that the class doesn't
> exist

It's in the collections module:

>>> import collections as coll
>>> help(coll.OrderedDict)
...
>>> od = coll.OrderedDict()
>>> od
OrderedDict()
>>>


HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


[Tutor] Use of None (was: Re: Tutor Digest, Vol 147, Issue 52)

2016-06-01 Thread Alan Gauld via Tutor
On 01/06/16 12:43, marat murad via Tutor wrote:
> Thanks for your replies,I think I understand it much better now. I Also I
> wanted to know what the 'None' does in the second program.

Please make the subject something meaningful and delete all the excess
messages. we have all seen them already and some people pay by the byte.

As for none, it just means a reference to nothing. ie no object.
So in your example:

start= None
while start != "":
start=input("\nStart: ")
...

The start = None could have been replaced by anything other than
an empty string. It just creates an initial value that causes
the while loop to start.

You will often find None used like this: to create a named
value that has no significance at that point in the program
but will be used later.

Another way of writing your example would be:

while True:   # loop forever
   start = input(...)
   if start = "": break   # break exits the nearest loop
   ...



HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Tkinter and threading

2016-06-02 Thread Alan Gauld via Tutor
On 02/06/16 14:40, Marco Soldavini wrote:

> What if I want to run another loop beside the graphical interface in
> the same python script?

You need to do it in a separate thread.
Keep the Tkinter loop on your main thread and use it to trigger
actions.

> For example a state machine with a var state which can have some
> discrete string values (like RUNNING, STOPPED, PAUSED, ABORTED, IDLE)
> and a text element on the gui that reports that state.

A state machine should not need a loop! It should be triggered
by state changes alone. ie state should only be changed by
calling a function. That function sets the state value
and calls any processing function associated with the
transition. (Whether before or after you set value depends
on whether you are using Moore or Mealy semantics, in
practice it makes little difference.)

You might need a loop to detect (some of the) changes but
setting the state machine should be entirely separate.

> So a button cause a transition > the python loop (not the gui loop)
> detects the transition and changes the state var value > the gui
> refresh its value on screen.

The button generates an event.
The event causes an event-handling function to be called.
That function may well cause a state transition that your state
machine can detect. (But it could just as well call your state
machine directly)

> I wrote some code to try it without threading but it does not give the
> expected result as it seems the button update status action is already
> triggered. I am missing some basic point here

If you want two parallel event loops you pretty much need threads.
Without threads you need to develop some kind of event-driven callback
solution - which may very well be preferable!


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Semantic Error: Trying to access elements of list and append to empty list with for loop

2016-06-02 Thread Alan Gauld via Tutor
On 02/06/16 18:05, Olaoluwa Thomas wrote:

> lst = list()
> for line in fhand:
> words = line.split()

words is now a list of words

 a test that a portion of my code was working)
> lst.append(words)

So you append that list to lst and get a list of lists.
Try using + instead:

lst += words

> would give me the output in the attached screenshot
> [image: Inline image 2]

This is a text based list attachments often get
stripped out by the server

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Practice Exercises for Beginner ?

2016-06-03 Thread Alan Gauld via Tutor
On 02/06/16 21:43, Andrei Colta wrote:
> Hi,
> 
> Anyone can recommend practical work on learning python.. seems reading and 
> reading does not helping.

Other have recommended starting a project and that's always the best way.

But if you are really stuck for ideas try the Python Challenge.
It's a game where you solve puzzles by writing Python code and
each solution gives you the url for the next puzzle. It's a great
way to learn about the standard library.

http://www.pythonchallenge.com/

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Desperately need help to uninstall python from my mac

2016-06-03 Thread Alan Gauld via Tutor
On 03/06/16 17:18, Christian Carbone via Tutor wrote:

> As the subject line indicates, I really need help uninstalling python on my 
> mac..

You almost certainly don;t want to to do that! Your Mac will stop
working properly, it uses Python. That's why its installed by
default on Macs.

> The reason i (think i) need to uninstall python is that when i open 
> IDLE i get this warning:
> "WARNING: The version of Tcl/Tk (8.5.9) in use may be unstable.

OK, So you have IDLE which is not ion a Mac by default so maybe you
installed an extra version of Python and you want to uninstall that?
Thats a very different thing that uninstalling Python entirely.

But the warning only says the version of Tcl/Tk *may* be unstable.
Does IDLE in fact work? If it doesn't can you replace the Tcl/Tk
libraries rather than Python?

> Visit http://www.python.org/download/mac/tcltk/ for current information.". 

Did you read that page?
Did you do what it suggested and install an ActiveState version
of Tcl/Tk for MAC?

Which versions of MacOS and Python are you using?

> I've heard i need to install a system appropriate tcl/tk (which i 
> believe i have done) before reinstalling python,

What makes you believe it? Which version did you install?
Where did you get it?

> but seeing as i cannot uninstall python I do not see any way 
> to resolve this issue.

Once we understand which version of Python you installed we
can start to consider whether/how you need to uninstall it.
What you should not do is try to uninstall the system version
of Python used by MacOS.

> Python.org doesn't seem to have any information that addresses 
> this problem, so I have come here in hopes of some guidance.

Did you read this page:

https://docs.python.org/3/using/mac.html

It doesn't explicitly tell you how to uninstall it, but it
does tell you what is installed, and where...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Cmd line not correctly interpreted

2016-06-04 Thread Alan Gauld via Tutor
On 04/06/16 02:01, Alan Outhier wrote:
> I'm working on a Python script to call "sox" to convert ;ogg files to .mp3s.

1outname=fname+".mp3"
2fname=ReSpace(fname)   # substitute " " with "\ "
3outname=ReSpace(outname)
4cmdline="sox " + fname + " " +outname
5print cmdline
6rtncode=os.system(cmdline)
7if rtncode <> 0:
8print "Bad return code (" + str(rtncode) + ") from sox command"
9sys.exit()*

> ...I DO get the error trap (every time). Line 5 causes the following (for
> example) to be printed:
> 
> *sox Carnegie\ Hall\ Jazz\ Band/Carnegie\ Hall\ Jazz\ Band/Frame\ for\ the\
> Blues Carnegie\ Hall\ Jazz\ Band/Carnegie\ Hall\ Jazz\ Band/Frame\ for\
> the\ Blues.mp3*
> *Bad return code (512) from sox command *

> I can however cop-past that output to bash and it works fine.

It might be easier to use the subprocess call() function
and pass the filenames in that way. Also you could try upping the
verbosity of sox so it tells you more about the error.

I'd be suspicious of the filename format and try using
hard coded strings in raw format first:

outname = r"Carnegie Hall Jazz Band/Carnegie Hall Jazz Band/Frame for
 the Blues.mp3"

If that works it suggests your formatting function is not doing
what it should.

Another thing to try is to eliminate the complex filenames entirely
by copying the file to foo.ogg in the local directory. See if that
works. Then try a name with spaces in the current directory. Then a
directory name without spaces. etc etc.

By a process of elimination you can find out where things start
to fall over.

> Please help! I'll send the whole program if requested.

The ReSpace() function might be helpful.

But please send using plain text. Trying to reconstruct Python
code as I did above is extremely error prone.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Python Setup Help

2016-06-08 Thread Alan Gauld via Tutor
On 08/06/16 03:24, Vincent Trost via Tutor wrote:
> Hi,
> I'm looking for help on the proper installation of Python and the Text 
> editor, Atom. 

OK, Lets break those into two separate activities. Start with Python.

> we downloaded Enthought Canopy and used that for some scientific Python work. 

Do you still have Canopy installed? Which version of Python was it?
Do you need anything more recent than that? If not stick with Canopy.
If you no longer need/want it you should be able to uninstall Canopy.

> I've struck up an interest in web-scraping, but for the life of me 
> I can't figure out how to set up a solid environment for Python 3.5.x

You don't need 3.5 to do web scraping. In fact your 2.7 install would
be fine for that.

> I've tried so many things that it's just become kind of a mess. 

We need a lot more specific details before we can offer concrete help.
- Which OS are you using?
- What are these "many things" that you've tried?
 (Which packages? From which site?)
- What exactly is the "mess" that you have?
- Do you get a working Python 3.5 prompt?
- What do you actually need beyond a basic vanilla Python installation?
  (I'd suggest Beautiful Soup as a minimum extra for web scraping,
  but are there other packages you think you need?

> I have a number of questions and problems with my installation that 
> I'm sure all it would take is for someone who actually understands
> the terminal, installation process, and just how all this works
> to come and get me straightened out. 

We don't really do home visits, it's a bit tricky when we are
scattered all over the planet... Penn State is a long way
from Scotland! But if you tell us what you are doing (in
much more detail) we can hopefully offer some advice.

Once you have Python installed we can think about installing
Atom. BTW. Is there any special reason you want to use Atom rather
than one of the more common editors? Have you used it before for example?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Command statement work well on interactive mode, which running as pf file it throws error object has no attribute '__getitem__'

2016-06-09 Thread Alan Gauld via Tutor
On 09/06/16 08:33, Joseph John wrote:

> Now when I create a *.py  file with all the above steps and run it, I am
> getting error
> Traceback (most recent call last):
>   File "./ReadingDataFrom1X.py", line 10, in 
> c = sheet['A1']
> TypeError: 'Worksheet' object has no attribute '__getitem__'
> 
> 
> The contents of  “ReadingDataFrom1X.py” is as follows
>  #!/usr/bin/python
> import openpyxl
> wb = openpyxl.load_workbook('MyTutor.xlsx')
> wb.get_sheet_names()
> sheet= wb.get_sheet_by_name('SQL Results')
> sheet.title
> print sheet.title
> print sheet['A1']

Not according to the error message. It says the error
is on the line:

c = sheet['A1']

But you don't have such a line.

So the code you sent us is not the code you are running.
Why that may be is the puzzle.
Do you have more than one file called ReadingDataFrom1X.py?

How are you running the code? Is it from an IDE such as IDLE?
Or from the OS command line? That might make a difference.



-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Command statement work well on interactive mode, which running as pf file it throws error object has no attribute '__getitem__'

2016-06-10 Thread Alan Gauld via Tutor
On 09/06/16 10:03, Joseph John wrote:

> itsupport@Server-A:~$ cat ReadingDataFrom1X.py
> #!/usr/bin/python
> import openpyxl
> wb = openpyxl.load_workbook('1XDataUserMDN.xlsx')
> wb.get_sheet_names()
> sheet= wb.get_sheet_by_name('SQL Results')
> sheet.title
> print sheet.title
> print sheet['A1']

I can't see anything obvious and since this is not part
of the standard library I suggest you try asking on the
support site for openpyxl.

http://groups.google.com/group/openpyxl-users

hopefully they can figure out what's happening.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Loop in pre-defined blocks

2016-06-10 Thread Alan Gauld via Tutor
On 10/06/16 23:43, Jignesh Sutar wrote:
> Is there a better way to code the below than to specify blocks as I have.
> Ideally I'd like to specify blocks simply as *blocks=(12,20,35)*
> 
> blocks=[(1,12), (13,20), (25,35)]
> for i,j in enumerate(blocks):
> for x in xrange(blocks[i][0],blocks[i][1]+1):
> print i+1, x


Can you explain in English what you are trying to do.
Working through your algorithm in my head is too much
like hard work. At the very least show us the output.

Better still explain what it means - what the data
represents and how the outputs relate to the inputs.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


[Tutor] Fwd: Re: Loop in pre-defined blocks

2016-06-10 Thread Alan Gauld via Tutor
Forwarding to tutor list. Always use Reply All when responding to list mail.

> Sorry, to be a little bit more descriptive. I'd like to loop from 1 to 35
> but within this loop there are divisions which I need to prefix that
> particular division number.

> My output would look like this:
>>>
1 1 
1 2 
1 3 
1 4 
1 5 
1 6 
1 7 
1 8 
1 9 
1 10 
1 11 
1 12 
2 13 
2 14 
2 15 
2 16 
2 17 
2 18 
2 19 
2 20 
3 25 
3 26 
3 27 
3 28 
3 29 
3 30 
3 31 
3 32 
3 33 
3 34 
3 35
>>>

You can't specify the blocks as just (12,20,.35) since you are using
non-contiguous blocks - you have a gap between 20 and 25.

So your definition needs to be (1,12),(13,20),(25,35) to specify
the missing rows. But you can arguably simplify the code a little:

blocks = ((1,13),(13,21),(25,36))
for prefix, block in enumerate(blocks):
 for n in range(*block):
  print prefix+1, n

its very similar to your code but using tuple expansion in range()
cleans it up a little bit and the names hopefully make the intent
clearer.

Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



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


Re: [Tutor] Loop in pre-defined blocks

2016-06-13 Thread Alan Gauld via Tutor
On 13/06/16 08:46, Ek Esawi wrote:
> Here is a beginner code that might work for you. Best of luck.   EK
> 
> b=[12, 20, 35]
> 
> for i in range(len(b)):
>  if i==0:
>   c=0
>  else:
>   c=b[i-1]
>  for j in range(c, b[i]):
>   print(i+1,j+1)

The problem here is that it doesn't give the gaps in the output
data that the OP requested. That's why we said they need the start
and stop values in the ranges.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Howto display progress as cmd is being executed via subprocess ?

2016-06-13 Thread Alan Gauld via Tutor
On 13/06/16 17:50, Ramanathan Muthaiah wrote:

> Am aware of the module called 'progressbar' that can do this magic of
> displaying progress as the cmd is executed.

I'm not familiar with it, I don't believe its in the standard library?
So I can only offer generalized advice.

> def main():
> progress = ProgressBar()
> for num in progress(range(80)):
> time.sleep(0.15)

I have no idea how that works since I don;t know anything
about the progress API. Its apparently callable and takes
a sequence and returns a sequence but what it does with
those values I can't say.

> And, I have this piece of code that executes set of cmds 
> This too works without any issues until now.
> 
> try:
>  dlog = subprocess.check_output([cmd],
> stderr=subprocess.STDOUT, shell=True)
> except subprocess.CalledProcessError, e:
> dlog = e.output
> 
> Question:
> 
> Am lost as to how to combine the progressbar and subprocess code snippets

Here's where the generalized help comes in.
There are two common approaches:
1) Split your work into bite sized chunks. Repeatedly call
those chunks until done and update progress after each chunk.
2) Run your work in a separate thread and in the main thread
update the progress bar either based on an estimated time
to complete or by reading the process output in some way.

How that translates to your particular ProgressBar I can't say.
But it might give you ideas. Or maybe the start of a specific
question to the module support forum/list or author

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Python ODBC driver for Oracle 9

2016-06-13 Thread Alan Gauld via Tutor
On 13/06/16 11:47, Joseph John wrote:
> I am trying to connect Python to Oracle 9 DB, checked for python ODBC
> driver for oracle.

Please be clear. Are you looking for an ODBC driver that will
work with Oracle 9?

Or are you looking for a Python DBAPI driver for Oracle 9?

Those are two different things.

> What I need is driver for Pyhton to get connected to Oracle 9.

You can do it directly or via ODBC. For an old version of Oracle it
might be easier to find an ODBC driver - that should have come from
Oracle with the database. The current Python ODBC driver should then
work with the Oracle ODBC driver.

Finding a native Python DB driver for Oracle 9 might be harder
although I'd expect one to still be available somewhere.

A Google search threw this up as the first link:

https://wiki.python.org/moin/Oracle

And it claims to work with Oracle versions 8 to 11i.



-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Hello everybody

2016-06-13 Thread Alan Gauld via Tutor
On 13/06/16 20:55, Влад wrote:
>Hi. I've just begin with Python? I'm 34. Is it late or what? If it is - I
>will cut it out. What you think guys?

No you are just a young whippersnapper.
I've had students use my tutorial in their 70s
(and in their pre-teens too)

But is this also your start in programming in general?
Or can you already program in any other language?
If the latter you will find python easy to pick up.

If the former you have some extra work to learn the
basic concepts as well as how Python implements
those concepts.

Finally, it will help if you are experienced in general
computer use: navigating folders, manipulating files (especially
to edit text files), using a command console, etc.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] capture output from a subprocess while it is being produced

2016-06-14 Thread Alan Gauld via Tutor
On 14/06/16 21:03, Albert-Jan Roskam wrote:

> from subprocess import Popen, PIPE
> from threading import Thread
> from collections import deque
> import sys
> import time
> import os.path
> 
> 
> def process(dq):
> """Run a commandline program, with lots of output"""
> cwd = os.path.dirname(sys.executable)
> proc = Popen("ls -lF", cwd=cwd, shell=True, stdout=PIPE, stderr=PIPE)  
> #print len(proc.stdout.readlines())  # 2964
> output = errors = None
> while True:
> try:
> #output, errors = proc.communicate() # "Wait for process to 
> terminate."  
> output = proc.stdout.read()  # docs: "Use communicate() rather 
> than .stdin.write, .stdout.read or .stderr.read"

read() reads the entire "file", try using readline() instead.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] rock paper scissor lizard spock help

2016-06-14 Thread Alan Gauld via Tutor
On 14/06/16 11:18, Katelyn O'Malley wrote:
> Hi I am just getting into python and I am trying to create a rock paper
> scissor lizard spock game for 3 people and I cannot figure out the scoring

The scoring of any ganme is the bit that makes it unique, so we would
need to know the scoring rules to know how you should proceed. however
there are many things we could look at in your code, I will restrict
myself to one:

> def name_to_number(name):
> if name == "rock":
> name = 0
> return name
> elif name == "spock":
> name = 1
> return name
> elif name == "paper":
> name = 2
> return name
> elif name == "lizard":
> name = 3
> return name
> elif name == "scissors":
> name = 4
> return name

This type of code can be greatly shortened and simplified by using
a more appropriate data structure, such as a dictionary:

def name_to_number(name):
tokens = {"rock":0, "spock":1, "paper":2, "lizard":3, "scissors":4}
return tokens[name]

And something very similar for the number_to_name function below.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Py 2.4.4: Inheriting from ftplib.FTP()

2016-06-16 Thread Alan Gauld via Tutor
On 16/06/16 16:38, boB Stepp wrote:

> class FTPFiles(FTP, object):
> """FTP files to Windows server location(s)."""

OK, First comment. You describe this as an action(verb)
rather than a noun. Classes should represent nouns
(objects) not actions. FTP represents a protocol
connection with which you can do things (one of
which is put/get files) you class should be the same.
(Remember inheritance m,eans you are imp0lementing
an "is a" relationship. So FTPFiles is an FTP...or
should be.)

> def __init__(self, host=server_ip, user=user, passwd=passwd):
> """Initialize FTPFiles object.  Normally the defaults will be used."""
> 
> super(FTPFiles, self).__init__(host, user, passwd)
> self.host = host
> self.user = user
> self.passwd = passwd
> 
> def print_welcome_msg(self):
> """Print welcome message sent by FTP server."""
> print self.getwelcome()


> 1)  FTP from ftplib appears to be an old-style class.

Using Python 2.4 that's not too surprising, FTP is an
old module.

> 4)  I have to use "super(FTPFiles, self).__init__(host, user, passwd)"
> or I cannot successfully inherit from the FTP() class.  Also, "self"
> apparently must come AFTER "FTPFiles" in the super expression.

That's the v2 super(). v3 super is far supeerior.

> 4)  As this class stuff is mostly treading new ground for me, am I
> doing anything that I should not be doing or should do in a more
> preferred way?  Keep in mind that I am just starting on this code
> today.

I'll leave someone with more ftplib experience to answer the other
points but the question I'd ask is what are you planning to add to FTP?
Creating a new class by inheritance implies that you are going to be
extending (or specializing) its capabilities in some way. What are you
planning to extend/specialize? For example are you going to limit it to
manipulating files only? ie prevent listing directories say?

You need to know what you are changing to warrant using inheritance.
Inheritance is a powerful tool but it carries lots of potential for
problems too, especially if you plan on mixing your new class in with
the old one (or sharing it with others who will) - you need to be
careful to abide by the Liskov substitution principle (LSP).

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Py 2.4.4: Inheriting from ftplib.FTP()

2016-06-17 Thread Alan Gauld via Tutor
On 17/06/16 16:41, boB Stepp wrote:

>> Inheritance is a powerful tool but it carries lots of potential for
>> problems too,...
> 
> I looked up LSP last night.  I can see how I can easily get burned
> even on something seemingly simple.  One example, which I imagine is
> often used, is of a square class inheriting from a rectangle class.
> Squares have same sized sides; rectangles not necessarily so.  So any
> size changing methods from the rectangle class inherited by the square
> class can potentially wreak havoc on squares.  Am I getting the
> essence of the potential issues I might encounter?

Yes, that's one case. Another good example(in Java) is in the book
"Effective Java". It uses the example of a superclass which is a
collection and has add() and add_many() methods. Now let's say you want
to create a counted collection so you override the add() method to add
one to a total each time its called. Then you override add_many() to add
the number of items in the params list.

The problem is that, unknown to you, the inherited add_many()
calls self.add() internally so you wind up double counting on
add_many()... You need to know about the internals of the
superclass to correctly implement your sub class, which
breaks the concept of data hiding...

There is no way round this its just one of the inherent(sic)
issues with OOP, but a good reason to use delegation rather
than inheritance if possible. Inheritance is a powerful tool
but comes with sharp claws. (Its even worse in a static language
like Java but even in Python there are plenty of  opportunities
to mess up).

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] help with comparing list of tuples in python 2

2016-06-17 Thread Alan Gauld via Tutor
On 17/06/16 20:18, Lulu J wrote:

> I have a list of dictionaries. Each dictionary has a word and its position
> in the text  the positions are in the form of a tuple.
> Here is an example:
> [
> {'position': (5, 4), 'term': u'happy',},
>  {'position': (5, 5), 'term': u'something'}
> ]
> 
> for the potions, the first element is the paragraph number and the second
> is the word number in that paragraph(sequence from 1...n)
> 
> What I would like to is find which words are next to each other. Meaning,
> they will be in the same paragraph and the difference of their word numbers
> is 1.

You can sort them by providing a key function, for example,
a simplified version::

>>> L = [{'k':1,'v':0},{'k':5,'v':9},{'k':2,'v':6},{'k':0,'v':12}]
>>> sorted(L,key=lambda d: d['v'])
[{'k': 1, 'v': 0}, {'k': 2, 'v': 6}, {'k': 5, 'v': 9}, {'k': 0, 'v': 12}]
>>> sorted(L,key=lambda d: d['k'])
[{'k': 0, 'v': 12}, {'k': 1, 'v': 0}, {'k': 2, 'v': 6}, {'k': 5, 'v': 9}]
>>>

Then filter your results to find an adjacent pair that have matching
positions. (This may not be necessary if you have all of the words since
they should naturally be placed adjacent to each other, but
if you only have key words it will be needed)

Something like (untested)

neighbours = [item for index,item in enumerate(data)
  if item['position'][0] == data[index+1][position'][0] and
  item['position'][1] == data[index+1][position'][1]-1]

But there are lots of possible gotchas here.

- look out for the last item which will give you an index error!
- what happens to words that appear more than once? Are they
  in your list more than once?
- probably more :-(


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Why are expressions not allowed as parameters in function definition statements?

2016-06-18 Thread Alan Gauld via Tutor
On 18/06/16 20:04, boB Stepp wrote:

> py3: def d(row, col/2, radius=5):
>   File "", line 1
> def d(row, col/2, radius=5):
>   ^
> SyntaxError: invalid syntax
> 
> And this surprised me.  It seems that only identifiers are allowed as
> parameters in a function definition statement, and I cannot help but
> wonder why?  

What are the parameters (as opposed to the arguments)?
They are names. They are keys in the local dictionary
used by the function to look up the values passed in
as arguments.

You cannot use an expression as a key in a dictionary.
If you try, Python tries to evaluate the expression
and uses the result if its valid or throws a nameerror etc.

hth
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Correct use of model-view-controller design pattern

2016-06-19 Thread Alan Gauld via Tutor
On 19/06/16 05:18, boB Stepp wrote:

> code, I am left scratching my head.  My main issue is what am I aiming
> at for a final CLI display of a circle?  This is not such a simple
> thing!  First, what are the units for a circle's radius in a CLI?  If
> it is 1 radius unit = 1 character, then your code is displaying too
> many characters.  

CLI "ASCII art" is dependent on the font used. If you change
your font size to an 8x8 character set then it will be much
easier (but your text will look awful!).

That's why we tend to use GUIs to do imagery. :-)

The effort to make a circle look circular in a CLI is
vastly disproportionate to the benefit since you need to
detect font sizes etc and have compensating parameters
that you can multiply by. And if the user picks a non
mono-space font things get even more difficult. Basically
its hardly ever worth it!

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


  1   2   3   4   5   6   7   8   9   10   >