Re: [Tutor] tar a directory

2016-11-04 Thread Alan Gauld via Tutor
On 03/11/16 17:56, Bill Nolf wrote:

> Test 4
> 
> archive = tarfile.open("test.tgz", "a:gz")
> archive.add=(dirarchive, arcname="test")
> archive.close()
> 
> Create a gzip file called test.tgz in the current directory, which is close
> but no cigar
> What I would like is the following gzip file:
> 
> /a/b/c/archive.tgz

So why not:

archive = tarfile.open("/a/b/c/archive.tgz", "a:gz")

or is that too obvious?

-- 
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: tar a directory

2016-11-04 Thread Alan Gauld via Tutor
Always use reply-all or reply-list when responding to tutor posts

==

The archive file changes each time so I need to set a variable based on the 
changing directory

Sent from my iPhone

> On Nov 4, 2016, at 5:54 AM, Alan Gauld via Tutor <tutor@python.org> wrote:
> 
>> On 03/11/16 17:56, Bill Nolf wrote:
>> 
>> Test 4
>> 
>> archive = tarfile.open("test.tgz", "a:gz")
>> archive.add=(dirarchive, arcname="test")
>> archive.close()
>> 
>> Create a gzip file called test.tgz in the current directory, which is close
>> but no cigar
>> What I would like is the following gzip file:
>> 
>> /a/b/c/archive.tgz
> 
> So why not:
> 
> archive = tarfile.open("/a/b/c/archive.tgz", "a:gz")
> 
> or is that too obvious?
> 
> -- 
> 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 maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python code

2016-11-01 Thread Alan Gauld via Tutor
On 01/11/16 21:28, Haley Sandherr wrote:
> Hello, I am new to python and need help with this question:

What kind of help? What exactly do you find difficult?
> 
> Compose a function odd ( ) 

Can you define a function? Any function?

> that takes three bool arguments 

Can you define a function that takes arguments - any arguments?
Can you define one that takes exactly 3 arguments?

> and returns True

Can you define a function that returns a value - any value?
Can you define a function that returns True?

>  if an odd number of arguments are True and False otherwise.

Can you test if a value is True?
Can you test if 2 out of 3 are True?
(There are several ways to do this! Some easy and
some harder but shorter )

How far down that list do you get before becoming stuck?

I could show you a single line solution, but I doubt you
would learn very much from it. It is better for you to come
up with your own solution where you actually understand
what every line of code does.

-- 
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] implementing sed - termination error

2016-11-01 Thread Alan Gauld via Tutor
On 02/11/16 00:18, bruce wrote:

> Trying to do a search/replace over a file, for a given string, and
> replacing the string with a chunk of text that has multiple lines.
> 
> From the cmdline, using sed, no prob. however, implementing sed, runs
> into issues, that result in a "termination error"

I don;t understand what you mean by that last paragraph.
"using sed, no prob" implies you know the command you want
to run because you got it to work on the command line?
If that's correct can you share the exact command you
typed at the command line that worked?

"implementing sed" implies you are trying to write the
sed tool in Python. but your code suggests you are trying
to run sed from within a Python script - very different.

> The error gets thrown, due to the "\" of the newline. 

That sounds very odd. What leads you to that conclusion?
For that matter which \ or newline?
In which string - the search string, the replacement
string or the file content?

> The test file contains 6K lines, but, the process requires doing lots
> of search/replace operations, so I'm interested in testing this method
> to see how "fast" the overall process is.

I'm not sure what you are testing? Is it the sed tool itself?
Or is it the Python script that runs sed? Or something else?

> The following psuedo code is what I've used to test. 

Pseudo code is fine to explain complex algorithms but
in this case the actual code is probably more useful.

> The key point
> being changing the "\n" portion to try to resolved the termination
> error.

Again, I don't really understand what you mean by that.


> import subprocess
> 
> ll_="ffdfdfdfg"
> ll2_="12112121212121212"
> hash="a"
> 
> data_=ll_+"\n"+ll2_+"\n"+qq22_
> print data_
> 
> cc='sed -i "s/'+hash+'/'+data_+'/g" '+dname
> print cc

I assume dname is your file?
I'd also use string formatting to construct the command,
simply because sed uses regex and a lot of + signs looks
like a regex so it is confusing (to me at least).
But see the comment below about Popen args.

> 
> proc=subprocess.Popen(cc, shell=True,stdout=subprocess.PIPE)
> res=proc.communicate()[0].strip()
> 
> 
> 
> ===
> error
> sed: -e expression #1, char 38: unterminated `s' command

My first instinct when dealing with subprocess errors is to set
shell=False to ensure the shell isn't messing about with my inputs.
What happens if you set shell false?

I'd also tend to put the sed arguments into a list rather
than pass a single string.

-- 
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 it is showing attribute error in line7

2016-10-29 Thread Alan Gauld via Tutor
Please always post the full error text in future.

Meanwhile I'll guess:


On 29/10/16 05:42, SONU KUMAR wrote:
> fname = raw_input("Enter file name: ")
> if len(fname) < 1 : fname = "mbox-short.txt"
> fh = open(fname)
> count = 0
> for line in fh:
>line=line.rstrip

missing parens means you reassign line to the method.

>if not line.startswith("From"):continue

The method does not have a startwith attribute.

>lst=line.split()

Nor a split method.

> 
>print lst[1]
> 
>count=count+1
> print "There were", count, "lines in the file with From as the first word"

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] looking for image library based on PIL Image

2016-10-30 Thread Alan Gauld via Tutor
On 30/10/16 15:32, Benjamin Fishbein wrote:
> I’m trying to automate a lot of images using PIL’s Image library, 
> but I don’t want to write all the filters and manipulation
> algorithms myself. Do you know of any good code that people
> have written that does this?

It depends on what kind of image manipulation you want.
You might find something on SciKit and there are libraries such
as Pymunk and and cgkit for 2&3D modelling.

And don't forget Imagemagick has Python bindings too,
Blender has a Python API while cgkit also comes with
bindings to Maya.

As for add-ons for Pillow (the v3 version of PIL) you should
ask on their dedicated forum. Last time I looked it was
fairly active.

-- 
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] Module webbrowser.os

2016-11-02 Thread Alan Gauld via Tutor
On 02/11/16 06:44, Palanikumar Gopalakrishnan wrote:
> After that i want to experiment with webbrowser.os  module, But dont know
> how to execute it.

webbrowser.os seems to just be a link to the standard os module.
So you should read the docs for os...and use the os module directly.

> So I use dir(webbrowser.os) to find some details. Then i
> tried the following
> 
> webbrowser.os(umask)
> 
> But It retruns the following error
> 
> *Traceback (most recent call last):  File "", line 1, in
> NameError: name 'umask' is not defined*

I'm not sure why because it works for me in both Python 2.7 and 3.4.
Which OS are you using? And which Python version?

But note that umask is a function so

webbrowser.os(umask)

returns a function reference. To get the umask value you must
supply one:

webbrowser.os(umask(0x777))

And the returned value will be the current umask() (Which you
should store and  restore when finished with the new umask)

-- 
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] Cluster analysis script error

2016-10-11 Thread Alan Gauld via Tutor
On 11/10/16 22:13, Mike Armson wrote:

> I am trying to run a script (attached) which determines the number of
> clusters of fixations within a set of eye movement data. The script says to
> enter the following command on python:
> 
> "python fixationClusters.py outputPrefix input clusterDistance"
> 
> I am getting a syntax error with the output command 

I'm guessing that you are trying to run  this from the
Python interactive prompt (>>>)?

In fact, you should run it from an OS shell prompt (you
don't say which OS but in Windoze thats a CMD prompt,
in MacOS the Terminal App and in Linux whichever of
the many Terminal apps you use...)

The clue is that you are getting a syntax error - which is
usually from Python, but the command begins with 'python'
which is how you call the interpreter from the OS.

I suspect the phrase "...enter the following command on python:"
is a little misleading, it should say something like
"enter the following command at an OS shell prompt"

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 Code Not Working

2016-10-11 Thread Alan Gauld via Tutor
On 09/10/16 21:39, jeremygaine...@gmail.com wrote:
> Everytime I run this it says test is not defined . I don’t understand. 

It means test is not defined - that is, Python doesn't know
about it. You call a function test() but there is no such
function built into Python, so it complains.

Presumably the test function is defined in a module somewhere,
in which case you need to import that function to make it
visible to python.


Can someone please help correct?

> def is_palindrome(myStr):
> if myStr in reverse(myStr):
> return True
> else:
> return False
> 
> test(is_palindrome("abba"))
> test(not is_palindrome("abab"))
> test(is_palindrome("tenet"))

-- 
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 dependencies in Anaconda

2016-10-11 Thread Alan Gauld via Tutor
On 10/10/16 16:54, David Wolfe wrote:

> Anaconda (using Spyder or a Juypter notebook), so the dependencies are
> included, so it's not an issue.  So, what I'm wondering is, are the
> dependencies that are included in Anaconda just contained in Anaconda, and
> not actually accessible in Python,

Anaconda is one of several specialist distributions of Python that
includes many modules not in the standard library, notably the
math/science related ones.

It is perfectly possible (although not entirely trivial) to
install all of the required dependencies manually into a
standard Python installation, but its tiresome and therefore
most folks working in that area will use a distribution like
Anaconda or Entropy.

The individual packages are mostly available on PyPI or on
the SciPy web site. They are also usually available on Linux
via the standard package management tools (apt-get, yum 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] Adding numbers within a string

2016-10-12 Thread Alan Gauld via Tutor
On 12/10/16 01:37, LQ Soh wrote:
> To whom it may concern,
> Can someone enlighten me as to how you can create a function such
> that sum_numbers('10 5 8'), when run, will give an answer of 23, without
> using str.split() and using a for loop

I'm assuming this is some kind of classroom exercise?
Otherwise the advice is just use string split()!

If it is a class  exercise then the easiest option
is to write your own string split(). That is a
function that takes in a string and spits out
substrings. To do that you need to traverse the
string and look for separators. Store the characters
between separators in a list. return the list.

Another way to do it is to use a regular expression
to detect the groups of characters - do you know
about regex?

Once you have done the splitting you need to
convert the substrings into numbers and add
them.

-- 
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] Need help

2016-10-12 Thread Alan Gauld via Tutor
On 12/10/16 09:03, niraj pandey wrote:

> Can you pls guide how to print this screen (Attached here) content in
> printer ?

As we already pointed out this is a text list so attachments
are usually stripped off...

However, printing from Tkinter is not easy. The simplest way is usually
to create an HTML file and use the OS to print that via a browser (many
browsers have a print command line option). It is possible to convert
your screen into a graphics file and print that, but the results can be
a bit unpredictable.

Alan G.

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


Re: [Tutor] Advise with coding

2016-10-11 Thread Alan Gauld via Tutor
On 11/10/16 10:16, tracey jones-Francis wrote:
> Is it possible someone on here can advise me where I am going wrong.

Yesm, thats what this list is for but...

We need to see code - we can't guess what you did.
We need to know what input you used, what output
you got and why its not what you expected.

Also provide the full text of any error messages
you get.

Finally it ioften helpsa to know which OS and Python
version you are using and, if applicable, what IDE
you are using to write/run the code.

If that seems a lot, it all helps to provide specific
answers. The more specific your information is, the
more specific our response can be,.

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

2016-10-16 Thread Alan Gauld via Tutor
On 15/10/16 23:48, Nicholas Hopkins wrote:
> Please tell me what is wrong with my code and how I can put an if else 
> statement 
> inside of another if else statement

You are almost right but...

> This is my code:
> path = input('Which path number will you take?')
> if path == '1':
>  print('You took the first path')
> elif path == '2':
>  print('You choose to take the second path')
>  print('You see a rock')
>   rock == input('Do you want to pick up the rock')

indentation is important in Python and the above line
should line up with the one above it. You should have
gotten an Indentation Error message.

>   if rock == 'yes':
>   print('you picked up the rock')
>   else:
>   print('You left the rock')

And if this clause lined up correctly too then it would
work as you expected.

> elif path == '3':
>  print('You choose to take the third path')
> else:
>  print('You must choose a number between 1 and 3')
> 
> 
> it comes up with this error
> [cid:image001.png@01D22792.63CCF290]

Please include the error in your message. This is a text
only list and attachments tend to get stripped off


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


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


Re: [Tutor] Adding numbers within a string

2016-10-12 Thread Alan Gauld via Tutor
On 12/10/16 17:58, D.V.N.Sarma డి.వి.ఎన్.శర్మ wrote:
> Sorry, I did not read the conditions that split and for should not be used.

It is even more confusing - split() may NOT be used
but 'for' MUST be used...

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


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


Re: [Tutor] Help on Software Design decisions

2016-11-29 Thread Alan Gauld via Tutor
On 29/11/16 02:02, Juan C. wrote:

>>> I have to build my own Moodle API to be consumed by my program,

I just noticed the last bit.
Is this a client side API or a server side API?
In other words are you building a set of services on the
server or are you building a module that makes it easy
for client side programs to access the server? I had
assumed the first but your responses make me think it
is probably the second.

> Well, basically get program information like title, id and units, within
> units get title, id and courses, within courses get title, id, assignments,
> and within assignments get title, id, due date and grade. 

For a client side API where you just populate the data that's not
unreasonable, the operations are more likely to be things like
open(), close(), read(), write()(), refresh(), etc.

> program to automate the process of getting assignments data and putting
> them on Trello and keep them up-to-date.

I've no idea what Trello is.

>> OK, Have you heard of CRC cards? These might be helpful here in
> 
> No, never heard about it...

They are a simple and concise way of recording requirements
(and some design) details for an OOP system. They may be less
useful in your scenario where you probably wind up with one
class doing most of the work and the others using it.

>>> - Inside Program init there would be attributes title, id and units;
> inside
>>> Unit init there would be attributes title, id and courses; inside Course
>>> init there would be attributes title, id, due_date, submitted, grade.
>>
>> The attributes are there to support the operations. What are the
>> operations (ie the responsibilities) of the classes. 

It doesn't sound like you know that yet. Once you have a
program to build using these classes you can add operations
to them. At the moment you are in the unfortunate position
of building a dumb API to some data. The functionality
you are hiding is infrastructure not application level.


>>> user = User('john.smith', 'password')  # will get all data needed
>>> user.program  # 

> Well, I'm trying to illustrate how the program would work. The parse would
> occur inside User, there I would call the site using requests and scrap
> data from it using bs4. I would get the username and password provided and
> use requests + bs4 inside User to login and keep session. 

OK, In that case you possibly want to call your class
Users since you seem to intend to fetch all User objects at once?
Or is the User ID doing double duty as a security token for
the server and as a key into the data? Or should it look like:

user = User(loginID, passwd, userID)

> The second line,
> and all of them for that matter, are just illustration. 

The problem is that they don't do anything. In the interactive
interpreter they would print the values but in a real script the
line

user.program

Does nothing useful, it would need to be part of an assignment:

program = user.program

But since program is itself a class do you need to go back
to the server to fetch that program data? Or are you going
to slurp it all up with the call to the top level user?
If you fetch it as needed then your program attribute
probably needs to become a method

program = user.program()

Where the method fetches the program details from the
server and returns a Program object.

-- 
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] function argument unpacking

2016-12-08 Thread Alan Gauld via Tutor
On 08/12/16 06:04, Palanikumar wrote:
> #Function Argument unpacking
> def myfunc(x, y, z):
>  print(x. v. z)
> 

Please always send the actual code that generates
the error, do not retype as it causes us to chase
phantom bugs. In this case the fact that the v
in the print statement should be a y and that
you are using periods as separators instead
of commas...

> File "func.py", line 8
>  tuple_vec = {1, 0, 1)
>  ^
> SyntaxError: invalid syntax

Change the opening brace { to a parenthesis (

-- 
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 scroll in Tkinter

2017-01-13 Thread Alan Gauld via Tutor
On 13/01/17 06:55, Ali Moradi wrote:
> https://paste.pound-python.org/show/CIKA8eOFbdq18r3nFUBv/
> 
> On Fri, Jan 13, 2017 at 10:25 AM, Ali Moradi  wrote:
> 
>> hi. I've written this code and i can't fix the scrollbar error. i am a
>> beginner in Python plz help. this is python3 code.

You've posted 70+ lines of code but no indication of the problem.
I'd suggest that you:

1) simplify your code to remove all irrelevant bits, that way
you can focus on what is actually the issue. So remove all
the sqlite query stuff and all the ttk styling stuff
 - unless the problem is the styling of course!

2) post the simplified code with a clear description of the
problem - what did you expect? what did you get? Were there
any error messages (you'll need to run it from a terminal to
see them)

By the time you remove the irrelevant stuff it should
be small enough to post within the email (using plain text)
which will encourage more people to look at it.

Please don't expect us to run code received from complete
strangers, especially since you've already told us its got
bugs in it!

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


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


Re: [Tutor] small remark

2017-01-11 Thread Alan Gauld via Tutor
On 10/01/17 17:56, adil gourinda wrote:
>When I was surfing in “Python Library” I made some observations and I want 
> to share them 

That's good and as a place to discuss those observations the
tutor list is a suitable forum. However, if you want the
proposals considered for actual implementation, you will
need to submit them via the bug tracker on python.org

> *date.replace(year=self.year, month=self.month, day=self.day)
> 
>… . For example, if "d == date(2002, 12, 31)", then "d.replace(day=26) == 
> date(2002,12, 26)".
> 
> ->change to:
> 
> *date.replace(year=self.year, month=self.month, day=self.day)
> 
> … . For example:
> 
>>>> d=date(2002,12,31)
>   >>> d.replace(day=26)
>   datetime.date(2002, 12, 26)

I see what you are getting at but I guess the current form is more
compact and that's why it was chosen.

> *date.weekday()
> 
> … . For example, "date(2002, 12, 4).weekday() == 2", a Wednesday. … .
> 
> →change to :
> 
> *date.weekday()
> 
> … . For example:
> 
>>>> date(2002, 12, 4).weekday()
>   2 (a Wednesday)

> Those are examples in script format that the reader can try

They are not really in "script" form, they are in
interactive interpreter form which is actually different
to when used in a script, but I guess that's what you
mean - that they can be typed at the interpreter.

Of course the existing examples can be typed at the interpreter
too, but they just return True...

>2) If we compare some methods between them we will find 
> some methods more generalized than others,
> So why we continue to use the latter :

There can be many reasons:
1) the specific method might be easier to use in the most common cases
2) the generalised method may be less efficient than the specialized
3) there may be a large body of legacy code that uses the specialised
version and it would be a lot of work to change it.
4) there may be subtle differences in the way the methods work for
certain data types

> * List.insert(i,x) vs List.append(x) vs List.extend(x) :
> 
>list.append(x) is restricted in the number of items in comparison with 
> list.extend(x) 

No, the both take exactly 1 item each. The item can be a list. but...
They do slightly different things. for example compare

lst = [0]
lst.extend([1,2,3])

lst2 = [0]
lst2.append([1,2,3])

If we were to get rid of append, say, then the use of
extend to replicate append's functionality gets a bit
ugly:

lst3 = [0]
lst3.extend([[1,2,3]])

> it is restricted in the position of items in comparison 
> with list.insert(i,x),

But you can't replicate extend() with insert() - at
least I can't think of a way. And even for appending, if
you don't know the size of the list you wind up with:

lst.insert(len(lst), data)

Which is both messy and slow.

> So I don’t see the utility of list.append(x) 

Appending is by far the most commonly used of
the three operations and append() is simpler and
it is faster - it doesn't have to do anything complex
like unpack its arguments(extend) or break open a
list and rearrange the contents(insert) it just
adds whatever it is given to the end.

> * For log function I suggest ...

I'm not familiar with the log functions but I suspect
performance of the most common scenarios may be the
reasons here too, but I'll leave others to comment
more fully.

Finally, it is probably possible to build optimised
versions of the general functions that would
recognise the special cases and treat them
differently. And if enough people ask for it somebody
may take the time to do it. But if you really want
it you need to discuss it via the official channels.

Python certainly does have a lot of redundant
functions - just look at how many ways there are to
start an external program (system/popen/command/
call/Popen/fork/exec etc...) And even when the docs
try hard to direct people to the recommended
option (like the subprocess module) many just
prefer the older ways because they know them,
or they are slightly simpler to 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] Importing classes

2017-01-11 Thread Alan Gauld via Tutor
On 11/01/17 02:53, kay Cee wrote:
> Is there a proper way to import  a class from a module? If so, please tell.


The most common way is probably:

>>> from mymodule import Myclass
>>>  myobject = Myclass()

but its just as good to do

>>> import mymodule
>>> myobject = mymodule.Myclass()



-- 
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] Convert tuple within tuple into single tuple

2017-01-11 Thread Alan Gauld via Tutor
On 11/01/17 06:31, ramakrishna reddy wrote:
> Hi All,
> 
> Is there any way to convert x = (1, 2, 3, (4, 5)) to x = (1, 2, 3, 4, 5) in
> python 2.7

You can write a function(*) to flatten the data structure,
but you need to be careful and think through how you
expect it to handle strings, say... or dictionaries?
Or user defined collection objects?

That's probably why there is no built-in method to flatten
a data structure.

Such functions are often recursive in nature looking
something like this list based example from my tutorial:

def printList(L):
# if its empty do nothing
if not L: return
# if it's a list call printList on 1st element
if type(L[0]) == type([]):
printList(L[0])
else: #no list so just print
print( L[0] ) # now process the rest of L
printList( L[1:] )

Obviously that prints rather than building a new list
but it should be fairly easy to modify it.

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


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


Re: [Tutor] Ran into a problem: Tried many different methods

2016-11-30 Thread Alan Gauld via Tutor
On 30/11/16 02:29, Parish Watteau wrote:
> A program that will read each player’s name and golf score as
> keyboard input, and then save these as records in a file named golf.txt.
> (Each record will have a field for the player’s name and a field for the
> player’s score.)
> 
> I attempted to solve it but ran into some errors from using some methods
> from a different python version but it didn't turn out the right way. 

OK, that tells us almost nothing.
Be specific.

What errors did you get?
Cut 'n paste the entire error message into your email.

Which particular methods were you using that gave problems?
What problems?

Which Python version are you using (and which OS)?

What does "it didn't turn out" mean?
What happened? What did you expect to happen?

> am stuck without a program and no where to start. 

Start with the basic problem and build up:

Can you write code that reads a player's name and prints it on screen?
Can you write code that reads a player's score and prints it on screen?
Can you write a program that does both of the above.
Can you write a program that reads say, 5 name and score pairs, printing
as it goes?
Can you write a program that repeatedly reads name and score pairs,
printing as it goes, until some end condition is reached  (an empty name
say)?

Can you write a program that writes a string to a
text file called 'golf.txt'?
Can you write a program that writes two strings to
a text file called 'golf.txt'?

Once you can do all of the above part-solutions you
just need to combine them.

Now tell us again what your specific problem is and we'll
try to help you out. But be as specific as you can, the more
detail you provide the easier it is for us to give you
specific answers.

-- 
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] copy files selectively from source to destination

2016-12-05 Thread Alan Gauld via Tutor
On 05/12/16 16:20, anatta anatta wrote:

> I however want to copy selective files.
> For example I like to copy only .txt files only 

> How could I do this selective copying?

By applying an if test just before you copy

filetype = '.txt'  # or read it as an input
...
if sourcefile extension == filetype
   copy sourcefile to destination

You can extract the extension using the
os.path module functions such as

splitext(p)
Split the extension from a pathname.

Extension is everything from the last dot to the end, ignoring
leading dots.  Returns "(root, ext)"; ext may be empty.
(END)


> if not os.path.isfile(newLoc):
> try:

The if test goes right about here... or you could
even put it higher up before all your tests.

> shutil.copy2(oldLoc, newLoc)
> print 'File ' + f + ' copied.'
> except IOError:
> print 'file "' + f + '" already exists'

An alternative option is to use glob.glob on the current
folder to get a list of files that match your desired
pattern and copy only those files.


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] Total newbie question

2017-01-04 Thread Alan Gauld via Tutor
On 04/01/17 06:51, MR ZenWiz wrote:

> It appears that while python is installed in /usr/bin, idle is in
> /usr/local/bin and expects the python interpreter to be also under
> /usr/local, which does not seem to be the default.
> 
> I created a symlink 'ln -s /usr/bin/python3.5
> /usr/local/bin/python3.5' and now idle comes up.

Did you install the idle-python3.5 package too?
That should have created a launcher in your menu system for idle.

On Ubuntu (and most Linux systems) you have to install "extra"
features like idle as packages. It's well worth browsing the
available python packages using synaptic, or whatever manager
you prefer.

-- 
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] Challenges with psycopg2 on Python 3.2

2017-01-06 Thread Alan Gauld via Tutor
On 06/01/17 12:55, Admire Mutsikiwa wrote:

> it screams on the Python3.2 prompt, it gives

Hardly screaming, rather a polite complaint that you've
messed up your indentation.

  import psycopg2
>   File "", line 1
> import psycopg2
> ^
> IndentationError: unexpected indent

I'll guess that you have a space or two in front of import.
Python is very fussy about spacing at the front of lines,
aka indentation.

-- 
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] Total newbie question

2017-01-03 Thread Alan Gauld via Tutor
On 03/01/17 01:21, MR ZenWiz wrote:
> I'm trying to install python 4.6 on my Xubuntu 16.04 desktop,

I assume you mean Python 3.6?
And my first question is why? Do you have some specific
features in 3.6 that you need? Otherwise just go with
the latest version in your package manager which will
probably be 3.4 or 3.5.

Both are stable releases and as a newbie should have
more than enough to keep you busy until packages
appear for 3.6. Seriously, life is too short to build
from scratch unless you really know you 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] prenting a line form appearing in log file

2017-01-05 Thread Alan Gauld via Tutor
On 05/01/17 13:01, anatta anatta wrote:

> I have created a log file, using 'logging' module, 

> name = raw_input ("Please enter your name.")
> print 'Hi ', name, 'Please go ahead and press enter to transfer files'
> 
> The log file records the variable 'name' in the log file at the 
> right location as I have coded.  So far so good.
> 
> However the log file also records the following statements 
> at the end of the log file.
> 
> Hi 'name', Please go ahead and transfer files
> 
> How can I prevent this line from appearing at the end of the logfile.

Its hard to tell what's happening without seeing your code.
If it is very long try creating a shirter example that
exhibits the same behaviour and post that. (Doing so may
even show you the error.)

But with the limited information you've given us, we are just
making wild 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] help :making window

2016-12-31 Thread Alan Gauld via Tutor
On 31/12/16 16:05, syafiqah amir via Tutor wrote:

>  Hello,Im trying to execute the code but the window does not come out.

Please always post python code in plain text, otherwise the html gets
wrapped and it becomes illegible.

> (script from Maya python for games and film)

This group is for core python language and library issues,
Maya is a bit off topic (although you may get lucky)
You would probably get a better response on the Maya
support fora:

http://forums.autodesk.com/t5/Maya/ct-p/area-c2

> I'm not sure what I did wrong

Nor me, and because the code is so mangled I can't
guess either...

> import maya.cmds as cmds;
> class AR_OptionsWIndow(object):def __init__(self):self.window 
> ='ar_optionsWindow';self.title='Options Window';
> self.size=(546,350);self.supportsToolAction=False;def 
> create(self):if cmds.window(self.window,exists=True):
> cmds.deleteUI(self.window,window=True);self.window = 
> cmds.window(self.window,title=self.title,widthHeight=self.size,menuBar=True); 
>self.commonMenu();cmds.showWindow()
> def commonMenu(self):self.editMenu=cmds.menu(label='Edit');   
>  self.editMenuSave=cmds.menuItem(label='Save Settings');
> self.editMenuReset=cmds.menuitem(label='Reset Settings');
> self.editMenuDiv=cmds.menuItem(d=True);
> self.editMenuRadio=cmds.radioMenuItemCollection();
> self.editMenuTool=cmds.menuItem(label='As 
> Tool',radioButton=True,enable=self.supportsToolAction);
> self.editMenuAction=cmds.menuItem(label='As Action' , radioButton=True 
> ,enable=self.supportsToolAction);
> self.helpMenu=cmds.menu(label='Help');
> self.helpMenuItem=cmds.menuItem(label='Help on '% self.title)
> 

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

2017-01-02 Thread Alan Gauld via Tutor
On 02/01/17 17:01, anatta anatta wrote:

> I am trying to create unsuccessfully source path as 
> a string 'str7' in part_1 of the code below,

When you say unsuccessfully what do you mean?
What do you expect? What do you get?

> to be used in part_2 of the code.

For that you need to expose it outside the
function, the best way to do that is to return
it as a value, which you comment suggests you
want to do. But the only return is commented out,
so you need to tidy that up.

But personally I think your function is trying to do
too much. You should simplify it to only return the
files and have another function that returns the path.
Functions that try to do too many things (ie more
than one) are notoriously difficult to debug.

> When I define the source path explicitly in part_2 
> of the code (#sourcePath = r'H://TCVFLDAT'), the
> code works right.

I'll take your word for it.

> How else could I find the path in part-1 and use it in part 2?

Return the value (assuming it is the right value)
and in part two assign the return from the
function to a variable.

For my analysis below I've removed all the flag
nonsense which is just cluttering things up for
now and gone with the ENDS_WITH option as
default

> def fetchFiles(pathToFolder, flag, keyWord):
>   
>   _pathToFiles = []
>   _fileNames = []
> 
>   for dirPath, dirNames, fileNames in os.walk(pathToFolder):
>   selectedPath = [os.path.join(dirPath,item) for item in 
> fileNames if item.endswith(keyWord)]
>   _pathToFiles.extend(selectedPath)
>   
>   selectedFile = [item for item in fileNames if 
> item.endswith(keyWord)]
>   _fileNames.extend(selectedFile)

You could simplify that by putting the selectedFiles
line before the selectedPath line and use selectedFiles
inside the comprehension.

>   
>   # Try to remove empty entries if none of the required files are 
> in directory
>   try:
>   _pathToFiles.remove('')
>   _imageFiles.remove('')

It would probably be better to check if they were empty
before putting them in. Since you use the endswith() test
I'm thinking there should never be any empty ones in
this scenario anyway?

>   except ValueError:
>   pass
>   

> #return _pathToFiles, _fileNames

Here is the missing return statement but it's not returning
what you said you wanted, ie str7


> #print _pathToFiles, _fileNames
> print 'path to first tuple file is:', _pathToFiles [0]
> str1 = ' '.join(_pathToFiles [0]) #convert tuple element 0 to string
> print 'length of str1 is: ', len (str1)

It might be wise to print the string itself to check
you have what you want, I'm not sure you do... But
I'm not really sure what you want since your code
logic is confusing me a bit here.


> str2 = str1.replace(" ", "") #remove white spaces

So why did you add it above? Why not just use an empty
string in the join?

However, more seriously, what affect does this have
on any paths/filenames that you found with spaces
in them? Is that really what you want?

> print 'str2 is', str2
> str3 = str2[13:16] #extract rgeistration
> print 'str3 is registration:', str3

I'll assume this is right since I've no idea what
format you think your filenames have. However, in general,
relying on fixed positions within a string is not a good
idea. This might be a valid case for using a regex which
can more flexibly match your pattern. But for now just
stick with the simple fixed values...


> str4 = 'FLDAT'
> print 'str4 is: ', str4
> str5 = str3.__add__(str4)

You shouldn't really call the dunder methods directly you
should use the + operator:

str5 = str3 + str4

Or, in this case, save a variable and use the literal:

str5 = str3 + 'FLDAT'


> print 'str 5 is: ',str5
> str6 = 'H://'
> print 'str6 is: ', str5

Did you really mean that? You've already printed str5.
And do you really need a double slash after the
drive letter? That's usually only needed if using
backslashes ('H:\\').

> str7 = str6.__add__(str5)

Again you could just use the literals:

str7 = 'H://' + str3 = 'FLDAT'

> print 'str7 is: ', str7  
> 
> fetchFiles('H://','ENDS_WITH','.FLD')

No assignment of any return value here

>  part_2  copying files from sourcePath to destPath
> 

> sourcePath = r'str7'

This assigns the literal string 'str7' is that what you want?
You cannot access the variable str7 that was inside the function.
It was a local variable and will have been destroyed by now.

> print 'Source path is: ', sourcePath
> destPath = r'c://test_o/'
> print 'Destination path is: ', destPath
> for root, dirs, files in os.walk(sourcePath):
> 
> #figure out where we're going

Re: [Tutor] Fw: path string

2017-01-04 Thread Alan Gauld via Tutor
On 03/01/17 15:59, anatta anatta wrote:

> Please disregard my request below.
> 
> I know the problem!
> 
> I have not defined the variable in question as a global variable.

That's one solution but its not a very good one.

Global variables are not considered good practice for many
reasons. In particular, they make code reuse difficult and
if you ever need to use your code in a multi-threaded
environment, to improve performance say, they are nearly
impossible to work with.

It's much better to pass the required value out of the function
as a return value.

> regret the inconvenience caused.

No inconvenience, its what the list is here for! :-)

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] Help with a Conversion

2017-01-05 Thread Alan Gauld via Tutor
On 05/01/17 13:29, S. P. Molnar wrote:

> Fortran II using punched paper tape.  Yes, am a rather elderly . .  .).

You are not the only one, there are at least 2 more of us on
this list that started in that era...

> short program to change frequency to wavelength for a plot of 
> ultraviolet spectra.  I have attached a pdf of the program.

This is a text list so attachments usually get stripped off.
Please post the code in the body of the email using plain text
formatting.

> To change the frequency to wave length I did the following:
> 
> p=1/1e7

p = 1e-7

> wave_length = p*np.array(frequency)

I don't really use numpy so don't know what that line does.
But assuming it applies the multiplication to each array element
I'd probably use:

wave_lengths = [p*f for f in frequencies]

or possibly

wave_lengths = map(lambda f: p*f, frequencies)

where frequencies was a tuple/list of frequency values.

However...

> (The relationship between wavelength and frequency is: wavelength = 
> 1.0e7/frequency, where 1e7 is the speed of light)

That formula doesn't look like the one you use above
if my guess is correct. That would look like:

wave_length = [1e7/f for f in frequencies]

ie positive exponent and division instead of multiplication

> Apparently what I have managed to do is divide each element of the frequency 
> list by 1/1e7.
> 
> What I want to do is divide 1e7 by each element of the freqquency list.
> How di I do this?

Rearrange the equation and use division instead of multiplication
I think that by calculating 1/p you have made things much more
complicated - unless there is some subtle arithmetic magic going
on that I'm missing?

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


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


Re: [Tutor] I download package and it says computer is missing this file, how do I fix?

2016-12-23 Thread Alan Gauld via Tutor
On 23/12/16 01:47, Don Pryor wrote:
> [image: Inline image 1]
> 
This is a text mailing list so the server strips out most attachments.
You need to tell us a lot more.
1) What package are you trying to install
2) How are you downloading/installing it(pip/ftp/binary installer?)
3) Which OS and Python version
4) Which file is missing

If you get an error message that you can copy/paste into
a mail that will help 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] How to interact with the result of subprocess.call()

2016-12-24 Thread Alan Gauld via Tutor
On 25/12/16 01:21, Jim Byrnes wrote:

> I am not trying to automate libreoffice using subprocess. 

No, but you are trying to automate LO from within Python
by sending it keystrokes and that's not easy. That's why I
previously asked whether you really wanted to open the LO
file directly and manipulate it from within Python
- that's (slightly) easier than manipulating LO directly
and much easier than manipulating LO from Python via
keystrokes.

> message I was told that subprocess was the way to open libreoffice from 
> a python script. 

Which is true if you want to bring up a LO session for
your user to manipulate. But it's not the way to drive
LO automatically. (One option is to start LO from Python
then use macros within LO to do the automation - there may
even be a command line switch to trigger a macro - I can't
remember off hand)

To drive LO via keystrokes your program needs to inject
key/mouse events into the LO event queue. That's not easy
and not very reliable either(*). There are some libraries that
can help but it should be the path of last resort.

(*)LO remembers its last screen setting and opens with them,
if those screen settings are different than the ones you
programmed for then navigation will be different and so on.
That's easy to deal with for a human who can see the screen
but sending keystrokes programmatically you are effectively
trying to drive the system blindfolded!

> Up until this point in the script I have used a combination of Selenium 
> and pykeyboard to log on to a web site and put some info in the 
> clipboard. Now I need to send keystrokes to libreoffice to paste from 
> the clipboard into the spreadsheet.

Or you could just open the spreadsheet file directly
and insert the data directly into it from Python. I think
there is a library for that - there are several for doing
it in Excel (so if your spreadsheet is in Excel format it
is fairly easy). Or, if you can use CSV format, its just a
standard library module.

Alternatively you can use the LO API to directly inject
the data into the spreadsheet objects (like using COM
in Microsoft land).

> I have used pyuno api to automate libreoffice in the past, but it was a 
> time consuming and confusing process.  

Trust me it is nowhere near as confusing and frustrating
as trying to drive LO (Or any other GUI) via keystrokes!

> I was trying this approach 
> because it looked like I could avoid the uno complexity.  

If there isn't a direct file manipulation library for LO
spreadsheets then UNO is probably the easiest option.


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


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


Re: [Tutor] formatting xml (again)

2016-12-27 Thread Alan Gauld via Tutor
On 27/12/16 19:44, richard kappler wrote:
> Using python 2.7 - I have a large log file we recorded of streamed xml data
> that I now need to feed into another app for stress testing. The problem is
> the data comes in 2 formats.
> 
> 1. each 'event' is a full set of xml data with opening and closing tags +
> x02 and x03 (stx and etx)
> 
> 2. some events have all the xml data on one 'line' in the log, others are
> in typical nested xml format with lots of white space and multiple 'lines'
> in the log for each event, the first line of th e 'event' starting with an
> stx and the last line of the 'event' ending in an etx.

It sounds as if an xml parser should work for both. After all
xml doesn't care about layout and whitespace etc.

Which xml parser are you using - I assume you are not trying
to parse it manually using regex or string methjods - that's
rarely a good idea for xml.


-- 
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 interact with the result of subprocess.call()

2016-12-25 Thread Alan Gauld via Tutor
On 25/12/16 01:58, boB Stepp wrote:

> the stdin option of call()might be used to direct the desired
> keystrokes to LO?  After looking at

The problem is that keystrokes in a GUI are not read from
stdin, they are read as events from the GUI event loop.
So, if LO was a CLI tool (like vim or top, say) then you
are right, you could pipe the keystrokes through stdin,
but in a GUI those keystrokes would never be seen (or
if seen do something very different to what is expected)

-- 
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 interact with the result of subprocess.call()

2016-12-25 Thread Alan Gauld via Tutor
On 25/12/16 17:08, boB Stepp wrote:

> Then I see that I have a GCE (Gross Conceptual Error) floating around.
> I thought that event loops are just intercepting the redirected stdin
> from the keyboard.  This is not true?  If not, then how is this
> working?

No event loops don't use stdin. They are monitoring the
hardware devices directly and creating event objects that
are put in a queue maintained by the GUI framework itself.
Most frameworks allow you create your own events and
inject them into the queue but they don;t come from stdin.
You could write a background thread that read stdin and
generated events from there but that's not normal by any
means. Some GUI programs will read stdin and process anything
found there but its usually a completely different set
of commands from those used by the normal user - and
even this is very rare.

For more exact detail of how GUIs get their input you
will need to investigate the individual GUIs, even
drilling down to X-Server level or the Windows API.

-- 
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] IndexError: list index out of range

2016-12-27 Thread Alan Gauld via Tutor
On 27/12/16 15:22, Mysore Ventaka Rama Kumar wrote:
> Please review and comment/correct my error!

Rather than expect us to read through many lines of code
it would help id you posted the entire error message
which will tell us exactly where the problem lies.

Also tell us for completeness  which Python version
and OS you are using.

-- 
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: Question about selenium with python

2016-12-22 Thread Alan Gauld via Tutor
On 21/12/16 01:29, Fazal Khan wrote:

> Im a new programmer and this is my first time posting here. I have a
> question about using selenium with python. 

I notice you haven't had an answer yet.
That may be because Selenium is not part of the
standard Python library and this list is for questions
about the core language and its standard library.

You may be better off asking on a selenium specific
list or forum. This page lists several options:

http://www.seleniumhq.org/support/

Meanwhile, this page may help with your specific
question:

http://selenium-python.readthedocs.io/navigating.html

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] Trouble Launching Python

2016-12-22 Thread Alan Gauld via Tutor
On 19/12/16 22:38, Joseph Olugbohunmi via Tutor wrote:
>  Hello,Good day, I installed Python 3.5.2 on my Windows 8.1 PC 

Are you sure you used the right Python version.
There are separate downloads for 32 and 64 bit machines.

It may be that you downloaded the 64 bit version and
have a 32bit OS running? I don't know if that would
give that error but it sounds like an OS type of issue.

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


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


Re: [Tutor] Using Python to solve factoria

2016-12-22 Thread Alan Gauld via Tutor
On 21/12/16 07:50, Hedgar wrote:

> I really happy to be accepted to the list!

You're welcome, but one very important thing to
note is that you should always post to this list
in plain text, not HTML. That's because HTML loses
the formatting of the code (see below) and in
Python formatting is very important.

> def factoria(numb):
> While numb > 1:
> If numb==0:
> return 1
> Else:
> result = numb*(numb-1)
> numb = numb -1
> return result
> factoria(5)

As you see we lost formatting, however this code
would never run because it is not valid Python.
Python is case sensitive so you need to use
'while' not 'While' etc.

> #should output 120
> What am I not getting right?

Another important point when postring is to
always include any error messages(in full)
that you get. They contain vital clues as
to what is wrong.

I see Bob Stepp has replied re the actual code,
so I assume his mail reader managed to interpret
it correctly - or maybe he just guessed. But
following the above guidelines will help you
get good answers more quickly in future.

-- 
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] Open a libreoffice calc file in Python

2016-12-22 Thread Alan Gauld via Tutor
On 22/12/16 03:37, Jim Byrnes wrote:
> Python 3.4 on Ubuntu
> 
> If I was going to open a libreoffice calc file from the terminal I would 
> go: libreoffice --calc /home/path/to/myfile.ods.
> 
> How would I do this from Python?

Others have advised how to run the Libreoffice app from
within Python.

If you really want to open the actual spreadsheet file
in Python rather than Libreoffice then its a bit more tricky.
If that is what you really meant get back to us and
we can start on the options available...


-- 
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] accessing attribute from python programming for absolute beginner

2016-12-26 Thread Alan Gauld via Tutor
On 26/12/16 04:08, syafiqah amir via Tutor wrote:
> i did not achieve the desired outcome which is the name of the critters did 
> not print 

> #attribute Critter#Demonstrates creating and accessing object attributes
> class Critter(object):"""A virtual pet"""def __init__(self,name): 
>print ("A new critter has been born!")self.name = name
> def __str__(self):rep= "Critter object\n"rep+="name: 
> "+self.name+"\n"return rep
> def talk(self):print("Hi.I'm, self.name ", "\n")
> #main  crit1 = Critter("Poochie")crit1.talk()
> crit2= Critter("Randolph")crit2.talk()
> print("Printing crit1:")print(crit1)
> print("Directly accessing crit1.name")print(crit1.name)
> print("\n\nPress the enter key to exit.")
> #A new critter has been born!Hi.I'm, 
> self.name  
> A new critter has been born!Hi.I'm, self.name  
> Printing crit1:name: Poochie
> Directly accessing crit1.namePoochie
> 
> Press the enter key to exit.

Please post in plain text because, as you can see, the code
is mangled when you use HTML. However in this case its
easy to spot the problem...

def talk(self):print("Hi.I'm, self.name ", "\n")

The second quotation sign should be after I'm, before the comma.
You probably don;t need the \n at the end since print() puts
one in by default.

-- 
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] Manipulating Dictionary values

2016-12-26 Thread Alan Gauld via Tutor
On 26/12/16 08:03, Sunil Tech wrote:
> Hi Team,
> 
> Dictionary is like
> 
> a = {'a': 'New', 'b': 'Two', 'l': [{'k': 'test', 'm': 'again'}, {'k':
> 'test', 'm': 'again'}]}
> 
> I am trying to modify a value in the dictionary value at a['l']

So make life easy for yourself and get rid of the outer dictionary
and use the python prompt to experiment:

>>> L = [{'k': 'test', 'm': 'again'}, {'k': 'test', 'm': 'again'}]
>>> [{'k':d['k'],'m':'replaced'} for d in L]
[{'k': 'test', 'm': 'replaced'}, {'k': 'test', 'm': 'replaced'}]
>>>

But that's not very general, you really should have a generator
for the dictionary that has a conditional expression within to
replace the m. But that means having a generator within a
comprehension inside a dictionary access.

It's all getting a bit ugly and overly complex and our goal as
programmers is to write clear, easily maintainable code, so
this is probably a bad idea.

Better to unroll into an explicit loop and make it obvious
what you are doing.

for d in a['l']: d['m'] = 'replaced'

Isn't that clearer?

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


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


Re: [Tutor] How to interact with the result of subprocess.call()

2016-12-26 Thread Alan Gauld via Tutor
On 25/12/16 16:33, Jim Byrnes wrote:

>> (*)LO remembers its last screen setting and opens with them,
>> if those screen settings are different than the ones you
>> programmed for then navigation will be different and so on.
> 
> I don't think I need to "know where stuff is" to manipulate LO. 

It depends on what you are doing. If you want to insert text
into a cell say you need to navigate to that cell.
In this respect a spreadsheet is much easier to work
with than, say, a word processor, but you still need
to be careful.

> some searching and found pykeyboard. Using it I was able to send Ctrl-A 
> and then Ctrl-C to copy the page to the clipboard.

I've never used (or even heard of) pykeyboard but it sounds
like its doing most of the hard stuff for you. It may well
work with LO.

> easier than diving back into Uno.  However, using subprocess seems to be 
> blocking me from sending any keystrokes to LO. 

subprocess has nothing to do with the keystrokes part
but you may need to run it in the background or somesuch
to get the keystrokes stuff working in parallel.

> subprocess well enough to know if it is actually blocking my keystrokes. 

No it's not blocking your keystrokes but it may well
be blocking your process.

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


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


Re: [Tutor] Using Class Properly - early beginner question

2017-03-23 Thread Alan Gauld via Tutor
On 22/03/17 12:30, Rafael Knuth wrote:

> I wrote a function that does exactly what I want, and that is:
> Create a shopping list and then let the user decide which items (food)
> are supposed to be instantly consumed and which ones stored.

That's a good start, because it means you understand your requirements.

> def ManageFood():
> create_shopping_list = []
> prompt = ("Which foods would you like to purchase?\nEnter 'quit' to exit. 
> ")
> food = input(prompt)
> 
> while food != "quit":
> create_shopping_list.append(food)
> food = input(prompt)
> 
> print("These are your foods on your shopping list: %s." % ", "
> .join(create_shopping_list))
> eat_food = []
> store_food = []
> for food in create_shopping_list:
> print("You bought this item: %s. " % (food))
> prompt = input("What would you like to do with it?\nEnter
> 'eat' or 'store'. ")
> if prompt == "eat":
> eat_food.append(food)
> elif prompt == "store":
> store_food.append(food)
> print("Food you want to eat now: %s." % ", " .join(eat_food))
> print("Food you want to store: %s." % ", " .join(store_food))
> 
> ManageFood()
> 
> PS: Please let me know if you have any suggestions how to write my
> code above in a shorter, more elegant fashion

The first thing to say is that shorter does not mean more
elegant, often more elegant code is shorter, but sometimes
its longer. Elegance is more about structuring the code
into clearly defined pieces, avoiding redundancy and
repetition and encouraging reuse. And it should be easy
to read and understand  too!

If converting from a function to classes its very common
for the classes to have a lot more code than the original
function. But you trade that for more reusable code.
Which begs the question of whether you need classes? - are
you likely to reuse the class? If not it may not be worth
the effort. (Although it might still be worth doing if it
clarifies the code and makes it easier to maintain - will
it be maintained? Or is it throw-away code?)

But let's assume this is just a training exercise and you
want to convert to OOP just for the experience.

> ... not sure if a pro would write it same way I did).

The answer is no, for several reasons, but probably not
the ones you expect!

> Besides that, I want to take it a step further and rewrite the
> function above as a class, and I don't know how exactly how to do
> this.

OK, I'll discuss one approach to this below, but there
are many OOP "methodologies", this is just one that I
personally find works for small/medium projects.


> (coding newbie pains ... I just learned the basics about classes in
> Python, but nowhere could I find examples of how to properly
> initialize classes, given that it operates solely with user input -
> same goes with with calling that class properly). 

There is a very important programming principle (not just
for classes) that says you should separate out the data
processing from the user interaction. So your initial design
concept is flawed - the first reason a pro would not write
your code the way you did.

So maybe you need a separate class (or just a function) to
represent the UI? That class can then interact5 with your
data models.

And talking about your data models...

Classes represent objects, things. Things that can do stuff.
So you should not normally have classes that *manage* other
things, the things should manage themselves. The exception
is when you have a container like your shopping list. The
list is a single thing (a class) that should manage itself.
It should control what goes in and out of the list but it
should not be manipulating its contents, it should be
providing access to its contents for the user of the list
to manipulate.

So it looks like we have maybe 3 kinds of object here.
1) The UI - could just be a function
2) The list - almost certainly a class
3) the items in the list - probably a class but we need
   to know more

To decide what these classes look like its often useful to
imagine that they already exist and think about how you
want to use them. (The formal way to do this is to
create a CRC card - Google it if interested)

Lets assume the UI is a function and that it is using
the other 2 classes.

The structure of our code is roughly:

# create and populate a FoodList
lst = FoodList()
while True:
item = input('What is the item? (quit to exit) ')
if item == 'quit': break
food = Food(item)
lst.add(food)

print(lst.contents())

# Separate thev list into eats and stores
eats = FoodList()
store = FoodList()
for food in lst.contents():
action = input('What action do you want for %s?' % food.name)
if action == 'eat':
   eats.add(food)
if action == 'store':
   store.add(food)

print('Items to eat now: %s' % eats.contents())
print('Items to store: %s' % store.contents())


Looking at that code we see that we have 3 lists of food.
We also see that a FoodList 

Re: [Tutor] Scrollbar

2017-03-27 Thread Alan Gauld via Tutor
On 27/03/17 17:22, Pooja Bhalode wrote:

> The scrollbar goes not work in the window. 

Define 'not work'?

You haven't connected it to anything and it doesn't
respond to any events so what kind of work did you
expect it to do? I assume it draws itself on screen
and the scroll buttons operate OK when you click them?

To make it do anything else you need to connect
it to a scrollable widget or bind some actions
to its events. Which Tkinter tutorial are you
using? It should have explained how to do that.

> from Tkinter import *
> 
> root = Tk()
> root.geometry("500x400")
> scrollbar = Scrollbar(root, orient = "vertical")
> scrollbar.grid(column = 5,sticky = W)
> 
> for i in range(0,20):
> Label(root, text = i).grid(row = 1+i, column = 1, sticky = W)
> 
> root.mainloop()


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


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


Re: [Tutor] Using Class Properly - early beginner question

2017-03-24 Thread Alan Gauld via Tutor
On 24/03/17 21:41, boB Stepp wrote:

>> I have a question: When creating an instance of GroceryListMaker, you are 
>> using:
>>
>> if __name__ == "__main__":
>>
>> What is that specifically for?

Its a common trick in Python that enables a single file to
act as both a module and a program. When a script is imported
Python sets its __name__ attribute to the name of the module.
When a script is executed directly Python sets its __name__
to __main__.

Thus

>> if __name__ == "__main__":
>> my_shopping_list = GroceryListMaker()
>> my_shopping_list.make_shopping_list()
>> my_shopping_list.display_shopping_list()

Means only execute the three indented lines if running the file
directly, do not execute them if the file is being imported.

Whereas:

>> my_shopping_list = GroceryListMaker()
>> my_shopping_list.make_shopping_list()
>> my_shopping_list.display_shopping_list()

will result in the three lines being executed regardless of
whether the file is imported or executed directly.

You will see this idiom in many files even when they
are not intended to be run directly because it is
common to create a tests or a demonstration that
will run when executed directly.

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] Using Class Properly - early beginner question

2017-03-24 Thread Alan Gauld via Tutor
On 24/03/17 21:42, boB Stepp wrote:

>> I noticed that you split your class into three methods:

Many real world classes have a lot more than 3 methods.

>> def __init__(self):
>> # initialize instances of class
>>
>> def make_shopping_list(self):
>> # input
>>
>> def display_shopping_list(self):
>> # output
>>
>> I was wondering what common practices are to structure a class?

I'm not sure exactly what you mean and there are no rules
but some programmers group related methods (as Bob did
albeit with only one method per "group")

Some possible categories:
- initialization/destruction
- input/output
- calculations
- event handlers (eg in a GUI)
- operations (eg __add__, __sub__, __str__ etc)
- (internal) helpers.

But others prefer to order their methods alphabetically.
Or to sort them alphabetically within the groups.

There are no hard and fast rules.


-- 
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] Retrieving DropDown List Values

2017-03-25 Thread Alan Gauld via Tutor
On 25/03/17 04:29, Braxton Jackson wrote:
> Is there a simple command for retrieving the chosen value a user inputs
> from a dropdown list? I am new to Python and cant seem to find a good
> tutorials link on retreiving drop down values.

That all depends on which GUI toolkit you are using.
The standard Python GUI is Tkinter but it does not
have a native drop-down list component, you need
to use the ComboBox from the ttk module (or the
ComboBox from the Tix module) for that. Alternatively,
you can use another third party version such as
the one in PMW. But these all work differently.

So first you need to tell us which GUI toolkit you
are using? And ideally, a bit more about what you
are trying to do?

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


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


Re: [Tutor] Function question

2017-03-25 Thread Alan Gauld via Tutor
On 25/03/17 10:01, Peter O'Doherty wrote:

> def myFunc(num):
>  for i in range(num):
>  print(i)
> 
> print(myFunc(4))
> 0
> 1
> 2
> 3
> None #why None here?

Because your function does not have an explicit return
value so Python returns its default value - None.
So the print() inside the function body prints the 0-3
values then the function terminates and returns the (default)
None to your top level print.

> def myFunc(num):
>  for i in range(num):
>  return i
> 
> print(myFunc(4))
> 0 #why just 0?

Because return always returns from the function immediately.
So you call the function, it enters the loop, sees the return for the
first element and exits. The print() then prints that returned value.

The preferred method to do what I think you were expecting is to build a
list:

def anotherFunction(num):
result = []
for i in range(num):
   result.append(i)
return result

Which is more concisely written using a list comprehension but
that would hide the general point - that you should accumulate results
in a collection if you want to return more than a single value.

To print the result you would typically use the string.join()
method:

print(' '.join(anotherFunction(4))


-- 
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] super constructor usage

2017-03-30 Thread Alan Gauld via Tutor
On 30/03/17 12:39, Rafael Knuth wrote:
 I am trying to wrap my head around the super constructor.
> 
> Is it possible to embed a super constructor into an if / elif
> statement within the child class?

Of course, the __init__ methods are special in any way
the normal coding mechanisms all work. If for some
reason you only want to call super some of the time
then by all means put it inside an if clause.

But remember that not calling super potentially leaves
some attributes of your superclass uninitialized. By not
calling super you assume full responsibility for
initializing both your sub class and the superclass.


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


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


Re: [Tutor] Help with function scoping

2017-03-23 Thread Alan Gauld via Tutor
On 23/03/17 10:15, Richard Mcewan wrote:

> #loop to check guess and report
> while userGuess != computerGuess:
>   if userGuess < computerGuess:
>   print('Too low')
>   userGuess = getUser()
>   elif userGuess > computerGuess:
>   print('Too high')
>   userGuess = getUser()

One tiny tweak would be to remove the userGuess = getUser()
lines from the if/elif structure and just have a single
assignment at the end of the loop. It just saves
duplication and so means less work if you ever have
to change that line.


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


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


Re: [Tutor] Help with function scoping

2017-03-22 Thread Alan Gauld via Tutor
On 22/03/17 21:17, Richard Mcewan wrote:

> I'm expecting two functions to be defined. Then called. 

And thats what you've got. But...

> One returns a random number. The other user input (guessing the number). 

And thats also what you've got but you don't do anything
with the returned value you just ignore it.

You need to assign the result to a variable.

> I expect the return values to act like variables that I can use in a while 
> loop. 

The return values are just values like any other.

Just as you can do

x = 42# assign the value 42 to the variable x

you can also do

y = myFunction()  # assign return value from myFunction to variable y

> ...The error report says 'NameError:The name 'userGuess' is not defined. 

Which is true, you use it but you never assign a value to it.
You need to do something like:

userGuess = getUser()

Although the name is poor since you are not getting
the User you are getting a number...

> My understanding is wrong somewhere. 

You are confusing values and variables.
Variables in Python are labels that we attach to values
(aka objects) so that we can refer to those values later
in our code.

> I thought functions would allow me to return values 
> I could use elsewhere without having to define them

They return values. But you need to assign those
values to variables to be able to use them.

> initially. I.e. Encapsulation. 

None of this has anything to do with encapsulation.
Functions encapsulate an algorithm and the data needed
to perform that algorithm, they return a value without
you needing to know how the value was worked out.
That is encapsulation.

> I've looked for other examples but get the same issue. 

The simplest examples are the built in functions,
such as pow() or len()

len('freddy')

Doesn't do anything(*) because we throw the result away.

L = len('freddy')

assigns the return value from len() to the variable L.

> I expect a function to return a variable I can use elsewhere. 

No, functions return values not variables.
You create the variables because its you
that will use them. How could the function possibly know what
you want to call the variable? It cannot, it just returns
the result of some operation or calculation. Only you know
what you are going to use that for, so you can create a
variable with a suitably descriptive name.

> In the case below I'm not sure how I can use the work of the function 
> elsewhere. 

Just assign it to a variable. Then use the variable.


-- 
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] super constructor usage

2017-03-29 Thread Alan Gauld via Tutor
On 29/03/17 15:33, Rafael Knuth wrote:
> I am trying to wrap my head around the super constructor. 

This is one of these cases where it matters whether you
are using Python v2 or v3. Use of super in v3 is much
easier. It looks from your examples like you are using
v2 but it would be good to confirm that.

> class A:
> def __init__(self):
> print("world")
> 
> class B(A):
> def __init__(self):
> print("hello")
> super(B, self).__init__()
> 
> B()
> 
> Then I changed the parent class A like this, as I wanted to test how
> the code would look like if I passed arguments:
> 
> class A:
> def __init__(self, message):
> self.message = message
> print(message)
> 
> I then modified the child class B like this:
> 
> class B(A):
> def __init__(self, message):
> print("This is the message from your parent class A:")
> super(B, self).__init__(message)
> 
> B("BlaBla")
> 
> That works, however I am not sure about what exactly happens inside the code.

Yes, you have the mechanism right.
As to what exactly happens inside the interpreter I'll leave
that for those who care about such things :-)

> What I am concerned about is whether the argument is being actually
> inherited from the parent class A or does B overwrite the argument.

The argument is just a parameter of the init() method like any
other argument. It is effectively a local variable. The self.message
attribute however is instantiated in A and inherited by B. (At least
conceptually. I'll let the interpreter gurus answer how it work in the
implementation)

Thus in B you could access self.message directly - and in a normal
method that might be the right thing to do. But in a
constructor/initializer you should leave the initializing
to super()


-- 
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] FUNCTIONS vs. CLASSES (early beginner questions)

2017-03-28 Thread Alan Gauld via Tutor
On 28/03/17 17:45, Rafael Knuth wrote:
> Question: When should I use functions?
> When should I use classes?

Thee is no definitive answer but here are some
guidelines:

1) Many instances -> class
2) Many methods sharing the same data -> class
3) An algorithm that has no side effects -> a function

Very often we start with a function then realize it
would be better in a class.

In general classes need more code but provide more
maintainable and reusable solutions. so on a bigger
project classes are likely to be a better option.

Pythons module/package mechanism is quite powerful
so often we don't need classes where other
languages would use them.

-- 
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] Merge Sort Algorithm

2017-03-28 Thread Alan Gauld via Tutor
On 28/03/17 15:56, Elo Okonkwo wrote:
> Can someone pls explain this Merge Sort Algorithm, 

You can try reading this generic explanation.
It's not Python but the explanation seems fairly clear.

http://www.personal.kent.edu/~rmuhamma/Algorithms/MyAlgorithms/Sorting/mergeSort.htm

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] super constructor usage

2017-03-31 Thread Alan Gauld via Tutor
On 30/03/17 21:08, Alan Gauld via Tutor wrote:

> Of course, the __init__ methods are special in any way

Should have said *not special* in any way...

> But remember that not calling super potentially leaves
> some attributes of your superclass uninitialized. By not
> calling super you assume full responsibility for
> initializing both your sub class and the superclass.

And it's worth reminding ourselves that there could be several
superclasses not just the one we immediately inherit from.

Finally, this discussion has been in the context of
constructors but super() applies to all methods. There is
nothing unique about construction, it's just like any
other method call where you want to include the
superclass functionality.

-- 
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 gtk serial loop thread readind data close

2017-03-31 Thread Alan Gauld via Tutor
On 30/03/17 13:40, Alexandru Achim via Tutor wrote:
> Dear users,
> I had a problem regarding Threads in python and Gtk3.

This list is really for the core language and library, I suspect you
might get a better response by asking on the PyGTK forum where there are
more likely to be people who have come across the same issues.

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


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


Re: [Tutor] All Entry Boxes taking the same value

2017-03-31 Thread Alan Gauld via Tutor
On 30/03/17 21:35, Pooja Bhalode wrote:

> *However, when I execute it, and type something in one entrybox, it shows
> in all the entry boxes using multi-cursor option. *

I'm not sure whats going on and don;t habe tome to experiment but one
thing I noticed:

> average = [" ", " ", " "]
> lowest = [" ", " ", " "]
> highest = [" ", " ", " "]
...
> for i in range(len(reactants)):
> *Entry*(root, textvariable =* average[i]*, width = 15,
> state=DISABLED).grid(row = 3+i, column = 1, sticky = W)

You are setting textvariable to a string but it should be
a StrinVar object. You could probably fix that by changing
your data definitions to StringVars:

average = [StringVar(), StringVar(), StringVar()]

I don't know if that will fix the problem but its probably
a good thing to do anyhow...


-- 
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] tiny, little issue with list

2017-03-19 Thread Alan Gauld via Tutor
On 19/03/17 12:17, Rafael Knuth wrote:
> LogActivities = []
> prompt = ("What have you done today? ")
> prompt += ("Enter 'quit' to exit. ")

I'm not sure why you put that on two lines but
thats just a nit pick...

> while True:

This will loop forever unless you explicitly break,
return or hit an exception. You should fix that.

> activity = input(prompt)
> LogActivities.append(activity)

You append activity regardless of what it is so
obviously you include the 'quit'.

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

Then after appending it you test to see if its
quit then print a message(but don;t actually
quit, see above)


To avoid the append you could put the test for
quit at the top of the loop and put the append
lines in an else:

if activity == 'quit':
   print # and break?
else:
   append


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] cx_Oracle and Pyinstaller

2017-03-14 Thread Alan Gauld via Tutor
On 14/03/17 14:29, Madhu Venkat wrote:

> try:
> Conn = cx_Oracle.connect (self.dsn)
> except cx_Oracle.DatabaseError as exception:
> 
> dsn has all the required connection info.
> 
> In this case, I believe I don't need TNSnames.ora file, please confirm.

I don't know about Oracle under Python but it sounds
reasonable. Hopefully someone else will confirm.

> In this case, do I place all script files along with the DLLs in
> c:\python2.7\ folder before I run the installer?

But this sounds wrong. Just to be clear...
Which specific installer are you talking about?
What exactly are you installing and how?


-- 
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] Summing arrays

2017-03-16 Thread Alan Gauld via Tutor
On 16/03/17 05:11, Aaliyah Ebrahim wrote:

> def sum2(N):
> 
> b = np.arange(1,N+1,1)
> mylist = [ ]
> for i in b:
> terms = 2*(1+3**(i-1))
> a = mylist.append[terms]
> return np.sum(mylist)

> terms = 2*(1+3**(i-1))> 9 mylist.append[terms] 10
> return np.sum(mylist) 11
> TypeError: 'builtin_function_or_method' object is not subscriptable

You are using [] to call append instead of ().
It should be
a = mylist.append(terms)

However, most of your function could be replaced by
a list comprehension:

def sum2(N):
mylist = [2*(1+3**(i-1)) for i in np.arange(1,N+1,1) ]
return np.sum(mylist)

And I'm not sure the np versions of the functions will
give much advantage over the standard range() and sum()

Any time you see a structure like

aList = []
for 
   aList.append()

You should consider whether a comprehension would
be more suitable

-- 
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] While condition

2017-03-17 Thread Alan Gauld via Tutor
On 17/03/17 14:46, Aaliyah Ebrahim wrote:
> Hi, in my code below, why is it returning a value that is greater than 1200
> if my condition is that the value should be less than 1200?

Your condition is that it be less than 1200 when it enters the loop
body. That means it will *always* be 1200 or greater when it exits the
loop. In this case n is 14 when it enters the last loop iteration so the
loop body does:

n = n+1 -> 15
term = n**2 -> 225
list_sum = list_sum + term -> 1240

That means that when it entered the loop the value was
1240-225 = 1015, which is less than 1200.

> def sum_list(val):
> list_sum = 0
> n =0
> mylist = []
> while list_sum < val:
> n = n+1
> term = n**2
> list_sum = list_sum + term
> 
> mylist.append(list_sum)
> return list_sum,n,mylist
> 
> print(sum_list(1200))
> 
> This is the output:
> (1240, 15, [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225])

Incidentally it looks as if your code actually did

 mylist.append(term)


-- 
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] CSV file Reading in python

2017-03-22 Thread Alan Gauld via Tutor
On 20/03/17 19:37, Edzard de Vries wrote:
> I have a CSV which I want to be able to read in Python. 

Are you using the csv module?
Have you read the documentation for that?
It gives several examples.

If not already then use csv. If you are using it
and still have problems send the code and errors,
otherwise we will just be guessing.


-- 
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] HTML module for Python

2017-03-22 Thread Alan Gauld via Tutor
On 20/03/17 22:09, ਪੰਜਾਬ ਪੰਜਾਬੀ wrote:

> Looking for recommendations on Python module to use to generate HTML
> pages/tables, other HTML content.  Kindly help.

While thee are some modules that help with this most Python
programs I've seen just generate the HTML directly as strings.
There is no direct equivalent of, say, Perl's CGI module.

However, if you are using a web framework, it will
generally provide a templating mechanism which will
separate out the HTML code  (the view) from your
Python code (the model and controller).

So if you give is more information about what the
HTML is being used for, we might be able to provide
more help. Is it part of a web application or just
a data file that you make available to some third
party?

-- 
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 do we create a GUI to run a simple calculation program in Python?

2017-04-04 Thread Alan Gauld via Tutor
On 04/04/17 17:55, Lisa Hasler Waters wrote:

> A middle school student of mine created a program to calculate simple and
> compound interest. He built it in PyCharm EDU using a Mac running 10.11.6.
> 
> He would like to create a GUI to run this program. Please, can you advise
> on how he could build this?

He could use Tkinter, or he could create an HTML screen and
write a small server using a Framework like Flask.

Whatever he does he will need to dsepsarate his UI from his
logic - a good programming skill regardless of UI.

So his first step should be to create a CLI UI on top of
his existing code such that none of hi functions contain
print() or input() statements, they should all be in
new UI code.

The next step is to convert it to event driven style.
For this code that should almost be a done deal.

Finally decide on his GUI/Web framework and do a tutorial
to get up to speed and fit his new event-driven backend
code into that.

> Here is his code:
> 
> def simple(m, t, r):
> r = r/100
> print("The interest is {} and the total is {} ".format(r*m*t, m+r*m*t))

Should return a value not print a message

> def compound(m, t, r):
> morg = m
> r = r/100
> for x in range(0, t):
> m = m*r+m
> print("The interest is {} and the total is {} if compounded
> yearly.".format(m-morg, m))
> m = morg
> r = r/12
> for x in range(0, t*12):
> m = m*r+m
> print("The interest is {} and the total is {} if compounded
> monthly.".format(m-morg, m))
> 

Possiobly should be two separate methods, and definitely
should be returning values not printing stuff.


> choice = str(input("Would you like to use simple or compound interest? "))
> m = int(input("Input the amount of money you would like to deposit
> (don't use the $ symbol): "))
> t = int(input("Input the amount of time you will be keeping your money
> in the bank (in years): "))
> r = int(input("Input the interest rate the bank offers (don't use the
> % symbol): "))
> 
> if choice == 'simple':
> simple(m, t, r)
> elif choice == 'compound':
> compound(m, t, r)
> else:
> print("Your input is invalid")

This needs to turn into a UI event loop which it almost is
but with no loop and no exit option.


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


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


Re: [Tutor] Validating String contains IP address

2017-04-03 Thread Alan Gauld via Tutor
On 03/04/17 19:43, Ed Manning wrote:

> untrust_ip_address = raw_input('\nEnter the  untrust IP ''"Example 
> 172.20.2.3/28"'':')
> while not ipaddress.ip_network untrust_ip_address:

Doesn't that give a syntax error?

-- 
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] Count for loops

2017-04-03 Thread Alan Gauld via Tutor
On 04/04/17 00:37, D.V.N.Sarma డి.వి.ఎన్.శర్మ wrote:
> I will go for this modification of the original code.

> count = 0
> b= '3'+b[2:]
> n = len(b)
> for i in range(n-4):
> if b[i:i+4] == get_year:
> count += 1

While I think this works OK, I would probably suggest
that this is one of the rare valid cases for using
a regex(*) with a simple string. The findall() method
with a suitable pattern and flags should catch
overlaps. And is probably faster being written in C.

(*)Assuming you want to include overlapping cases,
otherwise just use b.count()...

-- 
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] Count for loops

2017-04-04 Thread Alan Gauld via Tutor
On 04/04/17 12:04, Rafael Knuth wrote:
> Sarma: thank you so much, I checked your code, it works. However, can
> you enlighten me what it exactly does?

It just iterates over the PI string manually and compares
the birth date with the first 4 PI string characters.

It would probably be more pythonic and easier to read
to use startswith() instead

> count = 0
> b = "3"+b[2:]

I think this is to eliminate the period after the 3 of PI

> n = len(b)
> for i in range(n-3):
> if b[i:i+4] == get_year:
> count += 1

This is the core of it.
It starts with i = 0 and goes up to i = n-4
If b[i] to b[i+3] equals the birthdate you count
a match

You could rewrite it as

for i in range(n-3):
if b.startswith(get_year, i):
   count += 1

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] learning resources

2017-04-04 Thread Alan Gauld via Tutor
On 04/04/17 12:19, brian mituka wrote:
> what are the best learning resources for a beginner in python...

Look on Python.org and you will find a beginners page with
many links. But... it will depend on whether you can
already program in another language which beginners
page you go to.

I am, of coutse, biased, but you could try my tutorial,
linked below.

> I want to be able to write good code in ! month. 

Define "good code". An expert may tell you he is
still struggling to write good code after 20 years
of using Python. A beginner might tell an employer
that he writes good code after only a few days.

In reality, if you already know how to code in any other
language, you should be able to write productive code
within a week.

If you are a complete programming novice then a month
is probably ambitious!

-- 
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 would be good use cases for the enum module?

2017-04-09 Thread Alan Gauld via Tutor
On 09/04/17 13:58, Mats Wichmann wrote:

> All of these can of course be done without enums.  So the extra benefit
> of an enum is that the set is closed (immutable) and requires
> uniqueness: picking some other value will be an error, 

Indeed, good catch. The value of an enum over an integer is
that the values are limited to those prescribed by the enum,
any attempt to pass or create a different value will be an error.

-- 
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 entry box text changed event

2017-04-10 Thread Alan Gauld via Tutor
On 10/04/17 10:18, Phil wrote:

> def my_method(self.event):
> print("method called")
> 
> (self.event) is a syntax error and if I leave off "self", this is the result:

You want two parameters
self becaiuse its a method of a class so must have a self
event which is the event passsed by the GUI
So:

def my_method(self, event):
print("method called with ",event)


> I must be close, surely.

A comma instead of a dot...


-- 
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] Count for loops

2017-04-11 Thread Alan Gauld via Tutor
On 11/04/17 17:48, Rafael Knuth wrote:

> Pi_Number = str(3.14159265358979323846264338327950288419716939)
> Pi_Number = "3" + Pi_Number[2:]
> print(Pi_Number)
> 3141592653589793

> 
> How come that not the entire string is being printed, but only the
> first 16 digits?

There are two problems here.
First str() truncates the length of the output to make it look nicer.
Second your version of PI has too many decimal places for a floating
point to hold. Flosting point numbers can hold a huge range of numbers
but not a huge precision.


-- 
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] Count for loops

2017-04-11 Thread Alan Gauld via Tutor
On 11/04/17 19:44, Mats Wichmann wrote:

> import decimal
> 
> Pi_Number =
> str(decimal.Decimal(3.14159265358979323846264338327950288419716939))
> 

Unfortunately that doesn't work either:

>>> "   " + str(decimal.Decimal(
... 3.14159265358979323846264338327950288419716939))
'   3.141592653589793115997963468544185161590576171875'
>>>

Notice the output is both longer and has completely different
numbers in the last half of the result.


> topic. The decimal module documentation contains this pithy comment near
> the top:
> 
> Decimal “is based on a floating-point model which was designed with
> people in mind, and necessarily has a paramount guiding principle –
> computers must provide an arithmetic that works in the same way as the
> arithmetic that people learn at school.”

But sadly they haven't beat the problem of storing high precision
decimal numbers in binary storage.

-- 
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] Count for loops

2017-04-03 Thread Alan Gauld via Tutor
On 03/04/17 13:22, Rafael Knuth wrote:

> with open (file_path) as a:
> b = a.read()
> 
> get_year = input("What year were you born? ")
> 
> for year in b:

Can you explain what you think this loop line is doing?
I'm pretty sure it's not doing what you expect.

> if get_year in b:
> print("Your year of birth occurs in PI!")
> break
> else:
> print("Your year of birth does not occur in PI.")
> break
> 
> As a next challenge, I wanted to check how often a person's birth year
> occurs in PI. Unfortunately, I wasn't able to figure out how to use
> the loop count properly. 

What loop count?
There is none, its a for loop, no counter needed.
(OK I just spotted your code below...)

But there is a count() method on a string object that should help.


> count = 0
> for year in b:
> if get_year in b:
> count += 1
> else:
> print("Your birth date does not occur in PI.")
> break

> sum_count = sum(count)

sum() sums a sequence, but count is an integer. You have been
incrementing it as you go, the final value is already there.

-- 
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] Count for loops

2017-04-03 Thread Alan Gauld via Tutor
On 03/04/17 16:42, D.V.N.Sarma డి.వి.ఎన్.శర్మ wrote:
> Sorry. That was  stupid of me. The loop does nothing.

Let me rewrite the code with some different variable names...

>>> with open(file_path) as a:
>>> b = a.read()

with open (file_path) as PI_text:
 PI_as_a_long_string = PI_text.read()

>>> for year in b:

for each_char in PI_as_a_long_string:

>>> if get_year in b:
>>> count += 1

  if get_year in PI_as_a_long_string:
  count += 1

>>> print("Your birth date occurs %s times in PI!" % (count))

if count:
   print("Your birth date occurs in PI, I checked, count, "times!")


Aren't meaningful variable names great? We should all do
them more often.

-- 
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] Count for loops

2017-04-03 Thread Alan Gauld via Tutor
On 03/04/17 16:42, D.V.N.Sarma డి.వి.ఎన్.శర్మ wrote:
> Sorry. That was  stupid of me. The loop does nothing.
> 

On the contrary, the loop does an awful lot, just
not what the OP was expecting.

>>> with open(file_path) as a:
>>> b = a.read()

>>> for year in b:
>>> if get_year in b:
>>> count += 1

-- 
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] Count for loops

2017-04-03 Thread Alan Gauld via Tutor
On 03/04/17 16:07, D.V.N.Sarma డి.వి.ఎన్.శర్మ wrote:
> Modifying the code as shown below may work.

I doubt it.

> with open(file_path) as a:
> b = a.read()
> 
> get_year = input("What year were you born? ")
> 
> count = 0
> for year in b:

Once more I ask, what does this loop do?

> if get_year in b:
> count += 1
> print("Your birth date occurs %s times in PI!" % (count))

-- 
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] Asking about Run python script at Startup

2017-04-03 Thread Alan Gauld via Tutor
On 03/04/17 05:34, Quang nguyen wrote:

> I do not know how to run my python 3 script after my PI2 finished startup.

This might be a better question for a PI forum since it doesn't
seem to have anything directly to do with Python.

> the easy way to run at startup with escape plan?. 

You will need to define what you want more clearly.
Do you want your script to start as soon as the PI boots
up - before you login? Or do you want it to start as soon
as you login? Or do you want to start it manually as soon
as you finish logging in?

Also, if you are running a GUI then you must decide if
you want the script to start before or after the GUI
launches.

(BTW I have no idea what you mean by an escape plan?
Do you mean stopping the script when you hit Escape?
Ctl-C is the usual means of doing 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] Validating String contains IP address

2017-03-31 Thread Alan Gauld via Tutor
On 01/04/17 00:35, Ed Manning wrote:
> 
> What's the best way to validate a string contains a IP address 

It depends on how thorough you want to be.
You can define a regex to check that its 4 groups of numbers
separated by periods.

Or you can split the string into fields and validate that
the values are each less than 255

Or you could try connecting to it and see if you get a
response...

How sure do you need to be?

-- 
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] Euclidean Distances between Atoms in a Molecule.

2017-04-02 Thread Alan Gauld via Tutor
On 02/04/17 18:41, Stephen P. Molnar wrote:
> I am trying to port a program that I wrote in FORTRAN twenty years ago 
> into Python 3 and am having a hard time trying to calculate the 
> Euclidean distance between each atom in the molecule and every other 
> atom in the molecule.

Sounds highly specialized. Remember this is a general language
tutor group and very few of us even know what Euclidean
distances between atoms might mean let alone how to calculate
them.

You need to either ask on a more technical group (such as
the SciPy forum maybe?) or provide the context so we know
what you are talking about. Its easy for experts to forget
just how little the rest of humanity knows about their area.


>MASS X Y Z
> 0   12.011 -3.265636  0.198894  0.090858
> 1   12.011 -1.307161  1.522212  1.003463
> 2   12.011  1.213336  0.948208 -0.033373
> 3   14.007  3.238650  1.041523  1.301322
> 4   12.011 -5.954489  0.650878  0.803379
> 
> What I need for further calculation is a matrix of the Euclidean 
> distances between the atoms.
> 
> So far in searching the Python literature I have only managed 
> to confuse myself

Where are you searching and what for? You are very unlikely
to find any references to Euclidean maths in the standard
library of docs. You might find them in the SciPy forums.

What have you tried? How did it fail?

-- 
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] Startup Python

2017-04-12 Thread Alan Gauld via Tutor
On 12/04/17 13:47, Wim Berrelkamp wrote:

 a=2

Here you assign the number 2 to 'a'

 d=a+4
 print(d)
> 6
> a=input('-->' )

Here you assign whatever character(s) the user types to 'a'.
The fact that it looks like 2 doesn't change the fact that it
is really the character '2'. So you need to convert it to
a number using either int() or float()

a = int(input('-->'))
or
a = float(input('-->'))

> print(a)
> d=a+4
> print(d)
> 

> I tried to use float(), but nothing works.
> What am I doing wrong ?

I don't know, because you don't show us how you tried to
use float(), but if you apply it as shown above it
should work.

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


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


Re: [Tutor] Question to Phyton and XBee

2017-04-12 Thread Alan Gauld via Tutor
On 12/04/17 15:32, Daniel Berger wrote:

>For me it is not clear what is going wrong and I would be happy to get
>some help to solve the problem.

This list is for the core language and library, so while we
can help with installing third party packages that doesn't
mean anyone here will know how to use them. You might get
lucky and find somebody, but you are more likely to find
someone on a dedicated XBee support forum.

If both of those options fail then you can try the main
Python 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] Network Sniffing on Windows with Python 3.6

2017-04-07 Thread Alan Gauld via Tutor
On 07/04/17 06:07, Some Developer wrote:

> How would I go about writing a Python 3.6 script for Windows that would 
> sniff the network traffic and take the individual packets and then 
> reassemble them into something that is useful data?

That is definitely possible using Python although it is fairly advanced
networking code. Certainly further than I've ever gone using Python.

> I was thinking of installing Wireshark to have a look at the network 
> communications but I wasn't really sure what I would do with the data. 
> Are there any library functions in Python 3.6 that would help with this 
> task?

For sure, but I'd definitely install wireshark, if nothing else
its likely to be near essential in debugging your code.

> Also does the Python script require admin permissions for this to work 
> or can it run as a normal user? It doesn't matter if it does require 
> admin permissions but it would be better for my users if it didn't 
> require admin permissions.

That's more likely to be a feature of the OS and who is running the
code producing the data. Unless everything is running as your
user account I'd suspect admin privileges will be necessary
 - in fact I'd hope so!
> there are any books on the subject that would be even better as I like 
> reading books on programming subjects.

My two main sources for Python networking are:

Python Network Programming by Goerzen, published by APress
This is a great intro to the general theory of network programming
as well as the Python specifics. If you are already familiar with
networking through say, the classic Stephens books on C networking, then
this will be familiar ground. Its good if you want to
understand what you are doing rather than just copy somebody
else's code.

Programming Python 4th edition.
A monster book (1600 pages?) with about 500 pages dedicated to
networking. It's a book within a book! A bjt less background theory,
more code. If you like books this is a great value buy since it
also covers GUI/Tkinter(400 pages) and  Systems programming
(200 pages) as well as miscellaneous other topics.

-- 
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 grid question

2017-04-07 Thread Alan Gauld via Tutor
On 07/04/17 11:08, Phil wrote:
> ...In this case I become confused because had expected [][] 
> to be the same as a C two dimensional array.

It is, sort of.
If you set the data up correctly 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] [Python 3.5] TypeError: a bytes-like object is required, not 'str' PICKLE

2017-04-07 Thread Alan Gauld via Tutor
Please always send the full error trace not just the last line. The
message is full of useful details which we can't currently see.



On 07/04/17 09:28, Allan Tanaka via Tutor wrote:
> Hi
> I have added b so that it translates into bytes object. save_cPickle part is 
> not problem...
> But i still get an error when coming into load_cPickle for this function: 
> Dataset.save_part_features('categorical_counts', 
> Dataset.get_part_features('categorical'))
> although i have defined b in save_cPickle
> 
> THE CODE:
> import _pickle as cPickle
> def save_cPickle(filename, data):
> with open(filename, 'wb') as f:
> cPickle.dump(data, f)
> 
> 
> def load_cPickle(filename):
> with open(filename) as f:
> 
> return cPickle.load(f)
> 
> class Dataset(object): 
> 
> part_types = { 
> 'id': 'd1', 
> 'loss': 'd1',
> }
> parts = part_types.keys() 
> 
> @classmethod 
> def save_part_features(cls, part_name, features): 
> save_cPickle('%s/%s-features.pickle' % (cache_dir, part_name), features) 
> 
> @classmethod 
> def get_part_features(cls, part_name): 
> return load_cPickle('%s/%s-features.pickle' % (cache_dir, part_name))

Does the class add anything here given it only has two class
attributes and two class methods? If you aren't going to create
instances then a simple module level function is probably as useful.

> Dataset.save_part_features('categorical_counts', 
> Dataset.get_part_features('categorical'))
> Dataset(categorical_counts=train_cat_counts).save('train')

This tries to create an instance of Dataset but there is no matching
init() method...nor is there a save() method. ???

-- 
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 grid question

2017-04-07 Thread Alan Gauld via Tutor
On 07/04/17 03:09, Phil wrote:
> Thank you for reading this.
> 
> This is my first attempt at using Tkinter and I've quickly run into a problem.
> 

Peter has already answered the problem but I'd like
to point out how he used the interactive prompt >>> to
demonstrate what was going wrong. You should get into
the habit of always having an interactive shell running
while you code, then you can instantly answer questions
like this by copying code from your script into the shell
and seeing the output.

The shell is a vastly underused piece of pythons
programming environment, its not just for beginners
to learn on, it can greatly speed up your coding workflow.

Anytime you wonder what a particular method does,
or what a data structure looks like, just type it
into the shell and find out. No more guessing.

-- 
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] Question about loop and assigning variables

2017-04-05 Thread Alan Gauld via Tutor
On 05/04/17 20:07, Fazal Khan wrote:

> assign different variables with each loop

You can't, but you can fake it...

> def BeamInfo(x):
>   for Bnum in x:
> if plan1.IonBeamSequence[Bnum].ScanMode == 'MODULATED':
> TxTableAngle =
> plan1.IonBeamSequence[Bnum].IonControlPointSequence[0].PatientSupportAngle
> print(TxTableAngle)
> else:
> None

> Ideally what I want is this: when Bnum is 0, then "TxTableAngle" will be
> appended with "_0" (eg.TxTableAngle_0). When Bnum is 1 then TxTableAngle_1,
> etc. How do I do this in python?

Use a list (or a dictionary if the values are not sequential or numeric)

So
TxTableAngle_0 -> TxTableAngle[0]
TxTableAngle_1 -> TxTableAngle[1]

It's one extra character but hopefully that won't be too painful...

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


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


Re: [Tutor] (no subject)

2017-04-09 Thread Alan Gauld via Tutor
On 09/04/17 11:42, shubham goyal wrote:
> Hello, I am a c++ programmer and wants to learn python for internship
> purposes. How can i learn the advanced python fast mostly data science
> packages, I know basic python.

There are tutorials on most things.
But it depends on what you mean by advanced python. The ScyPy and NumPy
type stuff is certainly for advanced users of Python but mostly the
Python itself is fairly standard. To me, advanced Python means messing
around with metaclasses, decorators, functools, itertools and the like.

But thee are so many niche areas where Python is used its almost
impossible to recommend any single direction. Once past the basics
its a case of specializing in a given domain.

The biggest jump for most C++ programmers is giving up on type safety.
C++ has strict typing embedded as a religious dogma that it can seem
very strange for a C++ programmer to rely on dynamic typing and trust
that the system will just work. It was one of the things that surprised
me - that by giving up strict typing my programs were no less reliable.
But that understanding does change the way you design and think about
code - and, in particular, how you design and use objects.

-- 
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 function calls

2017-04-10 Thread Alan Gauld via Tutor
On 10/04/17 08:55, marcus lütolf wrote:
> Dear experts,
> I have written the following code for motion detection with a PIR sensor
> with a function and
> I need to count how many times the funtion is called, but I get a traceback:
> 
> #!/usr/bin/python3
> import sys, time
> import RPi.GPIO as gpio
> 
> gpio.setmode(gpio.BOARD)
> gpio.setup(23, gpio.IN)
> count = 0
> def mein_callback(pin):
> count += 1
> print('PIR 1 aktiviert', count)
> return

> UnboundLocalError: local variable 'count' referenced before assignment
> ^CPIR deaktiviert


You are trying to modify a variable defined in the module or
global scope. To do that you must tell Python that it is
the global variable you mean. You do that by adding

global count

at the top of your function:

def mein_callback(pin):
global count   # use the global variable
count += 1
print('PIR 1 aktiviert', count)
return

You don;t need the return since Python returns None automatically
at the end of a function. But it doesn't do any harm either...

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] Count for loops

2017-04-08 Thread Alan Gauld via Tutor
On 08/04/17 13:49, Rafael Knuth wrote:

>> b = "3"+b[2:]  #Removing the decimal point so that there are digits only in
> 
> my_number = 3.14159

Here you assign a floating point number to mmy_number but
the code Sama wrote was for working with strings read
from a text file.

You would need to convert it first:

my_number = str(3.14159)

> my_number = "3"+my_number[2:]
> print(my_number)
> 
> This is the error code I got:
> 
> == RESTART: C:/Users/Rafael/Documents/01 - BIZ/CODING/Python Code/PPC_56.py ==
> Traceback (most recent call last):
>   File "C:/Users/Rafael/Documents/01 - BIZ/CODING/Python
> Code/PPC_56.py", line 2, in 
> my_number = "1"+my_number[2:]
> TypeError: 'float' object is not subscriptable

And that is what the error tells you, that you are trying
to index a float but it should be a string.

> In case of a text file, your code works, but if I apply the same to a
> float assigned to a variable, it does not work.

That's right, the set of operations applicable to numbers is
completely different to those applicable to strings, you cannot
mix 'n match. You need to convert between the types.

-- 
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 entry box text changed event

2017-04-10 Thread Alan Gauld via Tutor
On 10/04/17 05:43, Phil wrote:

> I would like a function to be called when I enter text 
> and then tab to the next entry box.
One of the things about Entry boxes is that they are extremely
flexible and have many event types associated with them.
The consequence of this is that you as a programmer need
to be very, very specific in deciding which events you
want to bind to:

Enter text includes events such as key-press,
key-release. These catch individual keystrokes.

Then there are the navigation bindings such as focusIn
and FocusOut for entering and leaving the Entry(regardless
of whether you change anything.

And of course you have mouse events to consider too.

And you also have the StringVar() mechanism which auto
detects changed values and assigns them to the nominated
textvariable.

So do you want to trigger your code when keys are pressed?
or when the user leaves the box? or when the user arrives
in the next box? And do you only want to do this when the
user is tabbing around in sequence? Or what if they
randomly select one of the entry boxes using the mouse?
What if they use the mouse to select boxes rather than
the tab key?

Once you know that you will know which event types you
want to bind to. But 'StringVar()' is not one of them...

-- 
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 would be good use cases for the enum module?

2017-04-09 Thread Alan Gauld via Tutor
On 09/04/17 04:00, boB Stepp wrote:

> understandable to me, but I am having difficulty imagining where I
> might want to use these features.
> 

Steven has given the basics, here are a few more real world examples:

Any kind of status value:
(open,closed,opening, closing,locked)  - control valve
(on, off) - light
(red,green,amber,red-amber) - uk traffic light

small collections:
days of week
months in year
(cleaning, reception, waiting, valet) - rota duties
(hourly,daily,weekly,monthly,annual) - schedules

Enums are very common in larger programs once you get
used to the concept. It's a bit like dictionaries: many
traditional programmers think of everything as arrays
and can't initially think of when they would use a dictionary
(arbitrary key rather than numeric index) But once you
get started you find dictionaries are at least as useful
as arrays..

And, surprise, surprise, there is a link. Very often
enums form the set of valid keys to a dictionary...

-- 
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] sorted function

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

> sorted function is not working when i am trying to sort the list of strings
> but list.sort() is working. can you please help me understand.

sort() sorts the list "in place". That is it sorts itself.
sorted() returns a sorted copy of the list. It does not
alter the original list

> def front_x(words):
>   ls=[]
>   ls1=[]
>   for str in words:
>   if str[0]=='x':
>   ls.append(str)
>   else:
>   ls1.append(str);
>   sorted(ls)
>   sorted(ls1)

So here you should either do this:

ls.sort()
ls1.sort()

or this:

ls = sorted(ls)
ls1 = sorted(ls1)

In this case I'd suggest the first version is better.


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


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


Re: [Tutor] creating .json files

2017-04-13 Thread Alan Gauld via Tutor
On 13/04/17 17:32, Rafael Knuth wrote:
> Is there a way to split these two into separate steps:
> a) creating a .json file
> b) manipulating it (a, r, w ...)

Of course.

> What if I just wanted to create a .json file and do nothing with it?
> 
> import json
> file_name = "my_numbers.json"
> 
> The above does not do the job. What am I getting wrong here? Thanks.

The above creates a variable called file_name that stores a string.
It has nothing to do with any files.

You need to open the file to create it:

with open(file_name,'w') as json_file: pass

Will open a new file and immediately close it again.

You could do the same explicitly with

json_file = open(file_name,'w')
json_file.close()

Remember that variable names are just labels for your benefit.
The fact that you call it file_name means nothing to Python,
you might as well call it xcdseqplrtyg123 so far as Python is concerned,
its just a lablel. The name is only meaningful to
you (and possibly to other human readers).

Similarly, although your string looks like a file name to
a human reader, to Python it's just a string of characters.
Python cannot draw any meaning from that.

Finally, the code above creates a new file called my_numbers.json
But it is an empty file and is NOT a json file, despite the name.
It only becomes a json file once you add some json data to it.
open() creates text files, it has no understanding of what the
data you write to those files means.

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] Need help with code

2017-04-17 Thread Alan Gauld via Tutor
On 16/04/17 18:26, Tyler Seacrist wrote:

> I need to draw a stack diagram for print_n 
> called with s = 'Hello' and n=2 and am unsure of how to do so.

Me too.

What is print_n?

Which stack?
One in your program or the interpreters internal stack?

We need a lot more detail.

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


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


Re: [Tutor] Using Modules

2017-04-15 Thread Alan Gauld via Tutor
On 15/04/17 09:33, Aero Maxx D wrote:

> With Python I'm not finding which modules I need 

Search for the functionality within the python.org site.
The documentation tells you which module you are looking for.

> ...I thought I'd connect to a MySQL database 

There is a standard DB interface in Python for SQL based data.
But there is a separate module for each database. The idea
being that you should theoretically be able to write the code
that uses the database and then change the database from, say,
MySql to Oracle by just changing the import.

In practice it's not quite that easy but you should be able
to do it with only minor tweaks - usually around the login process.

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 do we create a GUI to run a simple calculation program in Python?

2017-04-15 Thread Alan Gauld via Tutor
On 15/04/17 03:38, Alex Kleider wrote:

>> Whatever he does he will need to separate his UI from his
>> logic - a good programming skill regardless of UI.
> 
> Can anyone suggest a good tutorial that explains exactly what this means 
> and how to achieve it?
> (separate UI from logic I mean.)

I don't know of a tutorial as such but the principles are enshrined
in the Model-View-Controller (MVC) design pattern and there are lots
of articles and tutorials on that. One caveat is that there are
almost as many variations on MVC as there are articles so you can expect
some contradiction in the details. That's ok, just focus
on the big ideas.

At the most basic just do as I suggested in the post. Identify the
functions that do the work(the logic) and make sure they take all
of their input via parameters and deliver a result back to the
caller with no UI (eg input() or print()) statements inside
the function.

Then write the code that interacts with the user as a separate
function which calls the logic functions as needed. You should
be able to put the core functions into a separate module and
import that into the UI module/main program. That's quite a
good check that you have made your logic reusable.

This is good practice for all programming projects but its
essential for GUI and Web projects.

Finally, if you can find a copy of my recent book "Python Projects"
there is a rolling project within that which demonstrates how
the same logic code can be used to build a CLI, a GUI and a
Web app. [ In fact it goes even further by demonstrating how
to break an app into 3 tiers - data, logic and UI - which
is industry best practice, but usually overkill for small
projects.]

-- 
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] Do not understand code snippet from "26.8. test — Regression tests package for Python"

2017-04-17 Thread Alan Gauld via Tutor
On 17/04/17 05:01, boB Stepp wrote:

> Am I missing anything?  If not, then why did the code snippet use the
> (I believe to be misleading.) class variable approach with "func =
> mySuperWhammyFunction" and "self.func(self.arg)"?

I suspect it was a slightly broken attempt at reuse in that
you can assign other functions to the class variable func.
In your code the function is hard coded into the test_func()
method. The original code (apart from using self.func) allowed
the mixin func attribute to be reset to different functions.

But I'm guessing at the authors intent, it may just have
been over-engineering...

-- 
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 layout question

2017-04-20 Thread Alan Gauld via Tutor
On 20/04/17 10:33, Phil wrote:

>> So, for a Suduko grid put 3x3 Entry boxes into a Frame.
>> Then put 3x3 such frames into another frame.
> 
> OK, so I'll go back to my original idea and use edit boxes. A grid of 9 x 9 
> edit boxes does actually work and it makes it easy to keep track of the 
> digits. The first digit is [0,0], the first digit on the second line is [1,0] 
> etc. 

Nine 3 x 3 boxes could add some complication to digit tracking.

Its not too bad you can map the large 9x9 table to the smaller units
using divmod()

So the 7th element becomes
divmod(7) -> 2,1

ie. element 7 maps to the 2nd cell, element 1
You can create a simple helper function that takes an x,y pair from
the 9x9 view and returns two pairs identifying the cell coordinates.

And having the smaller 3x3 cells works when checking that each 3x3
cell has the 9 unique numbers too.

> I did actually get my canvas version to the point where I could 
> enter digits into the cells but I had to enter them in sequence

Yes, that's exactly the kind of problems you hit and its a
terrible user experience. Far better to use the facilities
the GUI gives you for free. For example tab will move the
cursor from cell to cell etc.

> Thank you for the table example. I'm not sure what "tab = DisplayTable" 

It creates an instance of the table.

tab = DisplayTable(top,   # the containing widget/frame
  ["Left","Right"],   # table headings
  [[1,2], # The table data, 3x2 items
   [3,4],
   [5,6]],
  datacolor='green')  # the color used to draw the data

Note:
the constructor allows other colours to be specified too
such as the headings the grid lines and the cell background.
You may want to hard code those in a simplified version of
my class.


Hopefully when you run it you'll understand, especially
if you tweak the example instance options. For example
here is a full featured version:

tab = DisplayTable(top,
   ["Left","middle","Right"],
   [[1,2,1],
[3,4,3],
[5,6,5]],
   datacolor='blue',
   cellcolor='yellow',
   gridcolor='red',
   hdcolor='black')


If still confused drop a question here.


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


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


<    1   2   3   4   5   6   7   8   9   10   >