Re: [Tutor] eval use (directly by interpreter vs with in a script)

2014-11-03 Thread Ken G.


On 11/03/2014 12:37 AM, Danny Yoo wrote:

I use exec to jump to another program within the
same directory, such as:

execfile("BloodPressure02Sorting.py")

and let the program terminate there. Should I do
it differently or are you talking about a different
horse?


This is related.

Rather than use execfile, you may want to consider looking into "modules".

 https://docs.python.org/2/tutorial/modules.html

By using the module system, you can call the functions of other files.
We might think of one of the functions in a file as the main program,
in which case you should be able to arrange a module approach that
effectively does what you're doing with execfile.

Using the module system is often nicer because the functions of
another module are still just regular functions: it's easy to pass
along Python values as arguments to tell the next process some
contextual information.  We can contrast this with an execfile
approach, where there's not such a nice way of passing on that context
to the other program.

The module approach also can "fail faster", in the case that when we
want to use a module, we "import" it at the head of our main program.
So if we got the file name wrong, we get fairly immediate feedback
about our mistake.  In contrast, the execfile approach defers from
touching the secondary program until we're at the point of the
execfile call itself.  So if we got the filename wrong, we don't see
the error as quickly.



Wow! Such an interesting response. Much appreciated. Printing
this out as a reference. Again, thanks.

Ken


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


Re: [Tutor] Some shameless self promotion

2014-11-03 Thread Albert-Jan Roskam
 

- Original Message -
> From: Alan Gauld 
> To: tutor@python.org
> Cc: 
> Sent: Monday, November 3, 2014 2:22 AM
> Subject: [Tutor] Some shameless self promotion
> 
> For anyone who might be interested
> 
> http://www.amazon.com/Python-Projects-Laura-Cassell/dp/111890866X
> 
> A book aimed at those who have just finished their first python tutorial 
> and are wondering what to do next...
> 
> I promise not to mention it every post, honest :-)
> 
> 
> PS. Disclaimer:
> I had nothing to do with the blurb on the website :-(

Cool, and congratulations! Is there a preview chapter, and/or a Table Of 
Contents (Amazon sometimes has this..)?

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


Re: [Tutor] eval use (directly by interpreter vs with in a script)

2014-11-03 Thread Albert-Jan Roskam



>
>Real question is what you're trying to do.  eval() and exec() are to be 
>avoided if possible, so the solutions are not necessarily the easiest.

I sometimes do something like
ifelse = "'teddybear' if bmi > 30 else 'skinny'"
weightcats = [eval(ifelse) for bmi in bmis]

Would this also be a *bad* use of eval? It can be avoided, but this is so 
concise.

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


Re: [Tutor] eval use (directly by interpreter vs with in a script)

2014-11-03 Thread Alan Gauld

On 03/11/14 17:33, Albert-Jan Roskam wrote:


I sometimes do something like
ifelse = "'teddybear' if bmi > 30 else 'skinny'"
weightcats = [eval(ifelse) for bmi in bmis]

Would this also be a *bad* use of eval? It can be avoided, but this is so 
concise.


eval etc are worst where the code to be evaluated is
coming from outside your program (eg a file, user
input etc)

So in your use case its not quite so dangerous since
the code is hard coded into your program. But its is still easily 
avoided by putting the ifelse bit into a function


def getWeight(bmi):
return  'teddybear' if bmi > 30 else 'skinny'

weightcats = [getWeight(bmi) for bmi in bmis]

You could use the expression directly in the comprehension but I'm 
assuming the real examples are more complex...


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos

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


Re: [Tutor] eval use (directly by interpreter vs with in a script)

2014-11-03 Thread Danny Yoo
On Mon Nov 03 2014 at 10:04:41 AM Alan Gauld 
wrote:

> On 03/11/14 17:33, Albert-Jan Roskam wrote:
>
> > I sometimes do something like
> > ifelse = "'teddybear' if bmi > 30 else 'skinny'"
> > weightcats = [eval(ifelse) for bmi in bmis]
> >
> > Would this also be a *bad* use of eval? It can be avoided, but this is
> so concise.
>
>
Yes, this is bad and you need to learn to instinctively wince when you see
this.  I know that I am.  :P

Even if you don't think about the security perspective, this is not good
from an engineering perspective: eval() is a dynamic recompilation of that
bit of source code every single time it goes through the loop.

The only thing that is "varying" here is bmi, and when we're writing a code
that's parameterized by a varying value, the tool to use isn't eval(): you
want to use a function.

Here's what this looks like:

#
def ifelse(bmi): return 'teddybear' if bmi > 30 else 'skinny'
weightcats = [ifelse(bmi) for bmi in bmis]
#

This is formatted deliberately to show that this is about the same length
as the original code, but significantly safer and more performant.
Performant because Python isn't reparsing the code that computes the bmi
label.

Safer because the behavior of the function-using code is much more
statically definable: you can tell from just reading the source code that
it can only do a few things: it either computes a value, or maybe it errors
if bmi is not a number.  eval(), on the other hand, can be a big black hole
of badness just waiting to happen.

Consider if 'bmi' were ever controlled from the outside world.  At the very
worst, the normal function approach will raise a runtime error, but that's
it.  In contrast, the eval approach can take over your machine.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] eval use (directly by interpreter vs with in a script)

2014-11-03 Thread Danny Yoo
On Mon Nov 03 2014 at 10:48:29 AM Danny Yoo  wrote:

> On Mon Nov 03 2014 at 10:04:41 AM Alan Gauld 
> wrote:
>
>> On 03/11/14 17:33, Albert-Jan Roskam wrote:
>>
>> > I sometimes do something like
>> > ifelse = "'teddybear' if bmi > 30 else 'skinny'"
>> > weightcats = [eval(ifelse) for bmi in bmis]
>> >
>> > Would this also be a *bad* use of eval? It can be avoided, but this is
>> so concise.
>>
>

> Consider if 'bmi' were ever controlled from the outside world.  At the
> very worst, the normal function approach will raise a runtime error, but
> that's it.  In contrast, the eval approach can take over your machine.
>


I should be a bit more careful in saying this.  I should have said:
"Consider if 'ifelse'" were ever controlled from the outside world...".  My
apologies for writing a bit too fast there.

In any case, the other comments still stand.  You want to use functions for
cases like the above.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Flow of execution of execution

2014-11-03 Thread William Becerra
hey, I'm new to programming.
running Python 2.7.8 on windows 8 OS
Im on chapter 6 of a book called 'How to Think Like a Computer
Scientist-Learning with Python'
here is the code:
def printMultiples(n, high):
i = 1
while i<=high:
print n*i, "\t",
i = i + 1
print
def multipleTable(high):
i = 1
while i<=high:
printMultiples(i, i)
i = i + 1
print
print multipleTable(6)

when i run this code the result i get is

1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36

None


Can someone please explain why does it print a triangular table and not a
square table like this one:

1 2 3 4 5 6
2 4 6 8 10 12
3 6 9 12 15 18
4 8 12 16 20 24
5 10 15 20 25 30
6 12 18 24 30 36

None

is there any documentation i can read on tables?
Thank You
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Flow of execution of execution

2014-11-03 Thread Alan Gauld

On 03/11/14 18:04, William Becerra wrote:


def printMultiples(n, high):
 i = 1
 while i<=high:
 print n*i, "\t",
 i = i + 1
 print



def multipleTable(high):
 i = 1
 while i<=high:
 printMultiples(i, i)
 i = i + 1
 print



print multipleTable(6)

when i run this code the result i get is

1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36



Can someone please explain why does it print a triangular table and not
a square table like this one:


Because you call print Multiples() from within multipleTable()
Each time the loop executes the value of i increases so each line 
printed gets longer. The first line is printed by printMultiples(1,1)

The second is called with printMultiples(2,2) and so on up to
printMultiples(6,6).

This yields a triangular printout.


is there any documentation i can read on tables?


Not really, there's no such thing as a table in Python programming, its 
just a structure you create. In practice its usually composed of a list 
of lists.


HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
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] Python help

2014-11-03 Thread Juwel Williams
Good Day,

I am in a python class at my school. I am very confused, he gives us 
assignments but I am not sure how to attempt it. I am confused about tuples, 
lists and dictionaries. Now he has moved on to class and modules. Can you 
assist me please.

He has given us a module to go by. 

It says define a new variable called MOVES that contains a dictionary.
- I assume this means to create an empty dictionary to the variable called 
moves.
MOVES = { }

Then it says, “As keys, use the move variable defined in the pokemon module” 
- Is keys what we use in the parameters? 


Thank you,

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


Re: [Tutor] Python help

2014-11-03 Thread Alan Gauld

On 03/11/14 20:26, Juwel Williams wrote:


I am confused about tuples, lists and dictionaries.


The more specific your question the easier it is for us to answer.
What exactly is confusing you about them?
What they are? How to use them? The syntax?


Now he has moved on to class and modules. Can you assist me please.


Lets stick with lists, tuples and dictionaries for now.

You could try reading through the Raw Materials topic in my
tutorial (see .sig below) which discusses all three - and much
more besides.



He has given us a module to go by.

It says define a new variable called MOVES that contains a dictionary.
- I assume this means to create an empty dictionary to the variable called 
moves.
MOVES = { }


I assume so too, the terminology is wrong for Python but accurate
for most languages. Python variables dont store data inside themselves, 
they are only names referring to data values(objects).


But I think you are right, he means create a variable that refers to an 
empty dictionary.



Then it says, “As keys, use the move variable defined in the pokemon module”
- Is keys what we use in the parameters?


Recall that dictionaries consist of key-value pairs. You access
a value by passing the dictionary a key.

It seems that you have access to a Python module called pokemon?
Within that module is a variable called move. Without knowing what that 
variable looks like its hard for me to give you any further advise, but 
somehow you are expected to map the move values to dictionary keys...


HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos

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


Re: [Tutor] Some shameless self promotion

2014-11-03 Thread memilanuk

On 11/02/2014 05:22 PM, Alan Gauld wrote:

For anyone who might be interested

http://www.amazon.com/Python-Projects-Laura-Cassell/dp/111890866X

A book aimed at those who have just finished their first python tutorial
and are wondering what to do next...



Do you know if there are any plans for an electronic version i.e. pdf or 
kindle?



--
Shiny!  Let's be bad guys.

Reach me @ memilanuk (at) gmail dot com

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


Re: [Tutor] eval use (directly by interpreter vs with in a script)

2014-11-03 Thread Steven D'Aprano
On Sun, Nov 02, 2014 at 06:23:12PM -0500, Ken G. wrote:

> I use exec to jump to another program within the
> same directory, such as:
> 
> execfile("BloodPressure02Sorting.py")
> 
> and let the program terminate there. Should I do
> it differently or are you talking about a different
> horse?

That's an interesting use of execfile, but I think there's a slight 
misconception. The program doesn't terminate "there" (inside the other 
script), it terminates in the original script, after the execfile() 
function has returned. You can see this if you make a wrapper script 
like this:


print "inside wrapper script"
execfile("/path/to/script/you/want/to/run.py")
print "still inside the wrapper script"


provided the run.py script has no fatal errors, you will see the second 
print line as well as the first.

In fact, execfile doesn't merely execute the other script, it executes 
it *inside the current namespace*. Let me explain.

"Namespace" is the technical name for a collection of variables. 
Different places in your code have different variables. Every function 
has its own independent set of local variables, so each function is a 
namespace. Local variables inside one function don't affect local 
variables inside another.

Global variables also live in their own namespace. Normally, each .py 
file is its own namespace, but using execfile is special: rather than 
executing the script in its own namespace, by default it is executed 
in the current namespace.

Try this:

# File run.py
x = 42


# File wrapper.py
x = 23
execfile("run.py")
print x


Running wrapper.py should print 42, not 23.

Normally, that sort of behavious is not what you want. You want other 
scripts to be independent of the current script, so that you can use 
each of them independently. To give an analogy: your screwdriver 
shouldn't suddenly stop working because you've picked up a hammer.

execfile() is useful in the interactive interpreter, but to my mind if 
you want to run BloodPressure02Sorting.py you should just run that file. 
If you are using Linux, probably the easiest way is to have a shell open 
and just enter this:

python BloodPressure02Sorting.py

from the directory containing the script. Many Linux GUI environments, 
like KDE, will also have a "Run command" item under the Start menu.


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


Re: [Tutor] eval use (directly by interpreter vs with in a script)

2014-11-03 Thread Steven D'Aprano
On Mon, Nov 03, 2014 at 09:33:18AM -0800, Albert-Jan Roskam wrote:

> >Real question is what you're trying to do.  eval() and exec() are to be 
> >avoided if possible, so the solutions are not necessarily the easiest.
> 
> I sometimes do something like
> ifelse = "'teddybear' if bmi > 30 else 'skinny'"
> weightcats = [eval(ifelse) for bmi in bmis]
> 
> Would this also be a *bad* use of eval? It can be avoided, but this is so 
> concise.

Two lines, 92 characters. This is more concise:

weightcats = ['teddybear' if bmi > 30 else 'skinny' for bmi in bmis]

One line, 68 characters. And it will be faster too. On average, you 
should expect that:

eval(expression)

is about ten times slower than expression would be on its own.

In my opinion, a *minimum* requirement for eval() is that you don't know 
what the code being evaluated will be when you're writing it. If you can 
write a fixed string inside the eval, like your example above, or a 
simpler case here:

results = [eval("x + 2") for x in values]

then eval is unneccessary and should be avoided, just write the 
expression itself:

results = [x + 2 for x in values]


You *may* have a good reason for using eval if you don't know what the 
expression will be until runtime:

results = [eval("x %c 2" % random.choice("+-/*")) for x in values]


but even then there is often a better way to get the same result, e.g. 
using getattr(myvariable, name) instead of eval("myvariable.%s" % name). 
In the case of the random operator, I'd write something like this:

OPERATORS = {'+': operator.add, '-': operator.sub,
 '/': operator.truediv, '*': operator.mul}
results = [OPERATORS[random.choice("+-/*")](x, 2) for x in values]

which in this case is a little longer but safer and probably faster. 
It's also more easily extensible to a wider range of operators and even 
functions.



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


Re: [Tutor] Newbie Trouble Processing SRT Strings In Text File

2014-11-03 Thread Dave Angel
Please evaluate your email program.  Some of your newline s are
 being lost in the paste into your email.

Matt Varner  Wrote in message:
> TL:DR - Skip to "My Script: "subtrans.py"
> 
> 
> 
> Optional Links to (perhaps) Helpful Images:
> 1. The SRT download button:
> http://i70.photobucket.com/albums/i82/RavingNoah/Python%20Help/tutor1_zps080f20f7.png
> 
> 2. A visual comparison of my current problem (see 'Desire Versus
> Reality' below):
> http://i70.photobucket.com/albums/i82/RavingNoah/Python%20Help/newline_problem_zps307f8cab.jpg
> 
> 
> The SRT File
> 
> 
> The SRT file that you can download for every lesson that has a video
> contains the caption transcript data and is organized according to
> text snippets with some connecting time data.
> 
> 
> Reading the SRT File and Outputting Something Useful
> 
> 
> There may be a hundred different ways to read one of these file types.
> The reliable method I chose was to use a handy editor for the purpose
> called Aegisub.  It will open the SRT file and let me immediately
> export a version of it, without the time data (which I don't
> need...yet).  The result of the export is a plain-text file containing
> each string snippet and a newline character.
> 
> ==
> Dealing with the Text File
> ==
> 
> One of these text files can be anywhere between 130 to 500 lines or
> longer, depending (obviously) on the length of its attendant video.
> For my purposes, as a springboard for extending my own notes for each
> module, I need to concatenate each string with an acceptable format.
> My desire for this is to interject spaces where I need them and kill
> all the newline characters so that I get just one big lump of properly
> spaced paragraph text.  From here, I can divide up the paragraphs how
> I see fit and I'm golden...
> 
> ==
> My first Python script: Issues
> ==
> 
> I did my due diligence.  I have read the tutorial at www.python.org.

But did you actually try out and analyze each concept? Difference
 between read and study.

> I went to my local library and have a copy of "Python Programming for
> the Absolute Beginner, 3rd Edition by Michael Dawson."  I started
> collecting what seemed like logical little bits here and there from
> examples found using Uncle Google, but none of the examples anywhere
> were close enough, contextually, to be automatically picked up by my
> dense 'noobiosity.'  For instance, when discussing string
> methods...almost all operations taught to beginners are done on
> strings generated "on the fly," directly inputted into IDLE, but not
> on strings that are contained in an external file.

When it's in the file, it's not a str. Reading it in produces a
 string or a list of strings.  And once created you can not tell
 if they came from a file, a literal,  or some arbitrary
 expression. 

>  There are other
> examples for file operations, but none of them involved doing string
> operations afterward.  After many errors about not being able to
> directly edit strings in a file object, I finally figured out that
> lists are used to read and store strings kept in a file like the one
> I'm sourcing from...so I tried using that.  Then I spent hours
> unsuccessfully trying to call strings using index numbers from the
> list object (I guess I'm dense).  Anyhow, I put together my little
> snippets and have been banging my head against the wall for a couple
> of days now.
> 
> After many frustrating attempts, I have NEARLY produced what I'm
> looking to achieve in my test file.
> 
> 
> Example - Source
> 
> 
> My Test file contains just twelve lines of a much larger (but no more
> complex) file that is typical for the SRT subtitle caption file, of
> which I expect to have to process a hundred...or hundreds, depending
> on how many there are in all of the courses I plan to take
> (coincidentally, there is one on Python)
> 
> Line 01: # Exported by Aegisub 3.2.1
> Line 02: [Deep Dive]
> Line 03: [CSS Values & Units Numeric and Textual Data Types with
> Guil Hernandez]
> Line 04: In this video, we'll go over the
> Line 05: common numeric and textual values
> Line 06: that CSS properties can accept.
> Line 07: Let's get started.
> Line 08: So, here we have a simple HTML page
> Line 09: containing a div and a paragraph
> Line 10: element nested inside.
> Line 11: It's linked to a style sheet named style.css
> Line 12: and this is where we'll be creating our new CSS rules.
> 
> 
> My Script: "subtrans.py"
> 
> 
> # Open the target file, create file object
> f = open('tmp.txt', 'r')
> 
> # Create an output file to write the changed strings to
> o = open('result.txt', 'w')
> 
> # Create a list object that holds all the strings in the file object
> lns = f.readlines()
> 

Re: [Tutor] Fwd: Re: Simple guessing game - need help with the math

2014-11-03 Thread Dave Angel

You're still using html mail, and still top-posting. 

>

> But my curiosity is still begging me for an answer regarding my original 
> approach. Is there a way to manage the functionality of be round function 
> such that it does not strip any data to the right of the decimal point?

That's the whole point of round (). If you tell what you wish it
 to do, with sample data and desired results,  we can probably
 suggest an approach.  Or you could look at the message I posted
 some time ago, suggesting adding one before dividing by
 2.

Sometimes the best answer is to truncate by converting to int. But
 the increment is frequently needed as well.

-- 
DaveA

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


Re: [Tutor] Flow of execution of execution

2014-11-03 Thread William Becerra
Thank you guys

On Mon, Nov 3, 2014 at 11:26 PM, Alan Gauld 
wrote:

> On 03/11/14 18:04, William Becerra wrote:
>
>  def printMultiples(n, high):
>>  i = 1
>>  while i<=high:
>>  print n*i, "\t",
>>  i = i + 1
>>  print
>>
>
>  def multipleTable(high):
>>  i = 1
>>  while i<=high:
>>  printMultiples(i, i)
>>  i = i + 1
>>  print
>>
>
>  print multipleTable(6)
>>
>> when i run this code the result i get is
>>
>> 1
>> 2 4
>> 3 6 9
>> 4 8 12 16
>> 5 10 15 20 25
>> 6 12 18 24 30 36
>>
>
>  Can someone please explain why does it print a triangular table and not
>> a square table like this one:
>>
>
> Because you call print Multiples() from within multipleTable()
> Each time the loop executes the value of i increases so each line printed
> gets longer. The first line is printed by printMultiples(1,1)
> The second is called with printMultiples(2,2) and so on up to
> printMultiples(6,6).
>
> This yields a triangular printout.
>
>  is there any documentation i can read on tables?
>>
>
> Not really, there's no such thing as a table in Python programming, its
> just a structure you create. In practice its usually composed of a list of
> lists.
>
> HTH
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> 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] Some shameless self promotion

2014-11-03 Thread Alan Gauld

On 04/11/14 00:55, memilanuk wrote:

On 11/02/2014 05:22 PM, Alan Gauld wrote:

For anyone who might be interested

http://www.amazon.com/Python-Projects-Laura-Cassell/dp/111890866X

A book aimed at those who have just finished their first python tutorial
and are wondering what to do next...



Do you know if there are any plans for an electronic version i.e. pdf or
kindle?


I assume so but I'm only the author and that's a decision
for the publishers! :-)


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos

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