Re: [Tutor] pygame not working

2017-08-16 Thread Alan Gauld via Tutor
On 16/08/17 17:33, Quantz Jeremy wrote:
> I’m not sure if I should be asking here about this,

Strictly speaking no, this list is for questions about
Python and its standard library. So PyGame issues should
really go to the PyGame support fora, and that's still
the best place for detailed support. Here's the top
level link:

http://www.pygame.org/wiki/info?parent=

The getting started page is worth reading too if you
haven't already.

But...

>  ...I have Python 2.7.13 ...Mac OS X 32-bit i386/PPC installer. 

Because you've given us so much detail there's a fair
chance somebody here will try and help.

You shouldn't need to go to Windows, the Mac version should
be fine. OTOH the windows version of pyGame should be
fine 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] "Path tree"

2017-08-16 Thread Alan Gauld via Tutor
On 16/08/17 02:02, Cameron Simpson wrote:

> Ok. So you have a graph like this:

>   1 -- 2 -- 3 -- 4
>|
>   7 -- 5 -- 6 -- 8
> 
>   graph = {
> 1: [2],
> 2: [1, 3],

  2: [1, 3, 5],

> 3: [2, 4],
> 4: [3],
> 5: [7, 6],

  5: [2, 6, 7],

> 6: [5, 8],
> 7: [5],
> 8: [6]
>   }

The missing link is pretty critical in this case :-)

-- 
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] Long post: Request comments on starting code and test code on chess rating project.

2017-08-16 Thread Alan Gauld via Tutor
On 16/08/17 04:06, boB Stepp wrote:

>> I agree with Neil, this is exactly what SQL is good for and
>> would make this part of the project much easier and would have
>> the added benefit of introducing you to one of the trickiest,
>> but most common, bits of OOP - object persistence...
> 
> Would you expand on this in SQLite terms?

I'm not sure which bit you want expanded so I'll do both :-)

The reporting side is easily within SQLite's capabilities
once you have the table structures defined. And SQLite's
big benefit for this kind of project is that there is
no server involved just a single data file, so easy
to maintain. You can even use the in-memory mode if you
just want the SQL aspects and are happy to persist
your objects in text files(JSON maybe?) Simply load
the JSON data into SQLite in-memory tables to perform
the queries.

The persistence issue really has nothing to do with
SQLite per se. To persist (ie store) your objects
between program runs requires that you save them
to disk somehow. Simple classes can be saved in
simple text files. but as classes contain other
classes/objects that gets complex. The next step
is a formatted storage mechanism like XML or JSON
which can handle nested objects. The other issue
in persistence is when to save the objects? Do
you just load everything into memory at startup and
then write it all back at shutdown? Or do you
incrementally save all changes as they happen?
In a dynamic, garbage collecting language like
Python incremental saves are safer in case an
object gets deleted accidentally, before it is saved.

But sooner or later you will need to move to a database
and that brings the issues of translating a class
into tables - especially if inheritance is involved.
Do you have a table per class with superclass links?
Or do you duplicate the  superclass attributes in
each child table? There are no right answers and
figuring out the most effective mapping is one of
the big challenges in real world OOP projects.

Another option is to adopt an Object Relational
Mapper (ORM) which will create and manage the SQL
aspects for you - but in the process make reporting
more difficult.

And lastly you could use a NoSQL database like Mongo
which can more easily persist complex objects and has
a reasonable reporting language (especially if you
use Mongoose). But this is likely a much bigger learning
curve, especially if its the first time you've used
it.

For your project I suspect a JSON solution would
be fine for persistence but no help for reporting.
SQLite, especially if you don't have lots of
complex classes, gives both for low cost (both
resources and learning) assuming you know basic
SQL to start with.

-- 
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] Long post: Request comments on starting code and test code on chess rating project.

2017-08-15 Thread Alan Gauld via Tutor
On 15/08/17 15:09, Neil Cerutti wrote:

>> There are a variety of reports that I would like to be able to
>> print to screen or paper.  Things such as a "Top x List" of
>> rated players, full rating list sorted from highest rating to
>> lowest, rating lists for the current school year only or a
>> particular past school year, and so.  ...

> You really can do it, but to me this requirement argues for going
> back to a database backend. Why rewrite SQL?

I agree with Neil, this is exactly what SQL is good for and
would make this part of the project much easier and would have
the added benefit of introducing you to one of the trickiest,
but most common, bits of OOP - object persistence...

You might even find yourself writing some class methods! ;-)

And using SQLite, (even using in-memory mode if you don't
want to keep a database file) is about as easy as SQL gets.

If you do want to do it by hand consider using the itertools
module. (eg. its filterfalse(), dropwhile()/takewhile()
combinations() and groupby() functions.)

-- 
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: "Path tree"

2017-08-14 Thread Alan Gauld via Tutor

Forwarding to the list.

 Forwarded Message 




pic
http://imgur.com/a/CwA2G

On Mon, Aug 14, 2017 at 8:55 AM, Alan Gauld via Tutor mailto:tutor@python.org>> wrote:

On 13/08/17 21:07, Michael C wrote:

> Please look at the picture attached:

This is a text mailing list, no binary attachments allowed.
The server strips them off.

You need to put it on a web site and provide a link.


> consisting of (x,y).  Now I am trying to make a function go
through this
> list of tuples and then return the "path." to go from, say, 4 to 8.

> How do I do this?

Do you know how to do it mathematically - eg with pen and paper?
If so its a matter of transcribing the algorithm into python
code. But if you don't know the background math, that's
where you need to start. Find the algorithm first.



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


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


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


Re: [Tutor] "Path tree"

2017-08-14 Thread Alan Gauld via Tutor
On 13/08/17 21:07, Michael C wrote:

> Please look at the picture attached: 

This is a text mailing list, no binary attachments allowed.
The server strips them off.

You need to put it on a web site and provide a link.


> consisting of (x,y).  Now I am trying to make a function go through this
> list of tuples and then return the "path." to go from, say, 4 to 8.

> How do I do this?

Do you know how to do it mathematically - eg with pen and paper?
If so its a matter of transcribing the algorithm into python
code. But if you don't know the background math, that's
where you need to start. Find the algorithm first.



-- 
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] Long post: Request comments on starting code and test code on chess rating project.

2017-08-13 Thread Alan Gauld via Tutor
On 13/08/17 21:15, boB Stepp wrote:

I return to the point I made about focusing on the
objects not the functionality.

> It is not very well-written in my opinion.  But anyway ... The basic formula 
> is:
> 
> new_rating = old_rating + K_MULTIPLIER * (opponent_rating -
> old_rating) + K_ADDER * (your_result - opponent_result)

What is being rated? A player? A game? a set of games?
The rating calculation should probably be a method of
the object being rated rather than a standalone function.

If you make it a function you will probably have to pass
in lots of data objects (or worse use a lot of globals).
In OOP you want the data to be in the object and the
method to use that data to achieve its aim.

> I generally start as above by dividing things up into broad areas of
> functionality 

Which is exactly how you write procedural code - the technique
is called functional decomposition.

But if your objective is to use OOP you should start by identifying
the objects. Then you can assign the functionality(responsibilities)
to which ever object (or set of objects) is appropriate.


> to be a rather straightforward translation of a formula with various
> conditions into code, returning the newly calculated ratings 

Note that I'm not saying your approach is wrong in a general case,
it may well be the most appropriate approach for this application.
But it will not easily lead to an OOP style solution, and that I
thought was the secondary(or even primary?) objective of this
exercise?

> So how detailed should I plan out each broad section of the program
> before writing any code?  Alan seems to be suggesting getting a firm
> handle on initially imagined objects and their methods before any code
> writing.

You need some kind of idea of the classes you are going to write.
The CRC description only needs to be a few lines scribbled on a
sheet of paper or in a text editor. In OOP you are building classes that
represent instances. Your solution is an interaction between the
instances (objects). Without a fairly clear idea of how the objects
interact you can't make a sensible start. You don't need to analyse
the whole system (and indeed should not do so) but start with a
couple of basic use cases - what initiates the action? What are
the  preconditions(eg. data etc), the outcomes, the possible error
conditions. When you understand a use case enough to code it, do so.
Or even just the initial class/object.

It's a good idea to get an early code structure in place, maybe
a Player class? It seems that this is the thing being rated.
Maybe a game class since it seems that game (results and players)
are used in the rating algorithm. So your Player probably needs
a list of past games?

-- 
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] Long post: Request comments on starting code and test code on chess rating project.

2017-08-13 Thread Alan Gauld via Tutor
On 13/08/17 06:22, boB Stepp wrote:

> The intent of this project is more than just calculate chess ratings.
> I also envision being able to store a record of all game results and
> player information for my school chess players that I give lessons to.

That's fair enough but OOP or no OOP the basic advice is the same:
divide and conquer. Make the admin and logic parts of the application
separate and work on the core of each. Bring them together via the
UI (which initially may be a set of CLI tools...).

> I have started my coding with a RatingCalculator class.  The intent of
> this class is to gather all methods together needed to validate and
> calculate chess ratings.  

That may be appropriate in that it is often the case that you have a
single class representing the applications a whole. But a calculator
sounds like a low level helper class to me, possibly encapsulating the
detailed algorithms used top create the ratings. I'd expect there to be
potentially several subclasses representing different algorithms. I'd
expect the calculator instances to be passed as an object into the
rate() method of a game object...

> My intent is to only ever have a single
> instance of this class existing during a given running of the program.

I notice Steven's post, to which I'll add amen.
Singletons in Python are rarely needed, just make your game
a module. Maybe rethink the role of the calculator class.

> added any methods yet.  Currently I am adding class constants that
> will be used in this class' methods. 

Since internal data/attributes should support the operations
its usual to start with the operations before defining
the supporting data. Seriously consider using the CRC
methodology to identify and describe your projects classes.
It can be in a single document rather than physical cards,
the important thing is to briefly describe what each class
is called, its responsibilities(often becoming methods)
and collaborators (other classes which become attributes
or method parameters).

>  These constants are for internal
> class use only and should not be altered from outside the class.  

It sounds like they are to be shared values across
methods of various objects/methods, that suggests
putting them in a shared class or module.

> is the current state of the main.py program (Which will probably be
> broken into multiple modules as the project develops.):

While Python doesn't require using a module per class, it is better to
keep related classes in a single module so I strongly suggest breaking
it into multiple modules. At the least 3: rating engine, admin and UI.

> """Module to process chess ratings."""
> 
> class RatingCalculator:
> """This class contains methods to validate and calculate chess ratings."""

I'd suggest that validation and calculation are two very different
things. Probably requiring separate classes. But we need more detail
on the objects involved. What does a rating rate - a Game? a Move? a
strategy? And what does validation validate? A rating perhaps?
You are in danger of focusing on the verbs (rating calculate,
create, edit, etc rather than the objects that do these things.
You need to turn your initial thoughts away from what the application
does (traditional procedural coding style) and onto thinking
about what kind of objects make up the application. It's common
to start with a fairly long list then, as you apply CRC analysis(*),
realize that many of the objects are only attributes. But it's better
to start with too many objects than to try to squeeze functionality
into just a few uber-objects.


(*)If you discover that a candidate class has no responsibility
except holding one or maybe two pieces of information, or that
it only collaborates with one other object you may decide it
only needs be an attribute not a full class. Also, especially
in Python, many collections of classes will turn out to be
standard container types such as lists, dicts, tuples etc.
Or standard classes such as dates/times. Making these early
win decisions is one of the biggest reasons for doing CRC
analysis IMHO.

-- 
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] conditional renaming folder and files in the tree

2017-08-12 Thread Alan Gauld via Tutor
On 11/08/17 16:10, banda gunda wrote:

> for root, dirs, files in os.walk(".", topdown=False):
> for name in files:
> print(os.path.join(root, name))
> os.rename(name.replace("---", "changed"))

Here you give the new name but not the original name.
The function needs two values, the source(original name)
and the destination(dst)


> list_of_files[name] = os.sep.join([dirpath, name])

What is dirpath? This is its first mention.

> ---
> TypeError Traceback (most recent call last)
>  in ()
> > 4 os.rename(name.replace("---", "changed"))
> 
> TypeError: Required argument 'dst' (pos 2) not found

See above

-- 
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] Percentage of installations without setuptools (Was if __name__=='__main__' ...)

2017-08-11 Thread Alan Gauld via Tutor
On 11/08/17 19:13, Chris Warrick wrote:

>>> a) people who just downloaded Python and never installed
>>>anything else
> 
> False since Python 3.4/2.7.9. ensurepip installs Python on every new
> Python install.

Sorry Chris, that's not making sense? Do you mean ensurepip
installs setuptools on every install? How does it do that if
I don't have the internet connected? Does it wait for
a connection then automatically do a download?

How would I tell if it is installed? Where do I look and
for what? Because its not where I thought it would be
- (in the libs)...

-- 
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] Percentage of installations without setuptools (Was if __name__=='__main__' ...)

2017-08-11 Thread Alan Gauld via Tutor
On 11/08/17 13:35, Thomas Güttler wrote:

> I guess most python installations have setuptools. 

I guess so too, although I don't know.
Those that don't are probably in one of two categories
a) people who just downloaded Python and never installed
   anything else
b) people working for large paranoid corporates. Although
   in this case there is probably only one installation,
   albeit with hundreds of users.

So far as I can tell I don't have it on any of my
Python installs on my Linux box, but I may just be looking
in the wrong place... I know I have it on my Windows box.

> But this is only my naive vague guess.

Me 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] What exactly does the three dots do? Why such as thing?

2017-08-11 Thread Alan Gauld via Tutor
On 11/08/17 14:57, Mats Wichmann wrote:

>> obscure features. Most Python programmers never use ellipses,
> 
> I guess what this means is when I post code snippets with some lines
> elided for greater readability of the point being made I should not use
> ellipses for that, as they're actually a syntactic element!   :)

Good point, because I often do that when replying to posts

def foo():...

I certainly don't mean the ellipses to be a syntactic element!


-- 
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 exactly does the three dots do? Why such as thing?

2017-08-10 Thread Alan Gauld via Tutor
On 10/08/17 14:39, C W wrote:

> I suppose it's just a place holder, though I don't know when I would use it
> in my every day life.

Probably never.

Like most programming languages Python has a load of rarely used,
obscure features. Most Python programmers never use ellipses,
metaclasses(*), the __new__() constructor, the _ variable or
even the else clause in a loop. That doesn't mean you shouldn't
look into them - they might just be the bit of magic you
need - but don't feel you need to have a use for every
bit of the language.

(*) Actually, everyone uses metaclasses, but very few define
their own!

-- 
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] setup.py "script" vs "console_scripts" Was: if __name__=='main' vs entry points: What to teach new comers?

2017-08-09 Thread Alan Gauld via Tutor
On 09/08/17 22:15, Steven D'Aprano wrote:
> On Tue, Aug 08, 2017 at 12:56:56PM +0200, Chris Warrick wrote:
> 
>> While setuptools is not officially part of the stdlib,
> 
> This is the critical factor. How can you use *by default* something that 
> is *NOT* supplied by default?

I have to agree with Steven here. Any mature language should
ship with all the tools needed to create and distribute a
finished program. It is to Python's shame that it currently
fails that test because the recommended distribution framework
is not part of the standard language package. (and the irony
is that the tool for installing the recommended format (pip)
is in the standard library. You can download other peoples
stuff but you can't make your own in the same format.
That's bad.

I hope that this is remedied soon, but for the moment Python
is horribly at odds with itself - enough to disqualify it
from use in many organisations.

Any default solution must be available by default.
It doesn't matter how many people recommend another
solution, if it isn't there it can't be used, and
therefore, can't be the default.

Sadly there seem to be many in the Python community who
do not understand the seriousness of this limitation
in terms of Python's adoption. Because they can access
it they assume everyone can. It's not true, and the further
up the Fortune 500 tree you climb the more that is the case.

-- 
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] Difference(s) betweenPython 3 static methods with and without @staticmethod?

2017-08-08 Thread Alan Gauld via Tutor
On 08/08/17 02:22, boB Stepp wrote:

> "@staticmethod" then there are two ways of calling the method, using
> objects or using the class.  Is there some reason not to use the
> "ClassName.a_static_method()" syntax?  Are there intended uses for
> doing this?

classes are objects too...

You could have a list of objects, some of which are classes
and some instances.

Its nice to use polymorphism and just call the staticmethod (or
classmethod) and let the interpreter do the hard work without
having to test types - a nasty non-OO style of programming that
should be avoided if possible

> Class methods look to be something I will find difficult to find a use for.

Once you start using objects a lot they come in very useful.
I don't think I've built any significant OO system without
using at least a few class methods. Remember that class methods
conceptually act on the class as a whole - ie on all instances
both current and future. So any time you have a large group
of objects and you want to set some kind of state for all
of them you can use classmethods to set class state. Instance
methods can refer to the class state and modify their behaviour
accordingly. (Some OO gurus argue that you should only set
class state via a class method, although you can do it via an
instance too - but what if you need to set it when no
instances exist. In Python direct access allows that
from outside the class, but in other OO systems you need
a class method.)

Class methods are also the best place to put alternate
constructors - eg loading from a database given an
instance ID or by parsing a string representation.

Class methods can also be used to manage caches of instances,
do global searches of instances (eg from a database) etc.

>> (1) There are very, very few good uses for static methods in Python. If
>> you think you need a static method, you probably could just use a
>> regular module-level function.

Amen to that, I try to avoid staticmethods... and so far
have never found a valid use for one. I treat them as a
piece of legacy from earlier versions, prior to classmethods.

-- 
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] Difference(s) betweenPython 3 static methods with and without @staticmethod?

2017-08-06 Thread Alan Gauld via Tutor
On 07/08/17 00:35, boB Stepp wrote:

> =
> Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64
> bit (AMD64)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
> py3: class MyClass:
> ... def my_method():
> ... print('This is my_method in MyClass!')
> ...
> py3: class MyOtherClass:
> ... @staticmethod
> ... def my_other_method():
> ... print('This is my_other_method in MyOtherClass!')
> ...
> py3: MyClass.my_method()
> This is my_method in MyClass!
> py3: MyOtherClass.my_other_method()
> This is my_other_method in MyOtherClass!

You should also try calling them from an instance of the class.
That should also illustrate a difference between classmethod and
staticmethod when you get round to that.

> the entry "staticmethod(function)" the author states, "... Use the
> @staticmethod functiion decorator in version 2.4 and later ... In
> Python 3.X only, this built-in is not required for simple functions in
> classes called only through class objects (and never through instance
> objects)."  

Notice the bit in parens...
It doesn't say you cannot call staticmethods from instances,
it says that you don;t need the decorator unless you are
doing that. Very 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] how to make an lexical scope block?

2017-08-05 Thread Alan Gauld via Tutor
CCing the list.
Always use ReplyAll or ReplyList when responding to the list.

On 05/08/17 18:17, Xiaosong Chen wrote:
> 2) Also we avoid importing with the
>> from foo import *
>>
>> even if you import with
>>
>> import foo
>>
>> foo.temp can still be accessed. When you use autocomplete in an
>> interactive shell like ipython, it might become an item.

foo.temp does not pose a problem of name pollution because you have
to prefix it with foo. Thus every module can have a temp variable and
there is no risk of names clashing because they all need to be
accessed with name.temp. You can even compare them:

if foo.temp < bar.temp

> 3) We need fewer temporary variables because we can use
>> tuple unpacking and generator expressions to replace many
>> scenarios where C would use a temporary variable.
> I know little with python's xxx comprehension. In my memory, temporary
> variables seem not allowed inside, and the same for lambda
> expressions. Might you give some examples?
>
Things like list comprehensions often replace explicit loops which
would introduce extra named variables. Consider:

>>> lst = [n for n in range(7)]
>>> n
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'n' is not defined
>>> lst
[0, 1, 2, 3, 4, 5, 6]
>>> lst2 = []
>>> for n in range(7): lst2.append(n)
...
>>> n
6
>>> lst2
[0, 1, 2, 3, 4, 5, 6]
>>>

You can see how in the list comprehension case n
is not visible outside the comprehension whereas n
exists outside the for loop(as you noted in your original
post) so, by using the comprehension we reduce
the number of visible names.


-- 
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] unorderable types

2017-08-05 Thread Alan Gauld via Tutor
On 05/08/17 19:28, Howard Lawrence wrote:

> if guess_value != number:
> number = str(number)
> print ('nope. the number i was thinking of was ' + number)

There is the problem, you convert number to a str before printing
it. so next iteration of the loop your if test fails.

You don't need the conversion in this case because print does it
automatically. If you did need it for some other purpose then
you should store the result in a temp variable rather than
in number itself.

This is a good example of why you should post the whole of your
code not just the snippet that you think is causing the problem...
If you had posted this in the first message we would probably
have spotted it right away.

-- 
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] really basic question..

2017-08-05 Thread Alan Gauld via Tutor
On 05/08/17 16:48, bruce wrote:

> redid a search just now. found a bunch of sites that said it's
> doable.. embarrased

Just because its doable doesn't mean you should though...

Bare except clauses can hide a multitude of sins. Unless its
at the top level of your program and you use it to log
any errors that occur its probably a bad idea.

Much better to be as specific as possible and catch only
anticipated errors. Anything else will then cause a crash
and you can investigate the (unanticipated) cause.

Note, you can link multiple error types in a single
except clause

try:...
except Error1:...
except (Error2, Error3, Error4):

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] how to make an lexical scope block?

2017-08-05 Thread Alan Gauld via Tutor
On 05/08/17 08:23, Xiaosong Chen wrote:
> In C, it's a common pattern to use temporary variables in an lexical
> scope to prevent the global scope from getting dirty.

This was very common in the early days of C - around 1979-1985 - when
compilers often only considered the first 4 (or 6) characters of a
variable name - even though the name itself could be 16 or 32
characters long.

Thus 'index' and 'indeterminate' and 'indent' were all seen
as the same name. This required careful limiting of the lexical
scope of variables. Nowadays I don't see that as an issue and
most of the C code I work with doesn't limit scope beyond
a function definition. Maybe some old school C programmers
still worry about tight scoping but not the ones I work with!

As for Python it limits names to global (actually module)
and function scope. If you are creating well structured
code based on short clear functions there should not be
much of a problem.

So, to answer the question,

1) we don't tend to need such scoping because the language
permits many names, and it provides module and function scopes.

2) Also we avoid importing with the

from foo import *

style which increases risks of name pollution.

3) We need fewer temporary variables because we can use
tuple unpacking and generator expressions to replace many
scenarios where C would use a temporary variable.

In practice I've never found it to be an issue.

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] The results of your email commands

2017-08-03 Thread Alan Gauld via Tutor
On 03/08/17 11:05, Abdur-Rahmaan Janhangeer wrote:
> me i cooked up :...

Yes that works too, especially if you don;t need access
to the individual prices later.

There are a couple of things to make it more Pythonic...

> x = True
> sum = 0
> 
> while (x==True):
> a = input("input:")
> if a =="exit":
> x=False

You could replace that with

sum = 0
while True:
 a = input("input:")
 if a =="exit":
 break# exit the loop

and

> try:
> sum += float(a)
> except:
> pass

That's a risky strategy because if there is
any error other than the one you anticipate
then you will never know about it and
ignore it. You should always try to specify
the error(s) if possible:

try:
   sum += float(a)
except ValueError, TypeError:
   pass

-- 
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 results of your email commands

2017-08-02 Thread Alan Gauld
I'[ve CCd the list, please use ReplyAll when responding to the list.


On 02/08/17 22:13, Borisco Bizaro wrote:
> Hi,am try to write a code that take input from user continuently
> until key press it stop and give total amount user  enter.

> while True:
>   input ("enter another price :")
> print"\n\n press 0 key to stop"

The last line should probably be before the loop.

You need to store the value somewhere, probably in a list
of prices.

Also you need to convert the input value to a number, probably
a float in this case(although for a real system you'd probably
use a Decimal or a multiplied integer for money.)

You also need to check the value before you store it to see
if its the last value (ie "0"). Something like

value = input()
if value == "0": break
try: prices.append(float(value))
except ValueError: print "you need a number"


-- 
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] Loop problem (was: Re: Tutor Digest, Vol 161, Issue 42)

2017-08-02 Thread Alan Gauld via Tutor
On 02/08/17 20:53, Borisco Bizaro wrote:
> I try this using loop but could not stop by pressing a key and could not
> give total price please help me

It would help if you showed us the code you wrote with the loop.
Its difficult to guess what you did wrong when we can't see it.

> print"\n welcome to progrom that print total price\n"
> a=int(input("enter the first price: "))
> b=int(input ("enter another price: "))
> c=int(input ("enter another price: "))
> d=int(input ("enter another price: "))
> f=int(input ("enter another price: "))
> g=int(input ("enter another price: "))
> h=int(input ("enter another price: "))
> total=a+b+c+d+f+g+h

Here is a hint...
You could collect the prices in a list then use sum()
to get the total. Then your loop only needs to read a
value and append() it to the list. break out of the loop
if the user enters 0, or -1, or whatever you want to stop it.

> print"\n totol",a+b+c+d+f+g+h
> print("\n\n press the o key to exit ")

Notice one print uses parentheses, the other doesn't.
Which version of Python are you using? Its better if
you stick to one form or the other as appropriate
to your Python version.

> This is what I did but could not be able to used while loop
> On Jul 30, 2017 23:44,  wrote:
> 
> Send Tutor mailing list submissions to
> tutor@python.org
> 

Please delete the digest material (it wastes bandwidth
and costs some folks money) and change the subject line
to something hewlpful, as suggested here...

> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Tutor digest..."
> 

-- 
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] If tuple cannot be sorted, then why sorted() on a tuple is fine?

2017-08-02 Thread Alan Gauld via Tutor
On 02/08/17 20:01, C W wrote:

> I am a little confused about why Tuple can be sorted.
> 
> Suppose I have the following,
> 
>> aTuple = (9, 3, 7, 5)
>> sorted(aTuple)
> [3, 5, 7, 9]

sorted() returns a new object.
The original tuple has not been changed
 - print aTuple to confirm this.

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] if __name__=='main' vs entry points: What to teach new comers?

2017-08-02 Thread Alan Gauld via Tutor
On 02/08/17 04:35, Abdur-Rahmaan Janhangeer wrote:
> what difference do you make between python scripts and python code files?
> 

Not much. Scripts are a concept more than a defined term,
they often refer to executable programs written in a
"scripting language" - which is usually an interpreted
language, like Python. Scripts traditionally coordinate
the actions of other, external programs, but as scripting
languages get more powerful they increasingly do all
the work themselves.

Code files covers any file containing code. Thus a
script is a subset of code file since it contains code.
But code files are not all executable, some are modules
to be imported by other code files (including scripts).

> are codes relating to file manipulation called scripts?

Not necessarily. Scripts tend to be shorter, comparatively
simple programs, similar to OS utilities. So they might
manipulate files, or they may tweak environment or
network settings etc. But some programs that manipulate
files are much more complex than that (think of a web
server) and would not normally be called scripts.

But it is a very vague area, the naming of scripts,
programs, applications, systems, modules, packages,
libraries etc. There are no clear definitions of
where one stops and the next begins.

-- 
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] if __name__=='main' vs entry points: What to teach new comers?

2017-08-01 Thread Alan Gauld via Tutor
On 01/08/17 15:54, Thomas Güttler wrote:

> He asked me if "if __name__=='main':" is state of the art if you want
> to translate a shell script to python.

It all depends what you plan to do with the script.
If you literally just want to translate a shell script such
that it will always be executed directly then you don't
even need an 'if name' clause, just hard code the script.

But if you plan in writing some functions that could be
reused by importing the script as a module then you really
should use 'if main'...

And if you intend to use your script only as a module
you should still use 'if name'... but this time call a
test function that runs some regression tests and/or
demo code.

But if you want to write a distributable package that
users can install into their Python infrastructure then
you should *additionally* create setup scripts with
entry points etc.

> you want to teach a new comers the joy of python.

For a newcomer I'd ignore packaging for now and focus
on the benefits of 'if name' over hard coding. One of the
great things about Python is how insanely easy it is to
create a file that can act as both a module and
executable. That can be crazy complex in some other
languages by comparison.


-- 
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] Error with sqlalchemy

2017-08-01 Thread Alan Gauld via Tutor
On 01/08/17 12:13, rakesh sharma wrote:

> I am getting the error
> 
> TypeError: utf_8_decode() argument 1 must be string or buffer, not long

That's not too helpful out of context, can you show us more
of the error trace? Can you show us the method that generates
it? Do you have any indication about which field is generating
the error?

> at this point in the code
> 
> ship_schedules = ShipSchedule.query.all()

One line out of context doesn't really help.
I'm assuming query is a class attribute in
the inherited Base class? Do you have to create
any overridden methods/attribute values to
make it work for your subclass?

I can't comment on the schemas because I don't know MySql
or Flask's ORM well enough to understand what may be happening.
But a bit more detail on the actual code triggering the
error and the error message itself would certainly not hurt.

-- 
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 sum() works in python

2017-08-01 Thread Alan Gauld via Tutor
On 01/08/17 07:06, ramakrishna reddy wrote:

>> sum([1,2,3]) returns 6.
> 
> But sum with [] 'empty list' as second parameter returns as below.
> 
>> sum([[1,2,3], [3,4,5]], []) returns [1, 2, 3, 3, 4, 5]

An interesting question, I wasn't aware that you could
add lists with sum.

However, the results seem clear enough. Let's start with the help()
description:
#
Help on built-in function sum in module builtins:

sum(...)
sum(iterable[, start]) -> value

Return the sum of an iterable of numbers (NOT strings) plus
the value of parameter 'start' (which defaults to 0).
When the iterable is empty, return start.
#

And lets see how it behaves with integers first:
>>> sum([1,2,3])   # use start default of 0
6
>>> sum([1,2,3],0) # use explicit start=0
6
>>> sum([1,2,3],1) # use start=1
7
>>> sum([1,2,3],9) # start = 9
15

So in each case we get the sum of the items in the iterable
plus the value of start. sum() is effectively doing

result = start
for n in iterable: result += n
return result

Now lets try using a list of lists:

>>> sum([ [1,2,3],[3,4,5] ])
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unsupported operand type(s) for +: 'int' and 'list'

We get a type error because the start uses 0 and we can't
add an int and a list. So let's provide a list as the
start value:

>>> sum([ [1,2,3],[3,4,5] ], [])
[1, 2, 3, 3, 4, 5]
>>>

We now get the behaviour you saw because it adds the
three lists together using the same algorithm as above.

And if we use a non-empty start it becomes even more clear:

>>> sum([ [1,2,3],[3,4,5] ], [42])
[42, 1, 2, 3, 3, 4, 5]

We could use tuples instead of lists and get the same result.

What is interesting is that if we try the same thing with
other iterables, such as a string, it doesn't work, even
though string addition is defined. There is obviously
some type checking taking place in there.

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] Recommended Python Compiler

2017-07-31 Thread Alan Gauld via Tutor
On 31/07/17 13:45, Wolfgang Maier wrote:

> here. There may be more powerful IDEs than IDLE, but it takes you a long 
> way (far beyond beginner/scripting level) 

And IdleX is a vastly superior, drop-in replacement, superset
of IDLE. The extra features, for those interested, are described
here:

http://idlex.sourceforge.net/features.html

It fixes most of the things people don't like about IDLE, except
for its appearance!

-- 
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] Recommended Python Compiler

2017-07-30 Thread Alan Gauld via Tutor
On 30/07/17 23:22, George Sconyers via Tutor wrote:
> ...looking for a recommended compiler for an Ubuntu environment. 

In programming precision is everything.

You are not in fact looking for a compiler, you are
looking for a development environment or IDE.

A compiler takes source code and produces executable
machine code. C-Python does not have such a thing
(it uses an interpreter to translate the code at runtime)
although you an get one for the Java based Jython.
But that's not really what you are asking for...

> ...using gedit but don't get the benefit of auto-indentation > and color 
> coding of key words.

These are feature of the editor (usually a component of an IDE)
- and gedit can do the syntax colouring, I'm not sure about the
auto-indent... But rather than use gedit I suggest you use
IDLE which is a simple but useful Python IDE built in Python.

> ...something that facilitates debuggig and stepping through code. 

IDLE does all of the above.

You can get it via the Ubuntu software manager or Synaptic or apt-get...
Make sure you get the right version for your Python version

There are many other IDEs for Python, right up to professional tools
like Eclipse and Netbeans but IDLE is a good starting point. And
there are lots of YouTube videos to get you started.

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] While loop homework: was Re: Tutor Digest, Vol 161, Issue 33

2017-07-30 Thread Alan Gauld via Tutor
On 30/07/17 23:36, Borisco Bizaro wrote:

> a=1
> b=2
> while a   input ("enter another price :")

Do 'a' or 'b' ever change?
Does 'a print"\n\n press 0 key to stop"

Does the user ever get the chance to enter a value?
If they were, Where is the value stored and is the
value ever used?

>> When replying, please edit your Subject line so it is more specific
>> than "Re: Contents of Tutor digest..."

Please follow the instructions as requested.
It helps find answers in the archives.


-- 
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] Tutor Digest, Vol 161, Issue 41

2017-07-30 Thread Alan Gauld via Tutor
On 30/07/17 19:50, Borisco Bizaro wrote:
> Please I have been ask to write python code that ask user to enter a price
> continuetly until key press to and give the total amount of price I have
> enter using while loop I don't know how to go about it

First of all, please do not send the whole digest to the list
 - some people pay by the byte and we've all seen it already.

Second, we solve programming challenges by breaking them down
into small parts and solving each part.

Third we don't do homework for you, but we can point you
in the right direction.

So, looking at your problem...

> ...write python code that ask user to enter a price

Do you know how to do that bit? get the usr to enter
a price and store (or print) the value?

> continuetly until key press

We'll come back to this.

> to and give the total amount of price

Do you know how to get the total of a list of prices?
For exanmple if I say

prices = [12, 13.00, 24.50. 17. 5.30]

Can you print the total of prices?

> enter using while loop

This ties in with the earlier requirement:

> enter using while loop
> continuously until key press

Lets assume the "keypress" is 0.
Do you know how to write a while loop that terminates
when an input value is 0?

Let us know the answers and we can point you
a little further towards solving the problem.

-- 
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's the difference between sort(aList) and aList.sorted()

2017-07-26 Thread Alan Gauld via Tutor
On 27/07/17 03:22, C W wrote:
> Thank you very much, Steve!
> 
> I think I got it. To get help() on a method, you have to somehow invoke an
> object first.

Or just use the class. In Steven's examples he included list.sort.
'list' is the class name for a 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] basic decorator question

2017-07-26 Thread Alan Gauld via Tutor
On 27/07/17 03:22, boB Stepp wrote:

> use them.  The idea of replacing a function with its decorated version
> sounds cool, but what types of problems would I want to use this
> approach on?

I'm sure others will have their own take on this but personally I view
them as primarily for building frameworks. For example in the standard
Python pantheon we use decorators to create properties and classmethods.

Web frameworks like Django use decorators extensively.

They are a way of embedding user code into our framework code without
the user having to know anything about how the framework does its magic.

And that is why I try not to use decorators for day to day code -
because they hide how the code works. Its similar with metaclasses,
they are immensely powerful but should be used sparingly because they
obfuscate how the code is working. And that, IMHO, is a bad thing.

So if you have some functionality that you want to wrap around a
set of functions in a standard way while at the same time not impinging
on the core logic of those functions then use a decorator. If you are
not sure why you are using them don't use them, just write an explicit
wrapper 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] What's the difference between sort(aList) and aList.sorted()

2017-07-26 Thread Alan Gauld via Tutor
On 26/07/17 19:40, C W wrote:

> My understanding of each is:
> 1) function(variable) is manipulating a vector, I can do bList =
> sorted(aList)
> 2) object.method() is permanently changing it, I don't even need to assign
> it in #1.
> 
> Why is there both? They do the same thing.

As you have just shown they do very different things.
One sorts the list in place the other returns a sorted
copy of the list.

Sometimes you want one, sometimes the other.


-- 
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] new to python

2017-07-25 Thread Alan Gauld via Tutor
On 25/07/17 04:58, N6Ghost wrote:

> this code works

> f = open("C:/coderoot/python3/level1/inputfile.txt", 'r')
> for line in f:
>  for line in f:
>  #print(line.rstrip())
>  print(line)
> 
> f.close()

> the out put skips the first line of the inputfile and puts a blank line 
> inbetween


I'm not sure why you have two for loops? Why did you do that?
Can you explain your thinking there?

Remove one of the for... lines.

Your code does this:

> f = open("C:/coderoot/python3/level1/inputfile.txt", 'r')

open the file and assign it to 'f'

> for line in f:

get the first line from f and assign it to 'line'

>  for line in f: print(line)

get the next line from f and assign it to 'line'
This overwrites the value from the first for loop above.
The line is then printed.

The second loop then repeats for all of the remaining
lines in the file. At the end of the second for loop
control returns to the top for loop. But, since the file
is now empty, the top loop never gets any more values
from f, so it terminates.

The blank lines are caused by the fact that the lines
in the file end in a newline character and print() adds
a newline of its own. Either reinstate your rstrip()
call or stop print() adding a newline with

print(line, end='')

I'm also not sure why you posted two copies of
your code? I assume you only use one since otherwise
you would have told us that you got two lots of output?

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] Study Python was: Re: Tutor Digest, Vol 161, Issue 36

2017-07-25 Thread Alan Gauld via Tutor
On 24/07/17 18:41, Borisco Bizaro wrote:
> Please what is the best way to study python programming well.

One important skill is to read and follow instructions.
For example...

> On Jul 24, 2017 17:00,  wrote:
> 
>> Send Tutor mailing list submissions to
>> tutor@python.org
>>
...
>>
>> When replying, please edit your Subject line so it is more specific
>> than "Re: Contents of Tutor digest..."

Also, do not  resend the entire digest - we have already
seen the messages and some members pay by the byte for
internet access.

As for learning Python there are videos on Youtube, multiple online
tutorials at every level and literally dozens of books. It all
depends on your personal learning style and your previous
programming experience.

I'd suggest you start with a few YouTube videos to get a feel
for things then dive into an online tutorial. The important thing
is to write code. Not just what the tutorials show you but take
that as a starter and modify it. See if the changes do what
you expected, if not figure out why not.

If you get stuck as questions here. Always tell us your Python
version and OS, post the problem code (cut n paste) and the full
error message if any.


-- 
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: basic decorator question

2017-07-24 Thread Alan Gauld
Bah, Forgot to ReplyAll...



 Forwarded Message 

On 24/07/17 15:33, bruce wrote:

> But, I'm sooo confuzed! My real question though, can a decorator have
> multiple internal functions? 

Yes and classes too if you want. A decorator is just a
standard function in all respects. The only thing that makes
it a decorator is that it takes a function as input and returns
a function as a result (ie it observes the decorator protocol).
Internally it can do anything that is legal in any function,
including creating as many inner functions and data structures
and classes as it wants.

> And, if a decorator can have multiple internal functions, how would
> the calling sequence work?

The calling sequence is just like any other code, it starts
at the top and follows the program control logic until it
either hits a return statement of falls off the bottom
(implicitly returning None). Note that the inner functions
do not need to be part of the returned function, they could
just be there to create some fixed value that is then stored
and used in the returned function.

eg:

def f(g):
 def h(): return 42
 myValue = h()
 def z():
   return myValue
 return z

f() is a decorator that takes a function g. It uses an
internal function h() to calculate a value. It then creates
a second inner function z() which returns that value.
Finally the decorator returns z. Notice that neither g()
nor h() are used in the returned function z().

You would use it like so:

def aFunc():
   return 666

always42 = f(aFunc)
print( always42() )

OR

@f
def aFunc() :return 666

print(aFunc())   # --> prints 42 !

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] Python3 Help

2017-07-24 Thread Alan Gauld via Tutor
On 24/07/17 01:58, Alan Gauld via Tutor wrote:

> $ which python3
> 
>>  -bash: $: command not found  
> 
> The $ is the OS prompt you are not supposed to type it in.

While on the subject you might also see something like

# 

Which can mean one of two things
1) It's a comment and you should not type it in
2) It's a root level command and you should su to root
   before running it. (# was the default Unix prompt
   for super users)

The latter usage is dying out and usually replaced with

$ sudo 

Which means that as an ordinary user ($) you type sudo
before the command. sudo should then prompt for your
user password before carrying out the command.

But the older # prompt style is still around in some
onlne tutorials.

-- 
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] Python3 Help

2017-07-23 Thread Alan Gauld via Tutor
On 24/07/17 00:19, Brandon Anderson wrote:

> 2.  I’m trying to locate the directory path to where Python3 is located on my 
> system, but when I enter 
>   the following command:
>   $ type -a python3

You could also try

$ which python3

>   -bash: $: command not found  

The $ is the OS prompt you are not supposed to type it in.

> 3.  How do I determine why I’m getting the ‘error’ command, instead of the 
> directory location of Python3.

The error means that there a mistake in your input.
In this case you included the $ in your input.

Note that this is an OS error and nothing to do
with python itself.

-- 
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: Python Help

2017-07-23 Thread Alan Gauld via Tutor
Forwarding to list



 Forwarded Message 

I did use the pip command and am attempting to add the files to my
python path. I used
 import sys
sys.path.append("/Users/Jim/Documents/illustris_python")

and that worked. I even checked to make sure the files were there 


import sys
print (sys.path)

['', '/Users/Jim/anaconda/lib/python36.zip',
'/Users/Jim/anaconda/lib/python3.6',
'/Users/Jim/anaconda/lib/python3.6/lib-dynload',
'/Users/Jim/anaconda/lib/python3.6/site-packages',
'/Users/Jim/anaconda/lib/python3.6/site-packages/Sphinx-1.5.6-py3.6.egg',
'/Users/Jim/anaconda/lib/python3.6/site-packages/aeosa',
'/Users/Jim/anaconda/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg',
'/Users/Jim/anaconda/lib/python3.6/site-packages/IPython/extensions',
'/Users/Jim/.ipython', 'Users/Jim/Documents/illustris_python']

the file is clearly there but when i try to do import illustris_python
as il it still can't find the module. 

I also figured that I need to manually export to python path so i tried:
export PYTHONPATH=$PYTHONPATH:/Users/Jim/Documents/illustris_python/
  File "", line 1
export PYTHONPATH=$PYTHONPATH:/Users/Jim/Documents/illustris_python/
^
SyntaxError: invalid syntax

I got invalid syntax... using a mac os x

I tried typing in terminal open .bash_profile and telling it to export
the python path in there like some others recommended but in terminal it
is giving me an error message for that... it must not be the right
command for the shell.

Winonah

On Sat, Jul 22, 2017 at 9:34 PM, Cameron Simpson mailto:c...@zip.com.au>> wrote:

On 23Jul2017 00:20, Alan Gauld mailto:alan.ga...@yahoo.co.uk>> wrote:

On 22/07/17 19:14, Winonah Ojanen wrote:

using python with anaconda in jupiter notebook. However, I
am having


Usual caveat: The tutor list is targeted at the standard library
so any help for non standard library modules is best sought from
the library support fora. In this case that includes the SciPy forum
and any illustris one.


Though arguably the OP's problem is an import issue, not really
module specific.

That having been said, I'll take a guess...

$ mkdir Illustris-3
$ mkdir Illustris-3/groups_135

Are these folders in your PYTHONPATH? If not Python will not
find them.

import illustris_python as il

---
ModuleNotFoundError   Traceback (most
recent call last)


The OP cded into the new dir; I'd normally expect things to be found
if the module was a local file/dir. However...

For some reason the computer is not recognizing this as a
file on my
computer. The CCA folks says this is a coding problem and
not an illustris
problem. any ideas to get me past this? I may also need help
getting
farther into the download process.


I just ran the OP's download command:

 wget -nd -nc -nv -e robots=off -l 1 -r -A hdf5
--content-disposition --header="API-Key:
d522db2e1b33e36d3b365cc9ac1c2c5d"

"http://www.illustris-project.org/api/Illustris-3/files/groupcat-135/?format=api

<http://www.illustris-project.org/api/Illustris-3/files/groupcat-135/?format=api>"

This doesn't seem to download any Python code at all. It does get a
couple of HDF files, presumably with data to work with.

So the issue is initially that the module isn't present anywhere.
Looking at the instructions cited
<http://www.illustris-project.org/data/docs/scripts/
<http://www.illustris-project.org/data/docs/scripts/>>, they only
cover fetching som data and working; they presume the software is
already present. I don't immediately see actual software
installation instructions, and it is not presented in PyPI.

Most like the OP will have to install the software directly from:

 https://bitbucket.org/illustris/illustris_python
<https://bitbucket.org/illustris/illustris_python>

This command:

 hg clone
https://bitbucket.org/illustris/stris_pythonillustris_python
<https://bitbucket.org/illustris/stris_pythonillustris_python>

should produce an "illustris_python" in the current directory, and
then her import command will find it.

However, there are other prerequisites. This pip command:

 pip install h5py numpy

seems to resolve them. The OP will need to use Python 2 because the
module seems to rely on a relative import (for its "util.py" file).

Cheers,
Cameron Simpson mail

[Tutor] Fwd: Re: Python Help

2017-07-23 Thread Alan Gauld via Tutor

Forwarding to list,
please use ReplyAll or ReplyList when responding to the list.


 Forwarded Message 

I also tried the correct command for the mac ox s in terminal shell,
running:

Jims-MacBook-Pro-2:~ Jim$
PYTHONPATH="/Users/Jim/Documents/illustris_python:$PYTHONPATH

> export PYTHONPATH


no error messages there but it is still not finding the module through
python.

Winonah


On Sun, Jul 23, 2017 at 1:34 PM, Winonah Ojanen mailto:winonah1...@gmail.com>> wrote:

I did use the pip command and am attempting to add the files to my
python path. I used
 import sys
sys.path.append("/Users/Jim/Documents/illustris_python")

and that worked. I even checked to make sure the files were there 


import sys
print (sys.path)

['', '/Users/Jim/anaconda/lib/python36.zip',
'/Users/Jim/anaconda/lib/python3.6',
'/Users/Jim/anaconda/lib/python3.6/lib-dynload',
'/Users/Jim/anaconda/lib/python3.6/site-packages',
'/Users/Jim/anaconda/lib/python3.6/site-packages/Sphinx-1.5.6-py3.6.egg',
'/Users/Jim/anaconda/lib/python3.6/site-packages/aeosa',

'/Users/Jim/anaconda/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg',
'/Users/Jim/anaconda/lib/python3.6/site-packages/IPython/extensions',
'/Users/Jim/.ipython', 'Users/Jim/Documents/illustris_python']

the file is clearly there but when i try to do import
illustris_python as il it still can't find the module.


Note that only shows the folder is in the path.

What does an 'ls' listing reveal as to the contents of the folder?
Is there a file called illustris_python.py? or maybe illustris_python.pyc?



I also figured that I need to manually export to python path so i tried:
export PYTHONPATH=$PYTHONPATH:/Users/Jim/Documents/illustris_python/
  File "", line 1
export PYTHONPATH=$PYTHONPATH:/Users/Jim/Documents/illustris_python/
^
SyntaxError: invalid syntax

I got invalid syntax... using a mac os x

I tried typing in terminal open .bash_profile and telling it to
export the python path in there like some others recommended but in
terminal it is giving me an error message for that... it must not be
the right command for the shell.

Winonah

On Sat, Jul 22, 2017 at 9:34 PM, Cameron Simpson mailto:c...@zip.com.au>> wrote:

On 23Jul2017 00:20, Alan Gauld mailto:alan.ga...@yahoo.co.uk>> wrote:

On 22/07/17 19:14, Winonah Ojanen wrote:

using python with anaconda in jupiter notebook. However,
I am having


Usual caveat: The tutor list is targeted at the standard library
so any help for non standard library modules is best sought from
the library support fora. In this case that includes the
SciPy forum
and any illustris one.


Though arguably the OP's problem is an import issue, not really
module specific.

That having been said, I'll take a guess...

$ mkdir Illustris-3
$ mkdir Illustris-3/groups_135

Are these folders in your PYTHONPATH? If not Python will not
find them.

import illustris_python as il

---
ModuleNotFoundError   Traceback
(most recent call last)


The OP cded into the new dir; I'd normally expect things to be
found if the module was a local file/dir. However...

For some reason the computer is not recognizing this as
a file on my
computer. The CCA folks says this is a coding problem
and not an illustris
problem. any ideas to get me past this? I may also need
help getting
farther into the download process.


I just ran the OP's download command:

 wget -nd -nc -nv -e robots=off -l 1 -r -A hdf5
--content-disposition --header="API-Key:
d522db2e1b33e36d3b365cc9ac1c2c5d"

"http://www.illustris-project.org/api/Illustris-3/files/groupcat-135/?format=api

<http://www.illustris-project.org/api/Illustris-3/files/groupcat-135/?format=api>"

This doesn't seem to download any Python code at all. It does
get a couple of HDF files, presumably with data to work with.

So the issue is initially that the module isn't present
anywhere. Looking at the instructions cited
<http://www.illustris-project.org/data/docs/scripts/
<http://www.illustris-project.org/data/docs/scripts/>>, they
only cover fetching som data and 

Re: [Tutor] new to python

2017-07-23 Thread Alan Gauld via Tutor
On 23/07/17 07:26, N6Ghost wrote:

> 
> f = open("C:\coderoot\python3\level1\inputfile.txt", 'r')
> for line in file:

Note that you have no variable called 'file'.
So this line doesn't make sense.

>  for line in f:
>  print(line.rstripe())

This bit will work if you omit the line above and
fix the indentation. (and remove the 'e' from strip()

>  f.close()

This should be outside the loop, you don't want
to close the file after every line.

Finally, there is another way to do this which
is considered 'better'/more Pythonic:

with open("C:\coderoot\python3\level1\inputfile.txt", 'r') as f:
 for line in f:
 print(line.strip())

Notice with this construct the closing of the file is
handled for you.

> any idea why that does not work?

When posting questions always include the full error text.
Although apparently cryptic it actually contains a lot of
useful detail which saves us from making guesses.


-- 
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 Help

2017-07-22 Thread Alan Gauld via Tutor
On 22/07/17 19:14, Winonah Ojanen wrote:

> using python with anaconda in jupiter notebook. However, I am having

Usual caveat: The tutor list is targeted at the standard library
so any help for non standard library modules is best sought from
the library support fora. In this case that includes the SciPy forum
and any illustris one.

That having been said, I'll take a guess...

> $ mkdir Illustris-3
> $ mkdir Illustris-3/groups_135

Are these folders in your PYTHONPATH? If not Python will not find them.

> import illustris_python as il
> ---
> ModuleNotFoundError   Traceback (most recent call last)


> For some reason the computer is not recognizing this as a file on my
> computer. The CCA folks says this is a coding problem and not an illustris
> problem. any ideas to get me past this? I may also need help getting
> farther into the download process.
You probably need to add the folders to PYTHONPATH environment
variable. How you do that depends on your shell. But any shell
tutorial will show you how. The format of PYTHONPATH is the same
as most other Unix PATHs - eg $PATH, $MANPATH, etc

The other thing to check is that there is not a pip compatible
installer which will put it in the right place for you... often
somewhere in site-packages.

-- 
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] Quick Pythonic Style Tips

2017-07-22 Thread Alan Gauld via Tutor
On 22/07/17 12:20, Abdur-Rahmaan Janhangeer wrote:

> As a user switching between some languages, it took sometimes before i
> discovered that there was a styling guide in python

There are style idioms in most languages although not always
written down as clearly as in PEP8. That having been said
they should be viewed as guides not rules. In addition there
are often local style guides that must be followed in
a particular company.

> i'd like to know if there was a specific C++ or java> style of doing things 
> which should be avoided ?

Mostly it's not layout style things that should be avoided
but actual programming styles - such as using Java style
getXXX/setXXX type methods for attribute access. Or getting
overly hung-up on trying to make data "private".

Some people get excited about naming (xxx_yyy v xxxYyy v XxxYyy)
but in practice these things make very little difference in
comprehensibility of code, which is the most important
consideration. Much more important is clarity of intent
in naming (such as the plurals-for-collections rule you
mentioned, or not using types as names - eg. anInt - unless
it truly is a completely generic place-holder).

The exception to all of this is code submitted to the
standard library. It really should have PEP8 applied
fairly rigorously both for the sake of consistency and
because the library is often cited as a style template.

-- 
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] PYTZ Package not working.

2017-07-20 Thread Alan Gauld via Tutor
On 20/07/17 18:41, Daniel Bosah wrote:
> I'm trying to get my function to work:

Did you read any of the replies to your previous message?

You do not appear to have applied any of the suggestions.

>  def deposit(self,amount):
> if amount > 0:
> self.balance += amount
> self.show_balance()
> 
> self.transaction_list.append((pytz.utc.localize(datetime.datetime.utcnow()),amount))
> # appends traction details to list
> 
> def show_transactions(self):
> for date, amount in self.transaction_list:
> if amount > 0:
> tran_type = "deposited"
> else:
> tran_type = "withdrawn"
> amount *= -1 # to show negative number
> print "{:6} {} on {} (local time was {})".format(amount,
> tran_type, date, date.astimezone())


But you are showing us less 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] Problems with pytz module

2017-07-19 Thread Alan Gauld via Tutor
On 19/07/17 20:58, Daniel Bosah wrote:

> class Account:
> def deposit(self,amount):
> if amount > 0:
> self.balance += amount
> self.show_balance()
> 
> self.transaction_list.append(

> def withdrawl(self,amount):
>  if 0 < amount <= self.balance:
> self.balance -= amount
>  else:
> print "The account must be greater then zero and no more then
> your account balance"
>  self.show_balance()

Ignoring the indentation issue, you only write transactions for
deposits. nothing for withdrawals.

> def show_transactions(self):
> for date, amount in self.transaction_list:
> if amount > 0:
> tran_type = "deposited"
> else:
> tran_type = "withdrawn"
> amount *= -1 # to show negative number
> print "{:6} {} on {} (local time was {})".format(amount,

But here you only print for withdrawals but not for deposits.

So you try to print non existent transactions.

> Im using Ubuntu Linux. My problem is that I cannot get show_transactions to
> print out on the console.

Since there shouldn't be any that match that's not surprising.

-- 
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] unitest with random inputs

2017-07-19 Thread Alan Gauld via Tutor
On 19/07/17 16:01, Sydney Shall wrote:
> I am learning to use unittest.
> 

>   def test_zero_in_capitalsadvanced(self):
>  self.assertIn(self.capitalsadvanced, 0.0)

Remember the interpreter...


>>> help(unittest.case.assertIn)
Help on function assertIn in module unittest.case:

assertIn(self, member, container, msg=None)
Just like self.assertTrue(a in b), but with a nicer default message.
~

> The error message is:
> 
>  self.assertIn(self.capitalsadvanced, 0.0)
>File "/Users/sydney/anaconda/lib/python3.6/unittest/case.py", line 
> 1077, in assertIn
>  if member not in container:
> TypeError: argument of type 'float' is not iterable

The obvious float is 0.0
The likely container is self.capitalsadvanced

They are reversed according to the help screen.

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] if/else statement

2017-07-18 Thread Alan Gauld via Tutor
On 18/07/17 18:31, Shane Johnson (shanejoh) wrote:

> def greater_less_equal_5(answer):
>if answer is '>' 5
>return 1
>elif answer is < 5:
>return 0
>else:
>return 4

> I’m getting a invalid syntax line 2 error. Any assistance is greatly 
> appreciated.

Thee are two problems.

1) 'is' is a problem, you don't need it here. 'is' is an operator
for testing whether two object references are to the same
actual object
eg.

x = 42
y = x   # y and x both refer to the same number
if x is y: print 'yes!'

You don't use it in mathematical comparisons so your code
should look like:

   if answer > 5
  return 1
   elif answer < 5:
  return 0
   else:
  return 4

Notice I also removed the quotes around the > sign and
added indentation to the return statements which leads
us to...

2) You don't have any indentation in the function body.
Indentation is all important in Python, it's how the
interpreter knows where the conditional block starts
and stops.

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 Questions

2017-07-18 Thread Alan Gauld via Tutor
On 18/07/17 11:41, Max Smith wrote:

> What's the easiest way to learn python currently 

Write a lot of code.

As to which tutorial to follow, that's a very personal choice and
depends on your previous knowledge and learning style. If you can
already program in a similar language(say Perl, PHP or Javascript)
then the official tutorial is just fine. If you are a comp-lete
programming neophite then use one of the non programmers
tutorials on the python web site (eg mine :-)

You can start with some of the many YouTube video courses if you
prefer but none of these will give you the depth that a
written tutorial will.

-- 
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] Image i/o in python

2017-07-16 Thread Alan Gauld via Tutor
On 16/07/17 17:13, D.V.N.Sarma డి.వి.ఎన్.శర్మ wrote:
> In python we have a set of imread and imshow in skimage. In matplotlib.image
> we again have imreadand imshow functions. In scipy.misc we again have
> another set imread and imshow. Are there anyfunctional differences between
> these multiple sets to justify their presence? …


None of these are part of the standard Python library
(as documented on python.org).

As a result the functions are named by the developers
of the respective packages. There is no central control
over third party packages so the developers can call
them what they like(*). They may or may not do the same
things - you need to read the documentation and try
a few tests to find out.

(*) And even in the standard library there are several
different open() functions and at least two sets of
time formatting functions with the same names and
functionality. That's what namespaces are for: to
keep them separate.

-- 
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 __del__ method

2017-07-11 Thread Alan Gauld via Tutor
On 11/07/17 15:47, Jia Yue Kee wrote:
> I am new to Python and I came across the Python __del__ method 

The __del__() method is a bit of an oddity and often not
used in industrial strength Python code.

> if __name__ == "__main__":
> x = Robot("Tik-Tok")
> y = Robot("Jenkins")
> z = x
> del x
> del z
> del y
> 

> My question being why is that "Robot has been destroyed" 
> is only printed once in Case 2 

Because __del__() only got called once.
Which is really quite good, although you don't know which
object's del() was called!

The problem is that python does not promise to
call __del__() even when it is defined! It only promises
not to call it until all references are deleted.
So we can say when __del__() will not be called but
not when it will be called, if ever. The problem is
that __del__() is called by the garbage collector
when it actually collects the deleted object and that
could be a long time after the reference count goes
to zero, or possibly even never!

This means __del__() is of limited usefulness since
you can't rely on it being called. So you can't safely
use it as a destructor to release resources.

> ...after the del x and del z statements, the refcount 
> to the Robot object should reach zero and subsequently 
> triggers the __del__ method right?

Nearly.
It *might* trigger the __del__() method, eventually.
Or it might not, there is no guarantee. Mostly it
will get called, but you can't count on it.

I confess I don't fully understand the reasons why
it's been done that way, it just is...

-- 
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: call key on_press event multiple times when key is held down

2017-07-10 Thread Alan Gauld via Tutor
On 04/07/17 13:45, Carlton Banks wrote:

> Any suggestion on any GUI solutions?

Here is a Tkinter solution that increments a counter
while the mouse button is pressed. It should give you the idea...
Obviously you need to replace the counter increment
with your desired processing. And the print statements
are just to show the events being processed.

##
import tkinter as tk

display = "count: "
flag = False
counter = 0

def do_down(e):
global flag
print('Key down')
flag = True
after_loop()

def do_up(e):
global flag
print('key up')
flag = False

def after_loop():
print('looping')
global counter
counter += 1
l['text'] = display +str(counter)
if flag:
   top.after(10,after_loop)


top = tk.Tk()
l = tk.Label(top,text=display+'0')
l.pack()
l.bind("",do_down)
l.bind("",do_up)
top.mainloop()

###

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] @property vs @classmethod

2017-07-09 Thread Alan Gauld via Tutor
On 09/07/17 02:56, Mats Wichmann wrote:

> From OO people, though, we get the sputtering But... But... what about
> encapsulation, data hiding, etc?

Encapsulation isn't really an issue here since Pythons classes
fully encapsulate their data and methods. They just make them
both public.

Data Hiding is the issue for some OO purists, especially those
who learned OO via C++/Java. But data hiding was never
originally enforced by the language, when Parnas wrote
his seminal paper there were very few languages that
explicitly supported making module data (he wasn't writing
about OO at the time) private. Instead data hiding was
achieved by providing such a powerful and complete set of
API functions that there was no temptation to play with
the supporting data.

Python adheres to that philosophy, although for "simple"
attributes it does allow, and even encourage, direct access.
But in most cases we, as class designers, should be striving
to provide sufficiently powerful methods that nobody needs
to mess with the internal state directly.

-- 
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] @property vs @classmethod

2017-07-08 Thread Alan Gauld via Tutor
On 09/07/17 00:03, Evuraan wrote:

> I was hoping to learn when to use classmethod and when to use property.
> They both seem similar (to me at least..), what's the pythonic way to
> choose between them?

In fact they do completely different things.

A property is a field of an object that you access via a getter or
setter method but use a syntax that looks like direct access to the
field. This allows you to implement data validity rules when setting the
data, or to restrict data access in the getter for example.

You can even create read-only or write-only properties by omitting
one or other of the get/set methods. The pythonic way is to allow
direct access to the data if you have no need of special processing.
If you do need to limit access in some way create a property.

A classmethod by contrast is a method that applies to the class as
a whole rather than the individual instances. You access a normal
method via an instance of the class:

foo = Foo()  # create instance
x = foo.bar()   # call instance method bar()

A class method is accessed via the class, no instance is needed:

y = Foo.baz()  # call class method baz()

It's possible, and even quite common, to have a classmethod being
used when no instances exist at all. This is especially so in
languages like Java, whereas in Python those cases are more
often dealt with by creating a vanilla function in a module.

Typical use cases for class methods include factory methods
to create instances in special cases - for example loading
a specific instance from a database given some arbitrary
criteria. Or it could be that a class keeps a list of all
existing instances and a classmethod reports how many
instances exist. There are many other such cases.

[Note: What is confusing is the difference between staticmethod and
classmethod. Those two are similar but subtly different and I
recommend ignoring staticmethod and just use classmethod.]

-- 
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] principal question

2017-07-08 Thread Alan Gauld via Tutor
On 08/07/17 09:05, marcus lütolf wrote:

> Is it possible to have python compare 2   subsequent  *.jpg  images
> in subtracting the pixel values of the second from the first image.

Yes

> If the images and are identical the result should be 0 and the first
> image could be deletet.

That's possible too although thee are easier ways
to compare files than manually comparing them pixel by pixel.
There are libraries that exist that you can use that do
much of the work for you. One of the good things about python
is that it has a huge catalog of existing code libraries
that can do most things you might need.

> If there is a difference (treshold pixel value  and pixel number to
> be determined)another action should be executed. 

That's possible too, if you really need to.

-- 
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 DB use with standalone desktop app

2017-07-06 Thread Alan Gauld via Tutor
On 06/07/17 18:32, zhenghao li wrote:
> 100 records are not a lot, so sqlite is sufficient. Its database engine 
> is included in python and it doesn't need to be run as a stand-alone 
> server so that saves you a lot of time for setting things up. If you 
> have a lots of tables and data say like more than 10k then you might 
> consider switching to a real database server.

Provided it's single-user then SQLite can easily scale up to a million+
records and still perform OK. I have one database with about 250k
records over 8 tables and the file is only 10MB in size and
query performance is effectively instant.

Where a server becomes important is when you have multiple users
and you care about security, locking, etc. or want to use
advanced features like stored procedures 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] Which DB use with standalone desktop app

2017-07-06 Thread Alan Gauld
Oops, I forgot the list! Blush...


On 06/07/17 18:30, Alan Gauld wrote:
> On 06/07/17 09:57, Freedom Peacemaker wrote:
>
>> own but google cant help me. There are some with SQL in name (eg. sqlite3,
>> MySql), but there are some other NoSql like MongoDB or Redis. 
> NoSQL databases are best for unstructured data(or flexibly structured)
> and for large volumes.
> For ~100 records where you know the columns you want then a SQL
> database is fine and SQLite3 comes with Python. The big advantaghe
> of SQLite is that everything is stored in a single file which
> can be easily distributed, no server to install etc. The downside is
> that there is no security login, just basic file permissions. For a
> desktop app that's usually not an issue.
>
> To use:
>
> #
> import sqlite3
>
> db = sqlite3.connect("your/database/filename")
> cursor = db.cursor()
> cursor.execute(,
>())
>
> results = cursor.fetchall()
> ##
>
> If you know SQL you should be able to figure it out from there...
> (And the SQLite web site has a good reference for their SQL syntax.)
>
> If not you can try the database topic in my tutorial(see .sig)
> which teaches basic SQL and how to use it from Python... Use
> the python2 version of the tutorial, but its easy to convert
> that topic to python3...
>
>

-- 
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 use main() ?

2017-07-05 Thread Alan Gauld via Tutor
On 05/07/17 16:37, David Rock wrote:

> This is a question about the benefits of using a main() function vs not.


Others have answered for the pros, but I confess that I don't
always use a main(), but only if all I'm doing is, say,
instantiating a class and running a method. For anything
more complex I'd write a main() (or test() or demo() ) to
go inside the
   if name==main
clause.

-- 
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: call key on_press event multiple times when key is held down

2017-07-04 Thread Alan Gauld via Tutor
On 04/07/17 12:00, Alan Gauld via Tutor wrote:

>> the library you are using, I normally just use the standard
>> library for such things, or build a simple GUI…
> 
> Standard library being?.. 

The Python standard library that ships with Python and
is documented on python.org. As in:

>> There are several but it depends on your OS.
>> In the standard library
>> Unix variants can use curses.
>> Windows users have msvcrt.


> Interesting solution, but still find a bit "dirty hackish”
> to involve a timer in this..  I guess it just would be neat if 
> it just worked as i thought it to be.  But i guess i have to look into curses.

A timer based loop is actually the standard pattern for
implementing a loop in an event driven environment (the
main alternative is to launch a background thread).
It's how most GUIs handle such scenarios.

The problem in a CLI solution is that you have to build your
own timer event system (usually based on time.sleep() or
similar). Hence the suggestion to use a GUI.

-- 
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: call key on_press event multiple times when key is held down

2017-07-04 Thread Alan Gauld via Tutor
Forwarding to Tutor list


Please always use reply-All or reply-List to respond to tutor posts.



 Forwarded Message 

> Den 4. jul. 2017 kl. 11.35 skrev Alan Gauld via Tutor :
> 
> On 04/07/17 09:50, Carlton Banks wrote:
>> I am trying to record from my microphone while i press down a button,
> 
> First question is which OS?
> That makes a big difference in this kind of scenario.

I am currently testing it on OS X, but should also be working on a ubuntu 
machine.  

>> the library I am using is not able to detect on hold event. 
> 
> There isn't really any concept of a hold event, you usually
> have to detect repeated press events. However I don;t know
> the library you are using, I normally just use the standard
> library for such things, or build a simple GUI…

Standard library being?.. 

> 
>> It only detect on press, which happens once, 
> 
> That's unusual, usually you get a repeated stream of
> press events when you hold a key down. But it does
> depend on the OS and environment. Your library may
> indeed just be detecting the initial key down and
> be waiting for the key up event.

Hmm.. interesting but again it is currently being tested on OSX,
as it was the only machine available atm. 
> 
>> So does any of you know any libraries that monitor> state of the keyboard,
> 
> There are several but it depends on your OS.
> In the standard library
> Unix variants can use curses.
> Windows users have msvcrt.
> 
> And there are several 3rd party libraries that try
> to do in a platform independent way - I'm guessing
> the one you are using is one such.
> 
> Another way to tackle it is to switch your code so
> it works with a toggle. Set the toggle to on in
> the on_press handler. Set it to off in the
> on_release handler
> 
> Then trigger a timer loop that runs for as long
> as the toggle is set. This is probably easiest
> done within a GUI.
> 

Interesting solution, but still find a bit "dirty hackish”
to involve a timer in this..  I guess it just would be neat if 
it just worked as i thought it to be.  But i guess i have to look into curses.



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


Re: [Tutor] call key on_press event multiple times when key is held down

2017-07-04 Thread Alan Gauld via Tutor
On 04/07/17 09:50, Carlton Banks wrote:
> I am trying to record from my microphone while i press down a button,

First question is which OS?
That makes a big difference in this kind of scenario.

> the library I am using is not able to detect on hold event. 

There isn't really any concept of a hold event, you usually
have to detect repeated press events. However I don;t know
the library you are using, I normally just use the standard
library for such things, or build a simple GUI...

> It only detect on press, which happens once, 

That's unusual, usually you get a repeated stream of
press events when you hold a key down. But it does
depend on the OS and environment. Your library may
indeed just be detecting the initial key down and
be waiting for the key up event.

> So does any of you know any libraries that monitor> state of the keyboard,

There are several but it depends on your OS.
In the standard library
Unix variants can use curses.
Windows users have msvcrt.

And there are several 3rd party libraries that try
to do in a platform independent way - I'm guessing
the one you are using is one such.

Another way to tackle it is to switch your code so
it works with a toggle. Set the toggle to on in
the on_press handler. Set it to off in the
on_release handler

Then trigger a timer loop that runs for as long
as the toggle is set. This is probably easiest
done within a GUI.

-- 
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] [Python2.7] Convert (2,188,1) into (188,1)

2017-07-04 Thread Alan Gauld via Tutor
On 28/06/17 16:48, Allan Tanaka via Tutor wrote:
> Hi. I have array shape like: (2,188,1). 

I assume this is a numpy array rather than the standard
library array? If so consider asking on the scipy/numpy
support forum for more specialised help.

> I want to make it like this: (188,1). I try that 
> using .reshape(188,1) 

.reshape() is not a valid function name. What object
are you attaching it to?

Show us at least a code snippet so we don't need
to guess. We need to see how you create the initial
array, then how you try to use reshape. Ideally a short
but complete example that exhibits the problem.

> but throws an error: total size of an array must be unchanged

Show us the full error trace, they contain a lot of information.


-- 
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] Not returning out the series

2017-07-04 Thread Alan Gauld via Tutor
On 04/07/17 03:40, Rafael Skovron wrote:

> def m(i):
> total = 0
> for i in range(1,i+1,1):
> total+=(i/(i+1))
> return total

convert the numerator to a float. Otherwise you
are using integer division. (I'm guessing you
are running Python 2.7?)

You could also import division from future:

from __future__ import division

Alternatively you could try running Python v3.

PS, Its probably not a great idea to use i as both
the iteration variable and the input parameter.
It easily causes confusion.

-- 
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: Ubuntu install [was: Re: Fwd: Re: program code for Python Programming for the Absolute Beginner, 3rd ed.?]

2017-07-03 Thread Alan Gauld via Tutor
Forwarding to group.

Please always use ReplyAll (or ReplyList) when responding to list emails.





 Forwarded Message 


I have a fresh install of Ubuntu 16.04.2, on which I try to install
Python 3.6.1. I have done this multiple times in the past, but for some
reason I tried it 3 times since yesterday but I kept having the same
error message. Here are the steps that i have taken for my installation:

|$ sudo apt-get update $ sudo apt-get upgrade $ wget
https://www.python.org/ftp/python/3.6.1/Python-3.6.1.tar.xz $ tar xvf
Python-3.6.1.tar.xz $ sudo apt-get install build-essential checkinstall
$ sudo apt-get install libreadline-gplv2-dev libncursesw5-dev libssl-dev
libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev $ cd
Python-3.6.1$ ./configure $ sudo make altinstall|

After the last command the following message will popup at some point:

The directory '/home/mariejosv/.cache/pip/http' or its parent
directory is not owned by the current user and the cache has been
disabled. Please check the permissions and owner of that directory.
If executing pip with sudo, you may want sudo's -H flag.

The directory '/home/mariejosv/.cache/pip' or its parent directory
is not owned by the current user and caching wheels has been
disabled. check the permissions and owner of that directory. If
executing pip with sudo, you may want sudo's -H flag.

How can I fix this?



Sent from my T-Mobile 4G LTE Device


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


[Tutor] Ubuntu install [was: Re: Fwd: Re: program code for Python Programming for the Absolute Beginner, 3rd ed.?]

2017-07-03 Thread Alan Gauld via Tutor
On 03/07/17 09:13, Alan Gauld via Tutor wrote:
> forwarding to list.
> 
> Sorry,
> I still have no idea what you are trying to do and what you want help with?

OK, I just realized that you replied to the wrong post
and this is actually about the thread on installing 3.6
on Ubuntu.

> 
>  Forwarded Message 
> 
> Alan,
> my bad, here is the error message.
> *The directory '/home/mariejosv/.cache/pip/http' or its parent directory
> is not owned by the current user and the cache has been disabled. Please
> check the permissions and owner of that directory. If executing pip with
> sudo, you may want sudo's -H flag.
> The directory '/home/mariejosv/.cache/pip' or its parent directory is
> not owned by the current user and caching wheels has been disabled.
> check the permissions and owner of that directory. If executing pip with
> sudo, you may want sudo's -H flag. *
> 
> 

-- 
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: program code for Python Programming for the Absolute Beginner, 3rd ed.?

2017-07-03 Thread Alan Gauld via Tutor
forwarding to list.

Sorry,
I still have no idea what you are trying to do and what you want help with?

 Forwarded Message 

Alan,
my bad, here is the error message.
*The directory '/home/mariejosv/.cache/pip/http' or its parent directory
is not owned by the current user and the cache has been disabled. Please
check the permissions and owner of that directory. If executing pip with
sudo, you may want sudo's -H flag.
The directory '/home/mariejosv/.cache/pip' or its parent directory is
not owned by the current user and caching wheels has been disabled.
check the permissions and owner of that directory. If executing pip with
sudo, you may want sudo's -H flag. *


On Sunday, July 2, 2017, 5:36:34 PM EDT, Alan Gauld via Tutor
 wrote:


On 02/07/17 11:03, Richard Grose wrote:
>
https://www.google.co.uk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0ahUKEwiw1tD3qurUAhULKlAKHWMOAPMQFggkMAA&url=https%3A%2F%2Fgithub.com%2FCWade3051%2FPy%2Ftree%2Fmaster%2FAbsolute%2520Book%2Fpy3e_source&usg=AFQjCNG36WhZfh5ftqWncjtgZy3z6xgh6g&cad=rjt
>
> Py/Absolute Book/py3e_source at master · CWade3051/Py · GitHub
> <https://github.com/CWade3051/Py/tree/master/Absolute%20Book/py3e_source>
> Richard G

Your subject line ends with a question mark so, are you asking
us something? Or telling us something?

Its not very clear which...

If you are asking you need to ask again, being a bit more specific.

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


Re: [Tutor] program code for Python Programming for the Absolute Beginner, 3rd ed.?

2017-07-02 Thread Alan Gauld via Tutor
On 02/07/17 11:03, Richard Grose wrote:
> https://www.google.co.uk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0ahUKEwiw1tD3qurUAhULKlAKHWMOAPMQFggkMAA&url=https%3A%2F%2Fgithub.com%2FCWade3051%2FPy%2Ftree%2Fmaster%2FAbsolute%2520Book%2Fpy3e_source&usg=AFQjCNG36WhZfh5ftqWncjtgZy3z6xgh6g&cad=rjt
> 
> Py/Absolute Book/py3e_source at master · CWade3051/Py · GitHub 
> 
> Richard G

Your subject line ends with a question mark so, are you asking
us something? Or telling us something?

Its not very clear which...

If you are asking you need to ask again, being a bit more specific.

-- 
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] Query regarding output

2017-06-29 Thread Alan Gauld via Tutor
On 29/06/17 03:14, shubham goyal wrote:

> This Question is asked in some exam. i am not able to figure it out.
> 
> a = [0, 1, 2, 3]
> for a[-1] in a:
> print(a[-1])
> 
> its giving output 0 1 2 2
> 
> it should be 3 3 3 3 as a[-1] belongs to 3.
> can anyone help me figuring it out.

This is quite subtle and it took me a few minutes to figure
it out myself.

It might be clearer if we print all of 'a' instead
of a[-1]:

>>> for a[-1] in a:
...print(a)
...
[0, 1, 2, 0]
[0, 1, 2, 1]
[0, 1, 2, 2]
[0, 1, 2, 2]

What is happening is that a[-1] is being assigned the value
of each item in a in turn. The final iteration assigns a[-1]
to itself, thus we repeat the 2.

Another way to see it is to convert the for loop to
a while loop:

for variable in collection:
process(variable)

becomes

collection = [some sequence]
index = 0
while index < len(collection):
 variable = collection[index]
 process(variable)
 index += 1

Now substitute your values:

collection = [0,1,2,3]
index = 0
while index < len(collection):
 collection[-1] = collection[index]
 print(collection[-1])
 index += 1

Does that help?

-- 
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] Query regarding Regular Expression

2017-06-28 Thread Alan Gauld via Tutor
On 28/06/17 21:27, cookiestar227 - Cookie Productions wrote:

>  So far have understood everything except for the following example:
> 
  t = "A fat cat doesn't eat oat but a rat eats bats."
  mo = re.findall("[force]at", t)

> What I don't understand is the [force] part of the Regular Expression.  

A sequence of characters inside square brackets means match any one of
the characters. So [force]at matches:

fat, oat, rat, cat, eat

It does not ,atch bat because there is no b inside the brackets.

The fact that force spells a real word is misleading, it could just as
well be written

[ocfre]at

and it would do the same.

> I would prefer to use the following RE as it achieves my desired result:
> 
 mo = re.findall("[A-Za-z]at", t)
 print(mo)
> ['fat', 'cat', 'eat', 'oat', 'rat', 'eat',  'bat']
Fine, but it does a different job, as you discovered.

The problem with regex is that very minor changes in
pattern can have big differences in output. Or, as
you've shown a big difference in pattern can make
a very subtle difference in output.

That's what makes regex so powerful and so very difficult
to get right.

-- 
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] Choosing between dictionary or external file

2017-06-28 Thread Alan Gauld via Tutor
On 28/06/17 17:44, Henrique C. S. Junior wrote:

> using dictionaries to store information. Here is an example:
> 
> 
> basis_sets = {
> "Pople-style basis sets": {
> "3-21G": "Pople 3-21G (H-Cs)",
> "STO-3G": "Minimal basis set(H-I)",
> "3-21GSP": "Buenker 3-21GSP (H-Ar)",
> "4-22GSP": "Buenker 4-22GSP (H-Ar)",
> "6-31G": "Pople 6-31G and its modifications (H-Zn)",
> "m6-31G": "Modified 6-31G for 3d transition metals (Sc-Cu)",
> "6-311G": "Pople 6-311G and its modifications (H-Br)"},
> 
> "The def2 basis sets of the Karlsruhe group": {
> "def2-SVP": "Valence double-zeta basis set with 'new' polarization
> 
> 
> My question is: is this the correct approach? The dictionaries, after
> finished, probably will not have to be changed for a long time and my idea
> is to import them in the main code.

Using dictionaries is ok, but your keys are inordinately long.
I'd probably define the strings as a set of variables(consts)
that can then be used in the dictionaries and in your code.

Otherwise you are likely to wind up with horrible looking code like:

if "beunker" in lower(basic_sets["Pople-style basis sets"]["3-21GSP"]):
.

Which is verbose at the very least and likely to be
error prone too. Whereas if you define something like

POPLE = "Pople-style basis sets"
...
basic_sets = {POPLE: {}}

The code becomes

if "beunker" in lower(basic_sets[POPLE]["3-21GSP"]):
   ...

Which, I think, is slightly easier on the eye. (And
you can still use the longhand version if you think
you need it)

> A second question is regarding the creation os a GUI, what are your
> recommendations (keeping in mind that I'm not an experienced programmer)
> Glade, PyQt + QT Designer, Tkinter or something else (to run on Linux, Mac
> and Windows)?

For easy to learn wrapping of a CLI I'd suggest Tkinter but
if you want to distribute the code to others then Qt probably
looks nicer and has more features. But a steeper learning
curve.

-- 
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: Using files to read data

2017-06-27 Thread Alan Gauld via Tutor
Forwarding to list

Please always use ReplyAll or ReplyList when responding to list mail.



 Forwarded Message 

i apologize.  i guess it didn’t attach correctly.
my issue is how do i get it out of my file and use it. 

*the json file, its only about a fifth of it but it should serve its
purpose*
[
0.9889,
0.02,
"Mon Jun 26 20:37:34 2017"
]
[
0.9777,
0.03,
"Mon Jun 26 20:37:34 2017"
]
[
0.9667,
0.0,
"Mon Jun 26 20:37:34 2017"
]
[
0.9556,
0.06,
"Mon Jun 26 20:37:34 2017"
]
[
0.9444,
0.0,
"Mon Jun 26 20:37:34 2017"
]
[
0.9333,
0.06667,
"Mon Jun 26 20:37:34 2017"
]
[
0.9223,
0.07778,
"Mon Jun 26 20:37:34 2017"
]
[
0.9111,
0.08889,
"Mon Jun 26 20:37:34 2017"
]
[
0.9,
0.1,
"Mon Jun 26 20:37:34 2017"
]
[
0.,
0.,
"Mon Jun 26 20:37:34 2017"
]
[
0.8778,
0.1,
"Mon Jun 26 20:37:34 2017"
]
[
0.8667,
0.1,
"Mon Jun 26 20:37:34 2017"
]
[
0.8555,
0.14443,
"Mon Jun 26 20:37:34 2017"
]
[
0.8444,
0.15556,
"Mon Jun 26 20:37:34 2017”

*the code that creates it*

import json
import time

def xyz(heading, forward_time):
"""get x and y increments of 360 degrees"""

if heading in range(1, 91):
north = heading
east = 90 - heading
y = (north / 90) * forward_time
x = (east / 90) * forward_time
now_time = time.ctime()

xyz = [x, y, now_time]

xyz_save = "xyz_save.json"


with open(xyz_save, "a") as stamp:
json.dump(xyz, stamp, indent=0)
stamp.write("\n")

return xyz

elif heading in range(91, 181):
east = heading - 90
south = 180 - heading
y = (south / 90) * forward_time
x = (east / -90) * forward_time
now_time = time.ctime()

xyz = [x, y, now_time]

xyz_save = "xyz_save.json"


with open(xyz_save, "a") as stamp:
json.dump(xyz, stamp, indent=0)
stamp.write("\n")

return xyz

elif heading in range(181, 271):
south = heading - 180
west = 270 - heading
y = (south / -90) * forward_time
x = (west / -90) * forward_time
now_time = time.ctime()

xyz = [x, y, now_time]

xyz_save = "xyz_save.json"


with open(xyz_save, "a") as stamp:
json.dump(xyz, stamp, indent=0)
stamp.write("\n")

return xyz

elif heading in range(271, 361):
west = heading - 270
north = 360 - heading
y = (north / -90) * forward_time
x = (west / 90) * forward_time
now_time = time.ctime()

xyz = [x, y, now_time]

xyz_save = "xyz_save.json"


with open(xyz_save, "a") as stamp:
json.dump(xyz, stamp, indent=0)
stamp.write("\n")

return xyz
 

*One of multiple loads I’ve got. *
*
*
', '0', ':', '3', '7', ':', '3', '4', ' ', '2', '0', '1', '7', '"',
'\n', ']', '\n', '[', '\n', '0', '.', '0', '2', '2', '2', '2', '2', '2',
'2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '3', ',', '\n', '0',
'.', '9', '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
'7', '7', '7', ',', '\n', '"', 'M', 'o', 'n', ' ', 'J', 'u', 'n', ' ',
'2', '6', ' ', '2', '0', ':', '3', '7', ':', '3', '4', ' ', '2', '0',
'1', '7', '"', '\n', ']', '\n', '[', '\n', '0', '.', '0', '1', '1', '1',
'1', &#

Re: [Tutor] Using files to read data

2017-06-27 Thread Alan Gauld via Tutor
On 27/06/17 06:32, Micheal Dale Peterson wrote:
> I am trying to write something that stores x and y data
> with a time reference and then use it later ...

Lets stick to one thing at a time.
How far did you get writing the data to a file?
Did the file get created? Can you edit in the
text editor?

The simplest way to do it is probably

x = 42
y = 66
time = "10:40:22.5"

with open("Myfile.txt") as output:
output.write(str(x)+'\n')
output.write(str(y)+'\n')
output.write(time + '\n')


That only outputs one line to the file Myfile.txt,
but you could put the write lines into a loop if
you had a list of data items.

> the closest i have come is using the json save.  

Using json is a reasonable approach for this type of problem.
Can you show us the actual code you used to write the data?
I assume it did actually get saved to a file in this case?

> Trying to read it back does me no good.

That's too vague to be any use. What does "no good" mean?
Could you open the file from Python?
Did you get any data at all?
Show us some code, even if it doesn't work as you expected.

>  i can print each thing individually. 

What do you mean? Do you mean you can read each
item from the file and print it? If so what is
it that you can't do? Can you save it in a variable?
Can you add the variable to a list for future use?

> everyday i try i either get a bunch of added characters 

Again this this too vague to be helpful.
Show us what kind of characters.
Show us the code you are using to read the data and print it.

> or it separates every character. 

Again show us code, and sample data so we can see.
The problem could lie in how you read the file or
in how you display the data. But without code we can't tell.

> Sorry i can’t  post all of the ways i have tried. 

Just post the latest attempts we can start there.

> I am running OS X version 10.12.5 with python 3.6.1.

Thanks for that, it helps.

> my code to get saved list

There's no code...

Did you send it as a binary attachment maybe?
The list server strips off all binary attachments
Cut 'n paste the code from your text editor into
the mail body.

-- 
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: bottle: request.form.get()

2017-06-23 Thread Alan Gauld


Please always use ReplyAll when responding to the tutor list.
(Or ReplyList if your mail client supports it)

(Having said that I forgot to add the list - oops! :)


On 22/06/17 19:48, adil gourinda wrote:
> 1) I expected a well made documentaion that your

The Python web site provides documentation for the full standard library,
which includes some basic web programming tools. But those are not as easy
to use as others such as bottle.

Bottle provides full documentation (including a tutorial) on their web site

Between the two you should find what you need. If not send us (or the
bottle support group)  your code  and some sample data and we can
try to help.

The bottle support is at:

A mailing list

https://groups.google.com/forum/#!forum/bottlepy

and a chat channel:

https://webchat.freenode.net/?channels=bottlepy


Both are linked on the main bottle web site.

> 2) My problem is that I don't know how to retrieve data from 
> tag, but in general I don't know how to connect between python and
> html in script. I am new in web-framework, if you can advise me to a
> more easy framework than bottle
>

I don't know bottle personally but I believe it's based on Flask and as
such
should be as easy to use as any of the (many) other web frameworks. In
other
words you should probably persevere with it rather than jump to another
framework that won't be any easier to learn.

-- 
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 generate specific lines of text from two python lists

2017-06-22 Thread Alan Gauld via Tutor
On 21/06/17 21:26, Tahir Hafiz wrote:

> My python skills are limited but I have managed to generate a couple
> of lists using python and the psycopg2 library by querying a postgress
> table and it's columns.

You say your python skills are limited but how about your SQL skills?
The reason I ask is that it sounds like you could greatly reduce the
amount of Python work by slightly increasing the SQL... Right tool
for the job etc.

You say you generated two lists from a postgres table and its columns? A
single table?

If that's the case you should be able to easily extract the two data
elements into a single list of tuples like (address,name).

Even if its more than one table you should still be able to do it
if there is any kind of logical link between the two pieces of data?

> I would like to use the two generated lists from the python script to
> create a file called upgrade_email_addresses.sql (and then later on
> use the psql "postgress cli" with the -f flag against this .sql file)
> which will be used to update the users database with the correct email
> addresses.

Why not just do the updates directly from Python? If you can do
a SELECT from Python you can also do the UPDATE. Just iterate
over the list of tuples generated above and execute an update
for each tuple.

> Is there a way to generate a file from two lists? 

Of course, and Peter has addressed that.
But I'd ask first whether you even need to do it?

> Any help would be much appreciated. I was thinking I could run the
> UPDATE queries in the psycopg2 console function directly in my python
> script but haven't been able to do that

I'm not sure what the console function is, but I'd think you
could run the UPDATEs directly from the dbapi with something
like:

for entry in data:
cursor.execute(query, entry)

where data is your list of tuples and query is your
update statement.


If, for some reason, you cannot extract one list as a
set of tuples then you need to join the two lists, but
remember that SELECT does not return its results in
any order unless you specify an ORDER BY clause.
So your two lists may not match entry for entry.
Would that be an issue? How would you identify which
address goes with which name?

-- 
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] bottle: request.form.get()

2017-06-22 Thread Alan Gauld via Tutor
On 21/06/17 15:54, adil gourinda wrote:

>I was looking for the "request.form.get()" method in "Python Library"> but 
> I didn't find it, I looked also in "Requests 2.18.1 Documentation"

You don't say which requests package you are using. You reference bottle
in the subject line and Requests in the body...

If it is the requests package in bottle then the bottle web site
has the documentation:

http://bottlepy.org/docs/dev/

The "Python Library" - assuming you mean the standard library documented
on python.org - does not include documentation for non-standard packages
like bottle.

-- 
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] Class

2017-06-21 Thread Alan Gauld via Tutor
On 20/06/17 23:39, Rex Florian via Tutor wrote:

> Can someone explain how Python achieves the vector addition of more than 2 
> vectors
> without some kind of looping?
> 
> class Vector:
>def __init__(self, a, b):
>def __str__():
>def __add__(self,other):
>   return Vector(self.a + other.a, self.b + other.b)

> print(v1 + v2 + v3)

When you do the addition Python evaluates it from left to right
so it is interpreted as:

((v1+v2) + v3)

so Python does:

v1.__add__(v2)

Which returns a new vector, let's call it vt

Python then does:

vt.__add__(v3)

which returns another new vector, lets call it result,
which is what gets printed using

print (result.__str__())


-- 
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] __str__ on a subclass

2017-06-19 Thread Alan Gauld via Tutor
On 19/06/17 20:32, Evuraan wrote:

> class Employee:
> """Class with FirstName, LastName, Salary"""
> def __init__(self, FirstName,LastName, Salary):
> def __str__(self):
> return '("{}" "{}" "{}")'.format(self.FirstName,
>  self.LastName, 
   self.Salary)

> class Developer(Employee):
> """Define a subclass, augment with ProgLang"""
> def __init__(self, FirstName,LastName, Salary, ProgLang):
> Employee.__init__(self, FirstName,LastName, Salary)
> self.ProgLang = ProgLang
> def dev_repr(self):
> return '("{}" "{}" "{}" "{}")'.format(self.FirstName,
>   self.LastName, 
self.Salary,
   self.ProgLang)

> a = Employee("Abigail", "Buchard", 83000)
> print(a)
> dev_1 = Developer("Samson", "Sue", 63000, "Cobol",)
> print(dev_1)
> print(dev_1.dev_repr())
> 
> running that yields,
> 
> ("Abigail" "Buchard" "83000")
> ("Samson" "Sue" "63000")
> ("Samson" "Sue" "63000" "Cobol")
> 
> My doubt is, how can we set the  __str__ method work on the Employee
> subclass so that it would show ProgLang too, like the
> print(dev_1.dev_repr())?

You  can't show ProgLang in Employee because it doesn't exist.
You can only show it on Developer. To make __str__() work for
developer you need to define it as you did for Employee.
You could just call self.dev_repr()

Or you could call super.__str__() and append self.ProgLang.
eg.

return super().__str__() + " " + self.ProgLang


Does that answer you question?

-- 
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] Fahrenheit to Celsius Conversion another problem and Programming Paradigm

2017-06-14 Thread Alan Gauld via Tutor
On 14/06/17 15:20, William Gan wrote:

> print('Enter C for Celsius to Fahrenheit or F for Fahrenheit to Celsius.')
> 
> if unit == 'C' or 'c':

You have hit a common error for beginners. reading this as a human
it is quite clear what is meant but the computer sees it
differently. It sees:

if (unit == 'C') or 'c':

Now, a non empty string like 'c' is always considered True in a
boolean context so, the interpreter interprets it as:

if (unit == 'C') or True:

And since any 'or' test where one element is True is evaluated to True

it reads as

if True:

and so the 'if' part is always executed.

How to avoid this? There are several options:

if unit == 'C' or unit == 'c':

But that gets cumbersome if more than two values.
Better is:

if unit in ('C','c'):

This is best if there are multiple true options
not just upper/lower case
or

if unit.lower() == 'c':

This is best is the strings are longer than a
single letter. (You can use unit.upper() too,
that's just an arbitrary choice)

> 1.   Is it possible that I may not have the right aptitude 
   or mental paradigm to do computer programming?

Possible, but unlikely, most folks with a basic math ability
can pick up programming. You may not be a natural, and may
never be a programming guru, but you should be able to get
to the stage of competence.

> However, I am having difficulty learning it. 

It is difficult, despite what some books would have you believe.
If it wasn't difficult there would be no need to teach it as
a university subject!

You have to train your mind to think like a computer (as in
the case above) and to break things down into often painfully
detailed steps. But that is just practice.

> I have been learning for a few months already and I am 
> not learning fast enough.

Says who? I've been programming for over 40 years and am
still learning new things every week.

Don't give up, and keep asking questions.

-- 
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] Raspberry pi 2 python help

2017-06-13 Thread Alan Gauld via Tutor
On 13/06/17 15:08, DJ VIN Lom wrote:
> Can i create a script to have my pi change to a certian directory
> automaticlly after booting. 

You have some serious misconceptions about how the Pi works.
The Pi does not have any idea of a "directory" when it boots
up. The whole concept of a home directory is related to
users. When a user logs in the shell sets a variable to
indicate that users home directory - you can have multiple
users logging into your Pi at once and they each have a
different home directory. But users log in after the Pi
has booted - and it could be seconds, minutes, hours
or days after before the first user logs in.

Having established that it's your login that needs to
be addressed we can look at how to set or change your
home directory. One way is in your user definition
in /etc/passwd. There is a field there that states
where the user goes when they login and you can edit
that.

Secondly when your shell starts up it executes various
startup scripts, depending on which shell you use.
Assuming its bash you can put commands into .bashrc
in your home directory, including a 'cd' to change to
wherever you want.

Finally, since you mention a Python script that
concerns you then you can put commands into the
script itself to change to any given directory
before doing anything else.

Use

import os
os.chdir(<"/your chosen/folder")

> I want it to be in a directory so when i ssh
> into it its ready and i dont need to spend time to do it. 

If it's about being in the right place at login you
probably should just change the login directory
in /etc/passwd. Although this begs the question
why you don't want to use the default /home/userid
directory? Maybe you should be creating links
or aliases to the files you need?

-- 
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] Query

2017-06-13 Thread Alan Gauld via Tutor
On 13/06/17 10:09, Muddunuri Mahesh wrote:
> Where can i get the perfect tutorials for black scripting using python

I'm not sure what you mean by black scripting - and
neither does google apparently... Other than that
it is a gothic style of typescript font...

But the perfect tutorial for anything does not exist
so you are going to have to be more specific about
what you want.

Can you already program in any language?
Can you already program in Python?
What do you want to achieve?
What kind of teaching style do you prefer - theory or hands-on?
What kind of OS do you use?

-- 
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] string reversal using [::-1]

2017-06-12 Thread Alan Gauld via Tutor
On 12/06/17 15:57, Vikas YADAV wrote:

> for i in range(len(s)-1, 1, -2):
> print s[i]
> -
> 
> So my question is: how would you write "s[::-1]" in terms of a for loop for 
> illustration purpose?

Exactly as above but replace -2 with -1

for i in range(len(s)-1, 1, -1):
print s[i]

But that seems too obvious, am I missing something
subtle in your question?

-- 
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] Creating 2 Subarrays for large dataset

2017-06-12 Thread Alan Gauld via Tutor
On 12/06/17 16:52, Peter Gibson wrote:

> I have a large, 4 column data set that is in the form of an array.  

Do you mean 4 separate arrays or a single 4xN array?
Or do you mean an N size array of 4 item tuples?
Or are the 4 colums part of a class?

There are lots of ways to interpret that statement.
Also are you using NumPy arrays or standard Python
arrays, or standard Python lists/tuples treated as arrays?

These all have a bearing.

It might help if you post a small sample of
your real data structure?

> last column, there is either a 1 or a 2, and they are not organized in any
> predictable manner (ex of an array of the last columns:
> 1,2,2,1,2,2,1,1,1,1,2,1,1, ect).
> 
> I would like to cut this large data set into two different arrays, one
> where the final column has a 1 in it, and the other where the final column
> of the data has a 2 in it.

A trivial way to do that (assuming 4 arrays called
col1,col2,col3,col4) is to create two lists/arrays
and iterate over the data filtering on col4:

ones = []
twos = []
for n in col4:
   if n == 1: ones.append((col1[n],col2[n],col3[n]))
   else: twos.append((col1[n],col2[n],col3[n]))

If you must have arrays rather than lists that's a relatively
minor tweak.

However, depending on your data structures there are
likely more efficient ways to do it (e.g. sorting on
column 4 then using slicing, or using a dict keyed
on col4, etc).

but it all depends on how large 'large' is, what the
actual time constraints are, what the real data structures
look like etc. Premature optimisation is the root of all
evil...

-- 
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] Fahrenheit to Celsius Conversion with if else statements

2017-06-12 Thread Alan Gauld via Tutor
On 12/06/17 15:17, William Gan wrote:

> print('Enter C for Celsius to Fahrenheit or F for Fahrenheit to Celsius.')
> unit = input('Enter C or F:')
> temp = int(input('Enter temperature:'))
> 
> if unit == 'C':

Note this only t5ests for 'C' - ie capital C.
You might want to force the input to be uppercase first?

if unit.upper() == 'C':


> f = (temp + 32) * 9 / 5
> print(str(temp) + ' C is equivalent to ' + "%.2f" % f + ' F.')
> else:
> c = (temp - 32) * 5 / 9
> print(str(temp) + ' F is equivalent to ' + "%.2f" % c + ' C.')
> 

> However, when I entered C, the else block was executed instead. The if block 
> was skipped.
> 
> Enter C for Celsius to Fahrenheit or F for Fahrenheit to Celsius.
> 
> Enter C or F:c

Note you entered lowercase 'c' not 'C'.
Very 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] Huge list comprehension

2017-06-12 Thread Alan Gauld via Tutor
On 12/06/17 05:54, syed zaidi wrote:

> One reason fornsharing the code was that I have to manually create over 100 
> variables
> Is there a way i can automate thst process?
I doubt very much that you *have* to create 100 varables,
that's an implementation choice as part of your design.

If you tell us what the problem is you are trying to solve
we might be able to suggest a more manageable solution
 - such as a better data structure perhaps?

-- 
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 actively maintained?

2017-06-12 Thread Alan Gauld via Tutor
On 12/06/17 03:54, Michael C wrote:
> Hi all:
> 
> is tkinter still being actively maintained? I only had to ask about this
> because I have never looked stuff like this up before.

Yes, Tkinter tracks the Tk releases so that most of
the activity at present is in the ttk sub package.

There is a moderately active active mailing list
and you can take a look at the list archive
to see the kind of issues they cover.

https://mail.python.org/pipermail/tkinter-discuss/

That having been said, and despite the fact I use
tkinter a lot, it is not the best UI toolkit if
you want to build a comprehensive desktop app.
GTk, Qt and Wxwidgets all offer much richer widget
support and better integration with native look 'n feel.
But Tkinter is great for quick and dirty UIs on top
of CLI code and is easier to learn.

-- 
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] string reversal using [::-1]

2017-06-10 Thread Alan Gauld via Tutor
On 10/06/17 17:39, Vikas YADAV wrote:
> Question: Why does "123"[::-1] result in "321"?
> 
> MY thinking is [::-1] is same as [0:3:-1], that the empty places defaults to
> start and end index of the string object.

Did you try that? You may be surprised.
The wonderful thing about the >>> prompt is that it's as quick
to try it out as to guess.

Look in the archives for a recent post by Steven(29/5,
"Counting a string backwards") that explains slicing,
it may help.

-- 
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] Huge list comprehension

2017-06-10 Thread Alan Gauld via Tutor
On 10/06/17 08:35, Abdur-Rahmaan Janhangeer wrote:
> take a look at numpy

It seems he already has, np.array is in his code.
It's just the imports that are missing I suspect.

> and don't necessarily give us the whole code. it becomes too long without
> purpose

Yes although in this case it does serve to highlight
the problems with his approach - as highlighted by Peter.


-- 
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] Coming from R, what's a good IDE editor? I've tried PyCharm and Spyder

2017-06-08 Thread Alan Gauld via Tutor
On 08/06/17 19:24, C W wrote:

> IPython is great for presentation, but you need to start it up in Terminal,

> Spyder does not have an icon in Application, you again need to start it up
> in Terminal with a few commands. It is slow to start up. (I have it)

You should be able to create your own icons for both of these.
Just drag them from finder to desktop and from there into Applications.
(You might need to edit properties to set the interpreter - its a wee
while since I used a Mac in anger - but I'm sure somebody here can
help with 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] Coming from R, what's a good IDE editor? I've tried PyCharm and Spyder

2017-06-03 Thread Alan Gauld via Tutor
On 03/06/17 07:20, Mike C wrote:

> There is a high demand for Python in the 
> industry, but there has not been a good IDE.
There are a ton of IDEs for Python including the
generic ones like VS, Eclipse and Netbeans.
But... I've tried many of these and find I keep
coming back to the simpler 3-window approach to
Python development:
- A code editor(multi-tabbed),
- an open interpreter session and
- an OS prompt for running/testing the program.

I always find that faster and more effective
than a complex IDE.

I'm not against IDEs in general and for C++ and
Java I find an IDE more or less essential. But
the immediacy and simplicity of Python with its
interpreter is very hard to beat. (It's the closest
thing I've found to the Smalltalk workspace for
productive programming)

> I find that strange.

It seems so until you try it. IDEs and Python
just don't work that well for many people. (Of
course there are also many folks who do like them
and use them, but compared to other languages they
are less used, because they offer less benefit.)


-- 
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] Pasting an image with transparency

2017-06-02 Thread Alan Gauld via Tutor
On 01/06/17 20:34, Terry wrote:
> Slackware 14.2 64-bit
> Python 2.7.13
> 
> I am trying to automate some photo processing by pasting a
> sig or watermark. The sig image is a .png with transparency
> but when it pastes it does so with a black background. Is there
> a way to paste with transparency?
> 

I believe there is a Pillow support forum, this is probably
better addressed to the PIL experts there.

https://python-pillow.org/

Or possibly even to a general imaging/graphics discussion forum.

-- 
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 wsgi_ref.simple_server - sometimes very slow!

2017-06-02 Thread Alan Gauld via Tutor
This appears to be a duplicate of the message you sent on 31st May.
Please don not send multiple copies of the same message, it fragments
the threads and messes up the archives for searching. One message is
sufficient, if you don't get a response it probably means nobody
knows the answer (or maybe your question was insufficiently specific,
although that's not an issue here). If you want to clarify the issue
send a follow-on to your own message, please don't start a new thread.

Thanks

Alan G.
Moderator.

On 02/06/17 07:20, Attila Szabó wrote:
> Hi All,
> 
> I'm facing a really strange behavior with python's wsgi_ref.simple_server
> module.
> 
> I have the following setup:
> - Raspberry Pi 2
> - Ubuntu Mate 16.04
> - Python3.5
> -
> 
> I have the following simple source:
> #!/usr/bin/env python3
> import wsgiref.simple_server
> 
> def my_func(env, start_response):
>   start_response('200 OK', [])
>   return [''.encode()]
> 
> server = wsgiref.simple_server.make_server(
>   '0.0.0.0',
>   19891,
>   my_func,
> )
> 
> server.serve_forever()
> 

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


Re: [Tutor] threading tutorial

2017-06-01 Thread Alan Gauld via Tutor
On 01/06/17 16:30, Michael C wrote:
> Oh i get it alright, however in my code I have to push the W button like
> this:
> 
> import pyautogui
> import time
> 
> pyautogui.keyDown('w')
> time.sleep(2)
> pyautogui.keyUp('w')

So this emulates a user pressing the w key for 2 seconds.
What's not clear is where this appears in your design,
is it part of the code running in the thread or is it
part of the code that stops the thread?

If you can explain a little bit more of the high level
requirement hee rather than the implementation perhaps
we can come up with a better solution - ideally one
that doesn't involve any keypress emulation at all...

> while the example you gave:
> 
>  def fn():
>global run_me
>while run_me:
>  ... do some work ...
> 
> and then elsewhere you go:
> 
>  global run_me
>  run_me = True
>  ... create and start the Thread ...
>  ... later ...
>  run_me = False
>  T.join()
> 
> theoretically deals with my problem, in practice though, my function spend
> almost all its time holding down the 'w' button, 

The fact you say the function suggests you mean the thread.
So the question is why does it need to hold the key down
for so long? Indeed why does a background process need
to emulate a button press? What is the button press doing?
Is it in turn detected by some other process/thread? We
need to understand how the various bits interact to give
a better solution.

> Is there a way to pause/kill the thread?

Not really other than setting a flag, but if its the
thread that's doing the sleeping then killing it
won't help - in fact if you could kill it in the
middle of the sleep() you'd have the problem of
a key being "held down" forever - probably a
bad thing... Thats why its better to have the
thread kill itself on detection of the semaphore.

-- 
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] 3D plotting

2017-05-29 Thread Alan Gauld via Tutor
On 29/05/17 21:40, Jack Lambert wrote:

> I am very new to python and am using it for some astronomy data analysis.
> What I am trying to is plot a 3D scatter plot of three variables that are
> being read from a file. I've tried using code from other examples of 3d
> plots but, having little idea how the code functions, I have had very
> little luck. 

I'm not sure where you got the examples but the official site
contains a wealth of samples.

http://matplotlib.org/users/screenshots.html

If you find one that's close to what you want, grab the
source code and try to map your data to that code.
That may be what you've already done, in which case you
are going to have to spend a bit of time learning the tools.

There is a specific matplotlib support forum however
who may be better placed than this list to help:

https://mail.python.org/mailman/listinfo/matplotlib-users

-- 
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] Problem with if statements and else statements

2017-05-28 Thread Alan Gauld via Tutor
On 29/05/17 00:12, Alex Kleider wrote:
> On 2017-05-28 13:13, Mats Wichmann wrote:
> 
>> FWIW, if checking for multiples, you could also write:
>>
>> if Month in ['January', '1']:
> 
> Would
> 
 if Month in {'January', '1'}:
> 
> be even better?  (regarding efficiency perhaps? Trivial point, I know, 
> but just wondering.)

If in doubt try it out and profile/time it.

But I don't think it will make much difference since ultimately
it still has to test each value (although a hashing algorithm
may be involved that works on partial matches...) But if in
doubt...

-- 
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] Counting a string backwards

2017-05-28 Thread Alan Gauld via Tutor
On 28/05/17 18:58, C W wrote:

> Now if I do case 2,
>> print(great[-3:-1])
>> me
> 
> Where did the exclamation mark go in case 2?
> 
> I was told the count begins at zero, that's true going forward, but not
> backwards.

Its not about where the count starts its about where it finishes.
It finishes 1 item before the second index. so in this case
you get the items at -3 and -2.

If you specify a third parameter you can change the
direction of the count thus:

>>> great[-1:-3:-1]
'!e'

So now you get the characters at -1 and -2 (ie in reverse order)

If you want them in original order starting at -3 just omit
the -1:

>>> great[-3:]
'me!'

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] airflow dag

2017-05-28 Thread Alan Gauld via Tutor
On 28/05/17 04:37, shubham goyal wrote:
> Does anybody have answer?

You received two answers, both of which asked
you to try something and get back to us for more
information. Did you try printing sys.argv?
What was the result?

And did you try Peter's argparse code?

You still haven't explained what your dag is?
What library are you using? It may treat args
in a non standard way, but we can't tell if
you don't give us the information we need to
help 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] How to deploy seamless script updates to your "clients"?

2017-05-26 Thread Alan Gauld via Tutor
On 26/05/17 22:56, Juan C. wrote:

>> a basic idea would be to get a webpage and put your code there. This is
>> where you edit your codes
> 
> What does a webpage have to do with this, I really can't picture that.

I think it just means host the files on a web server so you can access
them using http. You don't necessarily need a web page with HTML etc.
But I'm only guessing at what was intended.

-- 
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] airflow dag

2017-05-25 Thread Alan Gauld via Tutor
On 25/05/17 13:15, shubham goyal wrote:
> He guys,
> 
> I want to ask that can we pass the parameters as commandline arguments in
> airflow when we are triggering the dag and access them inside the dag's
> python script/file.

I've no idea what a dag is.
This list is for people learning Python as a programming
language but it has no knowledge(necessarily) of other
environments that use Python. So you need to tell us more.

In generic terms Python can read command line arguments
in the sys.argv list. So you could try adding a line like

import sys
...
print sys.argv


And see if your arguments appear there.
Otherwise you'll need to find a dsag forum and try asking there.
Or get very lucky and find someone on this list that speaks dag.

If they are present in sys.aergv then there are several modules
that can parse the arguments looking for option flags etc.
argparse is the current official recommendation.


> script:
> 
> from airflow import DAG
> from datetime import datetime,timedelta
> default_args = {
> 'owner': 'airflow',
> 'depends_on_past': False,
> 'start_date': datetime.now(),
> 'email': ['airf...@airflow.com'],
> 'email_on_failure': False,
> 'email_on_retry': False
> }
> MAIN_DAG='check_dag'
> dag = DAG(dag_id=MAIN_DAG, default_args=default_args,
> schedule_interval=None)
> 
> with open(file, "r") as f:
> payload = f.read()  # Reading the json data from a file
> SimpleHttpOperator(  # creating cluster using SimpleHttpOperator
> task_id='cluster_create',
> method='POST',
> http_conn_id='qubole_default',
> # for directing to https://qa.qubole.net/api
> endpoint='/v2/clusters?auth_token=%s' % (passwd),
> data=payload,
> headers={"Content-Type": "application/json"},
> params={'auth_token': passwd},
> response_check=lambda response: True if response.status_code == 200
> else False,
> dag=dag

I'm not sure what you think the line above does but
in normal Python it would have zero effect.

> like this here i am trying to create a cluster but i need to pass password
> as cli arguments when i trigger the dag. can we do that. please help.

You need to explain what you mean bearing in mind we don't
know anything about dag, or clusters.

-- 
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] real time response

2017-05-24 Thread Alan Gauld via Tutor
On 23/05/17 21:07, Michael C wrote:

> def do_stuff:
>  blah
>  check()
>  blah
>  check()
>  blah
>  check()
>  blah
> 
> and then either break or return if condition is met?
> 
> But that just isn't responsive enough. Is there a way to make function
> check for the  event every 0.5 seconds without interfering with the
> do_stuff, ie a code that has its' own space?

Yes. What you have just described is called threading. You can
start a separate sub-process running in the background to
"do stuff" while in your main program (thread) you can monitor
the dots. If your condition is met you can close the sub-thread.

Threading is non trivial however and very easy to get wrong.
I suggest you google for some tutorials and maybe watch a
Youtube video or two to get a feel for 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


<    3   4   5   6   7   8   9   10   11   12   >