Re: [Tutor] Given a string, call a function of that name

2017-05-17 Thread boB Stepp
On Wed, May 17, 2017 at 1:42 AM, Peter Otten <__pete...@web.de> wrote:
> boB Stepp wrote:

>> Oh, and I suppose I should ask for a critique of the code as written
>> for appropriate Python style, proper targeted function use, etc.  I am
>> always eager to learn!
>
>> if function in valid_fcns:
>> return True
>> else:
>> return False
>
> should really be spelt
>
> return function in valid_fcns
>
> and personally I wouldn't mind to type the few extra chars to make it
>
> return function in valid_functions

[snip]

>> Hmm.  It bothers me that in check_fcn_input() I have a list valid_fcns
>> and in run_fcn() I have a dictionary fcn_dict.  These contain
>> essentially the same information.  Would this be a case for a global
>> function dictionary (Which I could also use to check for valid
>> functions.) or perhaps a class which only exists to have this function
>> dictionary?
>
> A global is indeed better than the duplicate information in your list and
> dict. Here's another option, return the function instead of information
> about its existence:

I keep forgetting that this is doable!  I like this idea and
implemented it.  Here -- for posterity and/or further critiquing -- is
my revised code:

=
#!/usr/bin/env python3

def spam(phrase):
print('spam function said: ', phrase)

def ham(phrase):
print('ham function said: ', phrase)

def eggs(phrase):
print('eggs function said: ', phrase)

def get_input():
function_name = input('Which do you want:  spam, ham or eggs?\n')
phrase = input('\nHow do you want your food to be prepared?\n')
return function_name, phrase

def find_function(function_name):
valid_functions = {'spam': spam, 'ham': ham, 'eggs': eggs}
function = valid_functions.get(function_name)
return function

def main():
while True:
function_name, phrase = get_input()
function = find_function(function_name)
if function:
break
print("You made an invalid food choice!  Let's try this again!")
function(phrase)

if __name__ == '__main__':
main()
=

I cleaned up the naming a bit.  I think it reads more clearly now, and
spells out "function" fully.  Also, the overall LOC is fewer, while
retaining the same functionality.  Thanks Peter and Alan!!

BTW, my son is now merrily calling his functions using this dictionary
technique.  He seems to like it and said that he now understands both
functions, returns and dictionaries better after adapting these ideas
to his own code.  Now if I can only get him to adopt unit testing and
version control!



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


Re: [Tutor] Python Image Library

2017-05-17 Thread eryk sun
On Thu, May 18, 2017 at 1:58 AM, Michael C
 wrote:
> when I run this, while it's called test.pyw, this pops up
>
> from PIL import Image
>
> im = Image.open('1.bmp')
> im.show()

Ok, I stand corrected. It's something weird, and most likely due to
Windows support here being an afterthought throw in just for coverage,
instead of something anyone actually cared about. The code does indeed
use os.system to show the file, which is just about the worst thing
one can do here for a Windows viewer.

>>> print(inspect.getsource(ImageShow.WindowsViewer))
class WindowsViewer(Viewer):
format = "BMP"

def get_command(self, file, **options):
return ('start "Pillow" /WAIT "%s" '
'&& ping -n 2 127.0.0.1 >NUL '
'&& del /f "%s"' % (file, file))

>>> print(inspect.getsource(ImageShow.Viewer.show_file))
def show_file(self, file, **options):
"""Display given file"""
os.system(self.get_command(file, **options))
return 1

The WindowsViewer class preferrably should override show_file to  call
ShellExecuteExW directly via ctypes, and wait (if possible) to delete
the temporary file. Or at least use subprocess.call with shell=True,
which will hide the console window. Note that being able to wait on
the image viewer is not guaranteed. For example, the image viewer in
Windows 10 is an app that cannot be waited on.

Since you already have a file on disk, you could skip PIL completely.
Just use os.startfile('1.bmp').
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Image Library

2017-05-17 Thread eryk sun
On Wed, May 17, 2017 at 10:33 PM, Michael C
 wrote:
> On Wed, May 17, 2017 at 3:30 PM, eryk sun  wrote:
>
>> You're probably running a .py script that's associated with py.exe or
>> python.exe. These executables create a new console (i.e. an instance
>> of the console host process, conhost.exe), if they don't inherit one
>> from their parent process. The new console defaults to creating a
>> visible window. Change the file extension to .pyw. This file extension
>> should be associated with pyw.exe or pythonw.exe, which will not
>> create a console.
>>
>> FYI, the cmd shell is unrelated to that console window. Windows users
>> often confuse the cmd shell with the console window that it uses. I
>> suppose it's less confusing on Linux. Like cmd, bash will inherit the
>> parent's terminal/console; however, it doesn't automatically spawn a
>> terminal on Linux if the parent doesn't have one. (Getting that
>> behavior on Windows requires the DETACHED_PROCESS creation flag.)
>> Since Windows users typically run cmd.exe to get a command-line shell
>> for running programs, they associate cmd.exe with the console window.
>> It isn't obvious that other programs create consoles without any
>> associated instance of cmd.exe.
>
> Actually, that is the whole script! I didn't get used to have the cmd.exe
> window pop up at all, could it be something I did?

Changing the script's extension to .pyw didn't prevent the console
from appearing? Or did you not try it?

Also, to reiterate, the cmd shell doesn't create or own any window,
and unless something really weird is going on, there's no cmd.exe
instance associated with the console window that you're seeing. cmd
can use a console via standard I/O File handles, and usually does, but
not always. It's no different from python.exe, powershell.exe, or any
other console application. Really, there is no such thing as a "cmd
window", "python window", or "PowerShell window". Because these are
long-running shell processes (e.g. Python's REPL), people are inclined
to think in those terms, and that's fine, but would you call it a
"where.exe window", "chcp.com window", "doskey.exe window",
"whoami.exe window", "findstr.exe window"? I think not. It's clear
that these programs simply use the console; they don't own it. Neither
do shells, but in the case of shells and other long-running console
processes, we're loose with language for convenience -- as long as it
doesn't confuse our understanding of how things really work.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Bug

2017-05-17 Thread Cameron Simpson

On 17May2017 12:26, Grace Sanford  wrote:

Theoretically, the following code is suppose to check if the user has won a
tic tac toe game by checking if there are all "X"s in either the
horizontal, vertical, or diagonal lines of a grid (represented by a list
with "board" with elements 0-8).  If one of these is the case, it is
suppose to print the "You won" string.  Nevertheless, when I change list
variable to reflect one of these conditions, there is no printing
occurring.  I cannot figure out why.

if board[0:3]==["X", "X", "X"] or board[3:6]==["X", "X", "X"] or
board[6:9]==["X", "X", "X"] or \
   [board[0],board[3],board[6]]==["X", "X", "X"] or
[board[1],board[4],board[7]]==["X", "X", "X"] or
[board[2],board[5],board[8]] ==["X", "X", "X"] or \
   [board[0],board[4],board[8]]==["X", "X", "X"] or
[board[2],board[4],board[6]]==["X", "X", "X"]:


Please post complete code, and the output (I accept that in your case the 
output is empty). For example:


 board = [ "X", "X", "X",
   "", "", "",
   "", "", ""
 ]
 if board[0:3]==["X", "X", "X"] or board[3:6]==["X", "X", "X"] or board[6:9]==["X", "X", 
"X"] or \
[board[0],board[3],board[6]]==["X", "X", "X"] or [board[1],board[4],board[7]]==["X", "X", "X"] or 
[board[2],board[5],board[8]] ==["X", "X", "X"] or \
[board[0],board[4],board[8]]==["X", "X", "X"] or [board[2],board[4],board[6]]==["X", 
"X", "X"]:
  print("ROW!")

so that proeple can reproduce your problem. For example, it may be that some 
winning positions do work and some don't, and you've tested only a failing 
combination.


The example I have above prints "ROW!" for me, and it is just your own code 
with a specific combination.


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


Re: [Tutor] Pyuthon 3 Combine 1 D Arrays

2017-05-17 Thread Alan Gauld via Tutor
On 17/05/17 20:50, Stephen P. Molnar wrote:
> I'm beginning to think that I don't know how to ask the question as 
> Google and Stack Overflow have resulted in nothing.  All of the results 
> seem to deal with integers.

Have you tried asking on the scipy forum?

https://www.scipy.org/scipylib/mailing-lists.html

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.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 I display a picture?

2017-05-17 Thread Alan Gauld via Tutor
On 18/05/17 00:24, Michael C wrote:

> or to find another way to display the picture without using python image
> library.


There are lots of ways it depends on what you actually want
to do with the image. For example you can run your favourite
image viewer program(that looks like what PIL is doing)

Or you could create a temporary html file with an img tag
pointing at the image, then open your browser on that file.

Or you can create a simple GUI and put the image into a
canvas component.

Or you could use a different image editing module like
the ImageMagik module(forgotten the name) or Blender.

It just depends what you need it for which solution suits.

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


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


Re: [Tutor] Fwd: Re: How do I display a picture?

2017-05-17 Thread Alan Gauld via Tutor
On 18/05/17 00:38, Alan G via Tutor wrote:
>Please always use reply all, or reply list when responding to list

Oops, it seems like you did that already, my apologies.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.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 I display a picture?

2017-05-17 Thread Michael C
I use python image library and apparently when I do

im = Image.open('1.png')
im.show()


show() actually opens a empty console window that doesn't do anything and
as long as it's around the script hangs.
Currently I have to close it by clicking on the close button and it makes
my script useless.

so  i am trying find either a way to prevent that from poping up or to
close it automatically somehow

or to find another way to display the picture without using python image
library.



On Wed, May 17, 2017 at 4:13 PM, Alan Gauld via Tutor 
wrote:

> On 17/05/17 21:33, Michael C wrote:
>
> > How do I display a picture?
>
> What do you mean? What kind of picture?
> Where do you want it displayed (what kind
> of window/screen)?
>
> There are a dozen possible ways to "display a picture"
> depending on what you specifically want.
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] copy/paste/move files

2017-05-17 Thread Michael C
Ok!

On Wed, May 17, 2017 at 4:11 PM, Alan Gauld via Tutor 
wrote:

> On 17/05/17 20:09, Michael C wrote:
>
> > How do I move files to a designated folder or copy/paste?
>
> copy/paste is a UI specific thing, you don't do that in Python code.
> What you do  is either copy a file or move it.
>
> The shutil module provides easy functions for both.
> See the documentation for the module.
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> 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] Help finishing a function

2017-05-17 Thread Alan Gauld via Tutor
Please use Reply-All or Reply-List when replying to the list,
otherwise it only goes to me.

On 17/05/17 17:21, Grace Sanford wrote:
> Syntactically speaking, how can I check if an element in the list
> "board" at position p equals "_" and then change that element to "0"?

You can use the == operator:

if board[index] == "_":
board[index] = "O"
else:
   # report an error? return false?


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
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: How do I display a picture?

2017-05-17 Thread Alan G via Tutor
   Please always use reply all, or reply list when responding to list
   messages. I think eryksun may have already answered your question, if not
   give more info about how you run your code.

    Original Message 
   Subject: Re: [Tutor] How do I display a picture?
   From: Michael C 
   To: Alan Gauld 
   CC: tutor@python.org

   I use python image library and apparently when I do
   im = Image.open('1.png')
   im.show()
   show() actually opens a empty console window that doesn't do anything and
   as long as it's around the script hangs.
   Currently I have to close it by clicking on the close button and it makes
   my script useless.
   so **i am trying find either a way to prevent that from poping up or to
   close it automatically somehow
   or to find another way to display the picture without using python image
   library.
   On Wed, May 17, 2017 at 4:13 PM, Alan Gauld via Tutor
   <[1]tutor@python.org> wrote:

 On 17/05/17 21:33, Michael C wrote:

 > How do I display a picture?

 What do you mean? What kind of picture?
 Where do you want it displayed (what kind
 of window/screen)?

 There are a dozen possible ways to "display a picture"
 depending on what you specifically want.

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

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

References

   Visible links
   1. mailto:tutor@python.org
   2. http://www.alan-g.me.uk/
   3. http://www.amazon.com/author/alan_gauld
   4. http://www.flickr.com/photos/alangauldphotos
   5. mailto:Tutor@python.org
   6. 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] copy/paste/move files

2017-05-17 Thread Alex Kleider

On 2017-05-17 12:09, Michael C wrote:

Hi all,

How do I move files to a designated folder or copy/paste?



The first hit when I googled "how to move a file using python" was
http://stackoverflow.com/questions/8858008/how-to-move-a-file-in-python
which in turn suggests the use of:
os.rename() or shutil.move()
depending on whether you need only to rename or to actually move a file.
(The unix mv utility is used to do both but the 'twofor' is not 
available in Python to my knowledge.)

Don't forget to
import os
or
import shutil
depending on your needs.


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


Re: [Tutor] How do I display a picture?

2017-05-17 Thread Alan Gauld via Tutor
On 17/05/17 21:33, Michael C wrote:

> How do I display a picture?

What do you mean? What kind of picture?
Where do you want it displayed (what kind
of window/screen)?

There are a dozen possible ways to "display a picture"
depending on what you specifically want.

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


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


Re: [Tutor] copy/paste/move files

2017-05-17 Thread Alan Gauld via Tutor
On 17/05/17 20:09, Michael C wrote:

> How do I move files to a designated folder or copy/paste?

copy/paste is a UI specific thing, you don't do that in Python code.
What you do  is either copy a file or move it.

The shutil module provides easy functions for both.
See the documentation for the module.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.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 - What is the best package to learn programming in Python?

2017-05-17 Thread Alan Gauld via Tutor
On 17/05/17 19:17, keith quach wrote:

> I hope you could help. I am new to the Python community. I am looking 
> for your recommendation for a Windows 10 (64 bit) Python 3.6 
> distribution package that covers all the necessary installtions/files.

It depends on what you want to do. There is no single package I
know of that includes *all* the Python modules available - there
are too many and many are out of sync with different versions.

If you do scientific/numeric computations you probably want
something like Anaconda or Enthought. If you do media/video
work you might want some of the distros targetting Maya or
similar.

Of the "standard" distributions I usually recommend the
ActiveState.com distro because it includes some extra
Windows goodies and integrates with the help system better.

If you need an IDE you will need to check those out separately,
there are at least half a dozen, some free, some commercial.
IDEs are a very personal choice, many Python programmers
prefer not to use one but work with multiple open windows
instead.


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


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


Re: [Tutor] Bug

2017-05-17 Thread Alan Gauld via Tutor
On 17/05/17 17:26, Grace Sanford wrote:

> with "board" with elements 0-8).  If one of these is the case, it is
> suppose to print the "You won" string.  Nevertheless, when I change list
> variable to reflect one of these conditions, there is no printing
> occurring.  I cannot figure out why.

You need to show us the whole code including the print statements.
Also, do you get an error message? If so please include the full message.

As it stands the formatting is all messed up but unless you have it all
on one line (or 3 lines, I just noticed the \ chars...) I suspect you
will get a syntax error?

To fix that you can put parentheses round the expression:


if ( board[0:3]==["X", "X", "X"] or
 board[3:6]==["X", "X", "X"] or
 board[6:9]==["X", "X", "X"] or
 [board[0],board[3],board[6]]==["X", "X", "X"] or
 [board[1],board[4],board[7]]==["X", "X", "X"] or
 [board[2],board[5],board[8]]==["X", "X", "X"] or
 [board[0],board[4],board[8]]==["X", "X", "X"] or
 [board[2],board[4],board[6]]==["X", "X", "X"]
   ):

Have you tried breaking it down in the interpreter?
Try an if statement with just the first three lines?
Then the last two? etc That will help identify where
the problem lies.

At a casual glance I can't see any issues with the
code above.


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


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


Re: [Tutor] Python Image Library

2017-05-17 Thread Michael C
Actually, that is the whole script! I didn't get used to have the cmd.exe
window pop up at all, could it be something I did?

Or, is there a way to suppress that from showing up?

thanks!

On Wed, May 17, 2017 at 3:30 PM, eryk sun  wrote:

> On Wed, May 17, 2017 at 8:24 PM, Michael C
>  wrote:
> > from PIL import Image
> >
> > im = Image.open('pic.bmp')
> > im.show()
> >
> > I ran this code and it not only opened the picture in paint, which is
> what
> > I want, but it also opens a CMD.exe console window! how do I prevent
> that from
> > happening?
>
> You're probably running a .py script that's associated with py.exe or
> python.exe. These executables create a new console (i.e. an instance
> of the console host process, conhost.exe), if they don't inherit one
> from their parent process. The new console defaults to creating a
> visible window. Change the file extension to .pyw. This file extension
> should be associated with pyw.exe or pythonw.exe, which will not
> create a console.
>
> FYI, the cmd shell is unrelated to that console window. Windows users
> often confuse the cmd shell with the console window that it uses. I
> suppose it's less confusing on Linux. Like cmd, bash will inherit the
> parent's terminal/console; however, it doesn't automatically spawn a
> terminal on Linux if the parent doesn't have one. (Getting that
> behavior on Windows requires the DETACHED_PROCESS creation flag.)
> Since Windows users typically run cmd.exe to get a command-line shell
> for running programs, they associate cmd.exe with the console window.
> It isn't obvious that other programs create consoles without any
> associated instance of cmd.exe.
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Image Library

2017-05-17 Thread eryk sun
On Wed, May 17, 2017 at 8:24 PM, Michael C
 wrote:
> from PIL import Image
>
> im = Image.open('pic.bmp')
> im.show()
>
> I ran this code and it not only opened the picture in paint, which is what
> I want, but it also opens a CMD.exe console window! how do I prevent that from
> happening?

You're probably running a .py script that's associated with py.exe or
python.exe. These executables create a new console (i.e. an instance
of the console host process, conhost.exe), if they don't inherit one
from their parent process. The new console defaults to creating a
visible window. Change the file extension to .pyw. This file extension
should be associated with pyw.exe or pythonw.exe, which will not
create a console.

FYI, the cmd shell is unrelated to that console window. Windows users
often confuse the cmd shell with the console window that it uses. I
suppose it's less confusing on Linux. Like cmd, bash will inherit the
parent's terminal/console; however, it doesn't automatically spawn a
terminal on Linux if the parent doesn't have one. (Getting that
behavior on Windows requires the DETACHED_PROCESS creation flag.)
Since Windows users typically run cmd.exe to get a command-line shell
for running programs, they associate cmd.exe with the console window.
It isn't obvious that other programs create consoles without any
associated instance of cmd.exe.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] How do I display a picture?

2017-05-17 Thread Michael C
Hi all,

How do I display a picture?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Python Image Library

2017-05-17 Thread Michael C
from PIL import Image


im = Image.open('pic.bmp')
im.show()


I ran this code and it not only opened the picture in paint, which is what
I want,
but it also opens a CMD.exe console window! how do I prevent that from
happening?

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


[Tutor] Pyuthon 3 Combine 1 D Arrays

2017-05-17 Thread Stephen P. Molnar
I'm beginning to think that I don't know how to ask the question as 
Google and Stack Overflow have resulted in nothing.  All of the results 
seem to deal with integers.


I have a number of single column floating point arrays each containing 
300 entries that I want to combine into a n by 300 array where n is the 
number of single column arrays.


I have tried zip, np.concatenate etc with only failure.

Thanks in advance.

--
Stephen P. Molnar, Ph.D.Life is a fuzzy set
www.molecular-modeling.net  Stochastic and multivariate
(614)312-7528 (c)
Skype: smolnar1
1.00e+00
1.100334448160535050e+00
1.200668896321070322e+00
1.301003344481605373e+00
1.401337792642140423e+00
1.501672240802675695e+00
1.602006688963210745e+00
1.702341137123745796e+00
1.802675585284280846e+00
1.903010033444816118e+00
2.003344481605351390e+00
2.103678929765885997e+00
2.204013377926421491e+00
2.304347826086956541e+00
2.404682274247491591e+00
2.505016722408027086e+00
2.605351170568561692e+00
2.705685618729097186e+00
2.806020066889632236e+00
2.906354515050167286e+00
3.006688963210702337e+00
3.107023411371237387e+00
3.207357859531772437e+00
3.307692307692307931e+00
3.408026755852842982e+00
3.508361204013378032e+00
3.608695652173913082e+00
3.709030100334448132e+00
3.809364548494983183e+00
3.909698996655518677e+00
4.010033444816054171e+00
4.110367892976588777e+00
4.210702341137123383e+00
4.311036789297658878e+00
4.411371237458194372e+00
4.511705685618728978e+00
4.612040133779264472e+00
4.712374581939799967e+00
4.812709030100334573e+00
4.913043478260869179e+00
5.013377926421404673e+00
5.113712374581940168e+00
5.214046822742474774e+00
5.314381270903010268e+00
5.414715719063544874e+00
5.515050167224080369e+00
5.615384615384615863e+00
5.715719063545150469e+00
5.816053511705685963e+00
5.916387959866220569e+00
6.016722408026756064e+00
6.117056856187290670e+00
6.217391304347826164e+00
6.317725752508361658e+00
6.418060200668896265e+00
6.518394648829431759e+00
6.618729096989966365e+00
6.719063545150501859e+00
6.819397993311037354e+00
6.919732441471571960e+00
7.020066889632107454e+00
7.120401337792642060e+00
7.220735785953177555e+00
7.321070234113712161e+00
7.421404682274247655e+00
7.521739130434783149e+00
7.622073578595317755e+00
7.722408026755853250e+00
7.822742474916387856e+00
7.923076923076923350e+00
8.023411371237457956e+00
8.123745819397992562e+00
8.224080267558528945e+00
8.324414715719063551e+00
8.424749163879599934e+00
8.525083612040134540e+00
8.625418060200669146e+00
8.725752508361203752e+00
8.826086956521738358e+00
8.926421404682274741e+00
9.026755852842809347e+00
9.127090301003343953e+00
9.227424749163880335e+00
9.327759197324414941e+00
9.428093645484949548e+00
9.528428093645485930e+00
9.628762541806020536e+00
9.729096989966555142e+00
9.829431438127089748e+00
9.929765886287626131e+00
1.003010033444816074e+01
1.013043478260869534e+01
1.023076923076923173e+01
1.033110367892976633e+01
1.043143812709030094e+01
1.053177257525083554e+01
1.063210702341137193e+01
1.073244147157190653e+01
1.083277591973244114e+01
1.093311036789297752e+01
1.103344481605351213e+01
1.113377926421404673e+01
1.123411371237458134e+01
1.133444816053511772e+01
1.143478260869565233e+01
1.153511705685618693e+01
1.163545150501672332e+01
1.173578595317725792e+01
1.183612040133779253e+01
1.193645484949832891e+01
1.203678929765886352e+01
1.213712374581939812e+01
1.223745819397993273e+01
1.233779264214046911e+01
1.243812709030100372e+01
1.253846153846153832e+01
1.263879598662207471e+01
1.273913043478260931e+01
1.283946488294314392e+01
1.293979933110367853e+01
1.304013377926421491e+01
1.314046822742474951e+01
1.324080267558528412e+01
1.334113712374582050e+01
1.344147157190635511e+01
1.354180602006688972e+01
1.364214046822742432e+01
1.374247491638796070e+01
1.384280936454849531e+01
1.394314381270902992e+01
1.404347826086956630e+01
1.414381270903010090e+01
1.424414715719063551e+01
1.434448160535117012e+01
1.81605351170650e+01
1.454515050167224111e+01
1.464548494983277571e+01
1.474581939799331209e+01
1.484615384615384670e+01
1.494648829431438131e+01
1.504682274247491591e+01
1.514715719063545230e+01
1.524749163879598690e+01
1.534782608695652151e+01
1.544816053511705789e+01
1.554849498327759250e+01
1.564882943143812710e+01
1.574916387959866171e+01
1.584949832775919809e+01
1.594983277591973270e+01
1.605016722408026908e+01
1.615050167224080369e+01
1.625083612040133829e+01
1.635117056856187290e+01
1.645150501672240750e+01
1.655183946488294566e+01
1.665217391304347672e+01
1.675250836120401488e+01
1.685284280936454948e+01
1.695317725752508409e+01
1.705351170568561869e+01
1.715384615384615330e+01
1.725418060200668791e+01
1.735451505016722606e+01
1.745484949832776067e+01
1.755518394648829528e+01
1.765551839464882988e+01
1.775585284280936449e+01
1.785618729096989910e+01
1.795652173913043370e+01
1.805685618729097186e+01
1.815719063545150647e+01
1.825752508361204107e+01
1.835785953177257568e+01
1.845819397993311028e+01
1.855852842809364489e+01

Re: [Tutor] Python Image Library

2017-05-17 Thread Michael C
in fact, when I ran this:

import os
os.system("mspaint 1.bmp")


It also opened a cmd.exe window and the script wouldn't continue until I
closed the cmd window!

On Wed, May 17, 2017 at 1:24 PM, Michael C 
wrote:

> from PIL import Image
>
>
> im = Image.open('pic.bmp')
> im.show()
>
>
> I ran this code and it not only opened the picture in paint, which is what
> I want,
> but it also opens a CMD.exe console window! how do I prevent that from
> happening?
>
> thanks!
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Help - What is the best package to learn programming in Python?

2017-05-17 Thread keith quach

Hi,

I hope you could help. I am new to the Python community. I am looking 
for your recommendation for a Windows 10 (64 bit) Python 3.6 
distribution package that covers all the necessary installtions/files.


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


[Tutor] copy/paste/move files

2017-05-17 Thread Michael C
Hi all,

How do I move files to a designated folder or copy/paste?

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


Re: [Tutor] Matplotlib error with Python

2017-05-17 Thread Pooja Bhalode
Hi Alan,

Yes, that was the issue, I had a tempfile.py created my me some time back.
That was interfering with this one.
Thanks a lot for your input.

Hope you have a great day!
Pooja

On Wed, May 17, 2017 at 11:27 AM, Alan Gauld via Tutor 
wrote:

> On 17/05/17 15:07, Pooja Bhalode wrote:
>
> > */Users/poojabhalode/.bash_profile: line 1: .bashrc: No such file or
> > directory*
>
> I'd start with this one.
> Where is the bash script error coming from?
> Is there really no .bashrc?
> If not what is the impact of not having it?
>
> I'm also not clear what is calling bashrc...
>
> > *[[ 2 -1  0]*
> > * [-1  2 -1]*
>
> I have no idea what these numbers are.
>
> > *Traceback (most recent call last):*
> > *  File "/Users/poojabhalode/Google Drive/PYTHON/files/1sttest/
> May17.py",
> > line 7, in *
> > *import matplotlib*
> > *  File
> > "/System/Library/Frameworks/Python.framework/Versions/2.7/
> Extras/lib/python/matplotlib/__init__.py",
> > line 947, in *
> > *rcParams = rc_params()*
> > *  File
> > "/System/Library/Frameworks/Python.framework/Versions/2.7/
> Extras/lib/python/matplotlib/__init__.py",
> > line 856, in rc_params*
> > *fname = matplotlib_fname()*
> > *  File
> > "/System/Library/Frameworks/Python.framework/Versions/2.7/
> Extras/lib/python/matplotlib/__init__.py",
> > line 726, in matplotlib_fname*
> > *configdir = _get_configdir()*
> > *  File
> > "/System/Library/Frameworks/Python.framework/Versions/2.7/
> Extras/lib/python/matplotlib/__init__.py",
> > line 597, in _get_configdir*
> > *return _get_config_or_cache_dir(_get_xdg_config_dir())*
> > *  File
> > "/System/Library/Frameworks/Python.framework/Versions/2.7/
> Extras/lib/python/matplotlib/__init__.py",
> > line 566, in _get_config_or_cache_dir*
> > *if not _is_writable_dir(p):*
> > *  File
> > "/System/Library/Frameworks/Python.framework/Versions/2.7/
> Extras/lib/python/matplotlib/__init__.py",
> > line 228, in _is_writable_dir*
> > *t = tempfile.TemporaryFile(dir=p)*
> > *AttributeError: 'module' object has no attribute 'TemporaryFile'*
>
> You don't happen to have a file called tempfile.py in your
> folder by any chance? It could be that the code is picking
> it up instead of the standard library version?
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> 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


[Tutor] Bug

2017-05-17 Thread Grace Sanford
Theoretically, the following code is suppose to check if the user has won a
tic tac toe game by checking if there are all "X"s in either the
horizontal, vertical, or diagonal lines of a grid (represented by a list
with "board" with elements 0-8).  If one of these is the case, it is
suppose to print the "You won" string.  Nevertheless, when I change list
variable to reflect one of these conditions, there is no printing
occurring.  I cannot figure out why.

if board[0:3]==["X", "X", "X"] or board[3:6]==["X", "X", "X"] or
board[6:9]==["X", "X", "X"] or \
[board[0],board[3],board[6]]==["X", "X", "X"] or
[board[1],board[4],board[7]]==["X", "X", "X"] or
[board[2],board[5],board[8]] ==["X", "X", "X"] or \
[board[0],board[4],board[8]]==["X", "X", "X"] or
[board[2],board[4],board[6]]==["X", "X", "X"]:
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Matplotlib error with Python

2017-05-17 Thread Alan Gauld via Tutor
On 17/05/17 15:07, Pooja Bhalode wrote:

> */Users/poojabhalode/.bash_profile: line 1: .bashrc: No such file or
> directory*

I'd start with this one.
Where is the bash script error coming from?
Is there really no .bashrc?
If not what is the impact of not having it?

I'm also not clear what is calling bashrc...

> *[[ 2 -1  0]*
> * [-1  2 -1]*

I have no idea what these numbers are.

> *Traceback (most recent call last):*
> *  File "/Users/poojabhalode/Google Drive/PYTHON/files/1sttest/May17.py",
> line 7, in *
> *import matplotlib*
> *  File
> "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/__init__.py",
> line 947, in *
> *rcParams = rc_params()*
> *  File
> "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/__init__.py",
> line 856, in rc_params*
> *fname = matplotlib_fname()*
> *  File
> "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/__init__.py",
> line 726, in matplotlib_fname*
> *configdir = _get_configdir()*
> *  File
> "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/__init__.py",
> line 597, in _get_configdir*
> *return _get_config_or_cache_dir(_get_xdg_config_dir())*
> *  File
> "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/__init__.py",
> line 566, in _get_config_or_cache_dir*
> *if not _is_writable_dir(p):*
> *  File
> "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/__init__.py",
> line 228, in _is_writable_dir*
> *t = tempfile.TemporaryFile(dir=p)*
> *AttributeError: 'module' object has no attribute 'TemporaryFile'*

You don't happen to have a file called tempfile.py in your
folder by any chance? It could be that the code is picking
it up instead of the standard library version?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.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 finishing a function

2017-05-17 Thread Alan Gauld via Tutor
On 17/05/17 14:31, Grace Sanford wrote:
> I am wondering if someone can help/advise me on finishing the code for this
> function:

Please only send one email for a given i8ssue it gets confusing
when people start responding to two different threads about
the same question.

Also please give us more information. We won;t do your homework
for you so you need to tell us specifically where you need help.
The assignment gives you lots of hints about what to do.
Which bits are you struggling with?


That having been said, there is much I don't understand
myself, see below...

> the_board = [ "_", "_", "_",
>   "_", "_", "_",
>   "_", "_", "_"]
> 
> def do_user_move(board, x, y):
> """
> signature: list(str), int, int -> bool
> Given a list representing the state of the board
> and an x,y screen coordinate pair indicating where
> the user clicked, update the board
> with an O in the corresponding position.

The board above is a list of strings and not represented
on any kind of "screen"? I assume there is some other
code somewhere that creates a grid on screen that the
user then clicks on and you need to map the cell to
the string table?


> The function returns a bool indicated if
> the operation was successful: if the user
> clicks on a position that is already occupied
> or outside of the board area, the move is
> invalid, and the function should return False,
> otherise True.
> """
> print("user clicked at "+str(x)+","+str(y))
> width = turtle.window_width ()
> height = turtle.window_height ()
> #Given coordinates of user click, update board with "O" in
> corresponding position
> if x<(-width/2)+(width/3):
> column = 0
> elif x>(-width/2)+(width/3) and x<(width/2)-(width/3):
> column = 1
> elif x>(width/2)-(width/3):
> column = 2

This  seems like a complicated way to get the cell!

> if y>(height/2)-(height/3):
> row = 0
> elif y<(height/2)-(height/3) and y>(-height/2)+(height/3):
> row = 1
> elif y<(-height/2)+(height/3):
> row = 2
> p = row * 3 + column

> for board[p]=="_":
> pass #code here

This is not valid Python code. The for loop requires
a sequence of some kind (to be technical an iterable).
This is a boolean test so you should get an error.

> #Check if user clicks on a position that is already occupied
> pass #code here

Assuming you get the code above to work and you have a
row/column [pair do you know how to map that onto your
9 element string list? If so put the code here.


> #Check if user clicks outside the board area
> if x<(-width/2) or x>(width/2) or y<(-height/2) or y>(height/2):
> return False

I'd have thought thus test should be right at the top
before attempting all the other stuff!

So in conclusion it looks like we only have half the story
(where is the missing screen?) and the code as provided has
at least one bug (the for loop). But otherwise the task
is fairly clear, so what bit are you stuck 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


[Tutor] Matplotlib error with Python

2017-05-17 Thread Pooja Bhalode
*Hi, *

*I have been working on a graphic user interface with matplotlib and
suddenly(Earlier, I didnt get these errors, and when I opened the files
now, I am) getting these errors: *
*/Users/poojabhalode/.bash_profile: line 1: .bashrc: No such file or
directory*
*[[ 2 -1  0]*
* [-1  2 -1]*
* [ 0 -1  2]]*
*[[  3.41421356e+00   8.32667268e-17  -6.37995760e-17]*
* [  0.e+00   2.e+00   1.35170527e-16]*
* [  0.e+00   0.e+00   5.85786438e-01]]*
*8.32667268469e-17*
*8.32667268469e-17*
*-6.37995760397e-17*
*0.0*
*1.35170526715e-16*
*0.0*
*0.0*
*[[ 3.41421356  0.  0.]*
* [ 0.  2.  0.]*
* [ 0.  0.  0.58578644]]*
*Traceback (most recent call last):*
*  File "/Users/poojabhalode/Google Drive/PYTHON/files/1sttest/May17.py",
line 7, in *
*import matplotlib*
*  File
"/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/__init__.py",
line 947, in *
*rcParams = rc_params()*
*  File
"/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/__init__.py",
line 856, in rc_params*
*fname = matplotlib_fname()*
*  File
"/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/__init__.py",
line 726, in matplotlib_fname*
*configdir = _get_configdir()*
*  File
"/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/__init__.py",
line 597, in _get_configdir*
*return _get_config_or_cache_dir(_get_xdg_config_dir())*
*  File
"/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/__init__.py",
line 566, in _get_config_or_cache_dir*
*if not _is_writable_dir(p):*
*  File
"/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/__init__.py",
line 228, in _is_writable_dir*
*t = tempfile.TemporaryFile(dir=p)*
*AttributeError: 'module' object has no attribute 'TemporaryFile'*
*[Finished in 0.2s with exit code 1]*
*[shell_cmd: python -u "/Users/poojabhalode/Google
Drive/PYTHON/files/1sttest/May17.py"]*
*[dir: /Users/poojabhalode/Google Drive/PYTHON/files/1sttest]*
*[path: /usr/bin:/bin:/usr/sbin:/sbin]*


*My code gives errors at the import statement itself: *

*Code::*
*import matplotlib*
*ERROR indicated here. *
*matplotlib.use("TkAgg")*
*from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg,
NavigationToolbar2TkAgg*
*from matplotlib.figure import Figure*

*Can someone please let me know what is going wrong with this?*
*Thank you. I would really appreciate it.*

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


[Tutor] Help finishing a function

2017-05-17 Thread Grace Sanford
I am wondering if someone can help/advise me on finishing the code for this
function:

import turtle
import time
import random

# This list represents the board. It's a list
# of nine strings, each of which is either
# "X", "O", "_", representing, respectively,
# a position occupied by an X, by an O, and
# an unoccupied position. The first three
# elements in the list represent the first row,
# and so on. Initially, all positions are
# unoccupied.
the_board = [ "_", "_", "_",
  "_", "_", "_",
  "_", "_", "_"]

def do_user_move(board, x, y):
"""
signature: list(str), int, int -> bool
Given a list representing the state of the board
and an x,y screen coordinate pair indicating where
the user clicked, update the board
with an O in the corresponding position.
The function returns a bool indicated if
the operation was successful: if the user
clicks on a position that is already occupied
or outside of the board area, the move is
invalid, and the function should return False,
otherise True.
"""
print("user clicked at "+str(x)+","+str(y))
width = turtle.window_width ()
height = turtle.window_height ()
#Given coordinates of user click, update board with "O" in
corresponding position
if x<(-width/2)+(width/3):
column = 0
elif x>(-width/2)+(width/3) and x<(width/2)-(width/3):
column = 1
elif x>(width/2)-(width/3):
column = 2
if y>(height/2)-(height/3):
row = 0
elif y<(height/2)-(height/3) and y>(-height/2)+(height/3):
row = 1
elif y<(-height/2)+(height/3):
row = 2
p = row * 3 + column
for board[p]=="_":
pass #code here
#Check if user clicks on a position that is already occupied
pass #code here
#Check if user clicks outside the board area
if x<(-width/2) or x>(width/2) or y<(-height/2) or y>(height/2):
return False
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Help writing a function

2017-05-17 Thread Grace Sanford
I need suggestions/help for writing the following function:

import turtle
import time
import random

# This list represents the board. It's a list
# of nine strings, each of which is either
# "X", "O", "_", representing, respectively,
# a position occupied by an X, by an O, and
# an unoccupied position. The first three
# elements in the list represent the first row,
# and so on. Initially, all positions are
# unoccupied.
the_board = [ "_", "_", "_",
  "_", "_", "_",
  "_", "_", "_"]

def do_user_move(board, x, y):
"""
signature: list(str), int, int -> bool
Given a list representing the state of the board
and an x,y screen coordinate pair indicating where
the user clicked, update the board
with an O in the corresponding position.
The function returns a bool indicated if
the operation was successful: if the user
clicks on a position that is already occupied
or outside of the board area, the move is
invalid, and the function should return False,
otherise True.
"""
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Given a string, call a function of that name

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

> corresponding to one of his functions or methods, if he could use that
> word to run a function of the same name.  I said I had done something
> once where I used the word as a dictionary key, which was then used to
> call the function. 

That's the usual approach.

> def check_fcn_input(function):
> valid_fcns = ['spam', 'ham', 'eggs']
> if function in valid_fcns:
> return True
> else:
> return False

I would rewrite this to return the function or None

def get_input_function(name):
return functions.get(name)

You can then use the result as a boolean in a
test or simply call it directly using Pythons
"ask forgiveness" approach:

name,phrase = get_input()
try: get_input_function(name)(phrase)
except TypeError: pass

> This works, but I cannot but help wondering if there is a more direct
> approach?  

Not really. Remember that Python itself uses a dictionary
to translate names to function calls. If its good enough
for the interpreter its probably good enough for you! :-)


> Hmm.  It bothers me that in check_fcn_input() I have a list valid_fcns
> and in run_fcn() I have a dictionary fcn_dict.  

A global dict wins here.
You could of course make it a class but I'm not sure that
actually makes anything clearer in this case.

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

2017-05-17 Thread Peter Otten
Grace Sanford wrote:

> how do you reset the turtle's position without drawing a line from where
> it last was?

Call turtle.penup() when you want to prevent it from drawing and pendown() 
to have it draw again. Example:

import turtle

for i in range(10):
# draw a 20 units line
turtle.forward(20)

# lift the pen
turtle.penup()

# move 10 units forward without drawing
turtle.forward(10)

# put the pen back on the paper
turtle.pendown()

turtle.mainloop()


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


Re: [Tutor] Given a string, call a function of that name

2017-05-17 Thread Peter Otten
boB Stepp wrote:

> My son (Now 13 years old.) is merrily programming away in Python 3 (Of
> course!) and has many projects he is working on.  Today he resumed
> work on his efforts to create a natural language parser, which he
> hopes will enable people to type in commands to a DnD-like game using
> natural English.  An ambitious project to be sure!  He asked me if
> there was any way that if he identified a word in the user's input
> corresponding to one of his functions or methods, if he could use that
> word to run a function of the same name.  I said I had done something
> once where I used the word as a dictionary key, which was then used to
> call the function.  After fumbling around a bit I came up with the
> following program for him to play around with:
> 
> ==
> #!/usr/bin/env python3
> 
> def spam(phrase):
> print('spam function said: ', phrase)
> 
> def ham(phrase):
> print('ham function said: ', phrase)
> 
> def eggs(phrase):
> print('eggs function said: ', phrase)
> 
> def get_input():
> function = input('Which do you want:  spam, ham or eggs?\n')
> phrase = input('\nHow do you want your food to be prepared?\n')
> return function, phrase
> 
> def check_fcn_input(function):
> valid_fcns = ['spam', 'ham', 'eggs']
> if function in valid_fcns:
> return True
> else:
> return False
> 
> def run_fcn(function, phrase):
> fcn_dict = {'spam': spam, 'ham': ham, 'eggs': eggs}
> fcn_dict[function](phrase)
> 
> def main():
> function, phrase = get_input()
> while not check_fcn_input(function):
> print("You made an invalid food choice!  Let's try this again!")
> function, phrase = get_input()
> run_fcn(function, phrase)
> 
> if __name__ == '__main__':
> main()
> ==
> 
> This works, but I cannot but help wondering if there is a more direct
> approach?  Given the above three functions spam(), ham() and eggs(),
> and given a string 'ham', what is the quickest, most direct way to run
> that function?  Or similarly for the other two?

If you are not bothered about security, getattr(module, function_name)() or 
even eval(). But usually the approach you have chosen is preferrable.

> Oh, and I suppose I should ask for a critique of the code as written
> for appropriate Python style, proper targeted function use, etc.  I am
> always eager to learn!  

> if function in valid_fcns:
> return True
> else:
> return False

should really be spelt

return function in valid_fcns

and personally I wouldn't mind to type the few extra chars to make it

return function in valid_functions

;)

> However, I did not use doc strings for the
> functions or write tests.  If I were actually planning on using this
> for real, I would have done so.
> 
> Hmm.  It bothers me that in check_fcn_input() I have a list valid_fcns
> and in run_fcn() I have a dictionary fcn_dict.  These contain
> essentially the same information.  Would this be a case for a global
> function dictionary (Which I could also use to check for valid
> functions.) or perhaps a class which only exists to have this function
> dictionary?

A global is indeed better than the duplicate information in your list and 
dict. Here's another option, return the function instead of information 
about its existence:

def find_function(function):
fcn_dict = {'spam': spam, 'ham': ham, 'eggs': eggs}
return fcn_dict.get(function)

def main():
while True:
function_name, phrase = get_input()
function = find_function(function_name)
if function is not None:
break
print("You made an invalid food choice!  Let's try this again!")
function(phrase)

If want to try the class-based approach you can steal from the cmd module:

class Lookup:
prefix = "do_"

def do_spam(self, phrase):
print('spam function said: ', phrase)

def do_ham(self, phrase):
print('ham function said: ', phrase)

def do_eggs(self, phrase):
print('eggs function said: ', phrase)

def known_names(self):
offset = len(self.prefix)
return sorted(
name[offset:] for name in dir(self)
if name.startswith(self.prefix)
)

def get_input(self):
names = self.known_names()
names = ", ".join(names[:-1]) + " or " + names[-1]

function = input('Which do you want:  {}?\n'.format(names))
phrase = input('\nHow do you want your food to be prepared?\n')
return function, phrase

def find_function(self, function):
return getattr(self, self.prefix + function, None)

def one_cmd(self):
while True:
function_name, phrase = self.get_input()
function = self.find_function(function_name)
if function is not None:
break