Re: [Tutor] question about strip() and list comprehension

2014-04-09 Thread Jared Nielsen
Thank Danny,
That's much more clear.
But I still don't understand what's happening with:

if line.strip()

Is that stripping the line of white space at the same time that it is
testing it?


On Tue, Apr 8, 2014 at 3:44 PM, Danny Yoo  wrote:

> > Could someone explain why and how this list comprehension with strip()
> > works?
> >
> > f = open('file.txt')
> > t = [t for t in f.readlines() if t.strip()]
> > f.close()
> > print "".join(t)
>
>
> Hi Jared,
>
>
> Let me rewrite this without the list comprehension, while preserving
> behavior.
>
> ##
> inputFile = open('file.txt')
> lines = []
> for line in inputFile.readlines():
> if line.strip():
> lines.append(line)
> inputFile.close()
> print "".join(lines)
> ##
>
> I am changing the names of the variables from the original code
> because I find it very difficult to distinguish 't' from 'f'
> sometimes, and because those names are very tied in my mind to
> something else entirely ("true" and "false").
>
>
> Does the above code make more sense to you than the version using the
> list comprehension syntax, or is there something there that is still
> confusing?
>
>
> Good luck to you.
>



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


Re: [Tutor] question about strip() and list comprehension

2014-04-09 Thread Jared Nielsen
Thanks Danny!
That was an awesome explanation.


On Tue, Apr 8, 2014 at 7:05 PM, Danny Yoo  wrote:

>
>> if line.strip()
>>
>> Is that stripping the line of white space at the same time that it is
>> testing it?
>>
>>
>
> Two features about Python:
>
> 1.  Strings are immutable, so the above is computing what a
> whitespace-stripped line would look like.  So that means that
> 'line.strip()' is doing just a computation: it's not mutating the original
> line, but computing a new string that has its leading and trailing
> whitespace stripped away.
>
>
> 2.  Empty strings are treated as false values.  I'm not happy with how
> loose Python treats truth, and would rather prefer:
>
> if line.strip() != "": ...
>
> so that the thing being tested is explicitly either True or False.  I like
> my truth to be black and white, but I suppose I'll have to grimace and bear
> the fuzziness.  :P
>
>
> Together, we see those two features allow us to look at the test in the
> Python code:
>
>if line.strip(): ...
>
> and rephrase it in English as:
>
>"If the line consists of at least one non-whitespace character: ..."
>



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


[Tutor] When to use classes

2014-04-09 Thread Ni hung
Hi

I am learning programming using python. I think of solving a problem using
functions and for this reason all/most of my code consists of functions and
no classes.  I have some understanding of classes/Object Oriented
Programming. I can write simple classes but I do not understand when to use
classes.

Any suggestions, pointers to documents/blogs/books are welcome!

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


Re: [Tutor] question about strip() and list comprehension

2014-04-09 Thread Peter Otten
Steven D'Aprano wrote:

> On Tue, Apr 08, 2014 at 02:38:13PM -0600, Jared Nielsen wrote:
>> Hello,
>> Could someone explain why and how this list comprehension with strip()
>> works?
>> 
>> f = open('file.txt')
>> t = [t for t in f.readlines() if t.strip()]
>> f.close()
>> print "".join(t)
>> 
>> I had a very long file of strings filled with blank lines I wanted to
>> remove. I did some Googling and found the above code snippet, but no
>> clear explanation as to why it works. I'm particularly confused by how
>> "if t.strip()" is removing the blank lines.
> 
> It isn't. Rather, what it is doing is *preserving* the non-blank lines.
> 
> The call to strip() removes any leading and trailing whitespace, so if
> the line is blank of contains nothing but whitespace, it reduces down to
> the empty string:
> 
> py> ''.strip()
> ''
> 
> Like other empty sequences and containers, the empty string is
> considered to be "like False", falsey:
> 
> py> bool('')
> False
> 
> 
> So your list cmprehension (re-written to use a more meaningful name)
> which looks like this:
> 
> [line for line in f.readlines() if line.strip()
> 
> iterates over each line in the file, tests if there is anything left
> over after stripping the leading/trailing whitespace, and only
> accumulates the lines that are non-blank. It is equivalent to this
> for-loop:
> 
> accumulator = []
> for line in f.readlines():
> if line.strip():  # like "if bool(line.strip())"
> accumulator.append(line)
> 
> 
>> I also don't fully understand the 'print "".join(t)'.
> 
> I presume you understand what print does :-) so it's only the "".join(t)
> that has you confused. This is where the interactive interpreter is
> brilliant, you can try things out for yourself and see what they do. Do
> you know how to start the interactive interpreter?
> 
> (If not, ask and we'll tell you.)
> 
> py> t = ['Is', 'this', 'the', 'right', 'place', 'for', 'an', 'argument?']
> py> ''.join(t)
> 'Isthistherightplaceforanargument?'
> py> ' '.join(t)
> 'Is this the right place for an argument?'
> py> '--+--'.join(t)
> 'Is--+--this--+--the--+--right--+--place--+--for--+--an--+--argument?'
> 
> 
> In your case, you have a series of lines, so each line will end with a
> newline:
> 
> py> t = ['line 1\n', 'line 2\n', 'line 3\n']
> py> ''.join(t)
> 'line 1\nline 2\nline 3\n'
> py> print ''.join(t)
> line 1
> line 2
> line 3
> 
> 
>> The above didn't remove the leading white space on several lines, so I
>> made the following addition:
>> 
>> f = open('file.txt')
>> t = [t for t in f.readlines() if t.strip()]
>> f.close()
>> s = [x.lstrip() for x in t]
>> print "".join(s)
> 
> 
> You can combine those two list comps into a single one:
> 
> f = open('file.txt')
> lines = [line.lstrip() for line in f.readlines() if line.strip()]
> f.close()

For those readers who are starting out with python but are not absolute 
beginners let me just mention that in

[line.lstrip() for line in f.readlines() if line.strip()]

the readlines() call is superfluous -- it reads the lines of the file into a 
list thus putting them all into memory when you need only one at a time, 
effectively more than doubling the amount of memory needed. So get into the 
habit of iterating over a file directly

for line in f:
   

In the case where you want to filter and modify lines you can omit the list 
with all modified lines, too:

import sys
for line in f:
line = line.lstrip()
sys.stdout.write(line)

Here sys.stdout.write() writes to stdout like print, but expects a string 
and doesn't add a newline. Note that I didn't add

if line:
sys.stdout.write(line)

-- it doesn't matter much if you do or don't write an empty string. Now what 
about the listcomp? An experienced programmer would use a generator 
expression which is similar to the listcomp, but just deals with the current 
line. Your script will never run out of memory no matter whether the file 
has one billion or one billion billion lines (diskspace and runtime are 
another matter). A genexp looks similar to a listcomp

lines = (line.lstrip() for line in f)

but has the limitation here that you can only iterate over the lines while 
the file is still open. Together with a sophisticated way to close the file

with open("file.txt") as f:
... # do something with the file
print "f is now closed without an explicit close() call"
print "even if an error occured while processing the file"

the whole script that removes empty lines and leading whitespace can be 
written as

import sys
with open("file.txt") as f:
sys.stdout.writelines(line.lstrip() for line in f)

What was I saying? Ah: FORGET ABOUT file.readlines(). You hardly ever need 
it.


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


Re: [Tutor] dictionary keys

2014-04-09 Thread Alex Kleider

On 2014-04-08 23:55, Peter Otten wrote:


You can create and sort the list in a single step:

l = sorted(myDict)



Thank you again; this is a new idiom for me.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] When to use classes

2014-04-09 Thread Alan Gauld

On 09/04/14 06:58, Ni hung wrote:


functions and no classes.  I have some understanding of classes/Object
Oriented Programming. I can write simple classes but I do not understand
when to use classes.


If you are just learning it may be that the programs you have written 
are too small to make classes useful. Classes tend to come into their 
own on larger programs.


As to when to use them: if you see a lot of functions all taking the 
same set of data inputs then there's a good chance you should turn that 
into a class that holds the data and has the functions as methods.


Alternatively if you need to manipulate several copies of a thing then 
defining thing as a class and creating multiple instances makes sense 
(Think of strings in Python - how much harder it would be to work with 
strings if they weren't classes. Up until Python v2 that's exactly what 
we had to do.)


As projects get bigger still, it starts to become more natural to
think of the program in terms of classes because they become more
of an expression of your real-world problem domain than an expression of 
programming data sets. Think about classes like employee, order, 
bankaccount, building, etc (Although those with a formal math background 
often find this hardest to do since they have had it

beaten into their skulls that things consist of functions and data!)

But don't sweat about it, you can go a long way without classes. And 
when they are needed it usually becomes clear based on what I said in 
paragraph 2 above.


--
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] When to use classes

2014-04-09 Thread Dave Angel
Ni hung  Wrote in message:

(Please post in text format,  not html.  It doesn't matter for
 your particular message,  but several things can go wrong, where
 some or most of us do not see what you meant to post)

> I am learning programming using python. I think of solving a
>  problem using functions and for this reason all/most of my
>  code consists of functions and no classes.  I have some understanding of 
> classes/Object Oriented Programming. I can write simple classes but I do not 
> understand when to use classes

Welcome to the forum., and to Python. 

You may not realize it, but you're already using classes in even
 the simplest Python program. int is a class, list and dict are
 classes. Even a function is an instance of a class.  So what
 you're really asking is when you should create your own new
 classes. 

The short answer is whenever the standard ones (there are many
 hundreds of them,  maybe thousands)
 is inadequate for your
 needs.  When writing simple programs,  compositions of existing
 classes can take you a long way.  When you need something a bit
 trickier,  Python has ways of generating classes that you might
 not realize,  such as namedtuple. 

At its simplest,  a class is a way to bundle up data items and
 method items so that each instance has all of those attributes
 with a simple call to the constructor. The simplest class is
 probably NoneType,  which has about 20 attributes,  I think all
 dunder ones.  (Use dir () to look at objects and find their
 attributes,  and help () to learn more about most
 attributes)

But sooner or later,  you find yourself with a dict of keys and
 values,  where the values are lists of tuples,  and you'll throw
 up your hands and write a nice class to make it easier to keep
 track of things. 

-- 
DaveA

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


[Tutor] Delete unwanted rows

2014-04-09 Thread Alexis Prime
Hello,

My question is whether I should write a loop or a function to delete rows.

I'm using pandas. But you may be able to help me as my question is about
the reasoning behind programming.

I have a pandas dataframe that looks like this, covering all countries in
the world, for over 200 rows and many columns:

Canada20
China  112
Germany 10
Japan  12
Martinique 140
Mexico180
Saint Kitts90
Saint Martins133
Saint Helena 166
USA18

# So I write a list of small countries that I wish to exclude from my
analysis. What I want to do is to delete the rows from my dataframe.

toexclude = ['Martinique', 'Saint Kitts', 'Saint Martins', 'Saint
Helena']

After this, should I write a loop to loop through the dataframe, find the
countries that I want to delete, and then delete the rows?

Or should I write a function, which deletes those rows, and then returns me
a new and trimmed dataframe?

Thank you for helping me figure this out.

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


Re: [Tutor] Delete unwanted rows

2014-04-09 Thread Mark Lawrence

On 09/04/2014 10:23, Alexis Prime wrote:

Hello,

My question is whether I should write a loop or a function to delete rows.

I'm using pandas. But you may be able to help me as my question is about
the reasoning behind programming.

I have a pandas dataframe that looks like this, covering all countries
in the world, for over 200 rows and many columns:

Canada20
China  112
Germany 10
Japan  12
Martinique 140
Mexico180
Saint Kitts90
Saint Martins133
Saint Helena 166
USA18

# So I write a list of small countries that I wish to exclude from my
analysis. What I want to do is to delete the rows from my dataframe.

 toexclude = ['Martinique', 'Saint Kitts', 'Saint Martins', 'Saint
Helena']

After this, should I write a loop to loop through the dataframe, find
the countries that I want to delete, and then delete the rows?

Or should I write a function, which deletes those rows, and then returns
me a new and trimmed dataframe?

Thank you for helping me figure this out.

Alexis



If you are going to do this repeatedly you'd be better off writing a 
function.  I don't know enough about pandas to say whether the rows 
should be deleted within a loop in the function or a new data frame is 
returned.  But before you write any code, have to checked to see if 
there is a function or method in pandas that does this for you?


--
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


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


Re: [Tutor] Delete unwanted rows

2014-04-09 Thread Peter Otten
Alexis Prime wrote:

> Hello,
> 
> My question is whether I should write a loop or a function to delete rows.
> 
> I'm using pandas. But you may be able to help me as my question is about
> the reasoning behind programming.
> 
> I have a pandas dataframe that looks like this, covering all countries in
> the world, for over 200 rows and many columns:
> 
> Canada20
> China  112
> Germany 10
> Japan  12
> Martinique 140
> Mexico180
> Saint Kitts90
> Saint Martins133
> Saint Helena 166
> USA18
> 
> # So I write a list of small countries that I wish to exclude from my
> analysis. What I want to do is to delete the rows from my dataframe.
> 
> toexclude = ['Martinique', 'Saint Kitts', 'Saint Martins', 'Saint
> Helena']
> 
> After this, should I write a loop to loop through the dataframe, find the
> countries that I want to delete, and then delete the rows?
> 
> Or should I write a function, which deletes those rows, and then returns
> me a new and trimmed dataframe?
> 
> Thank you for helping me figure this out.

The dataset is so small that I would not spend much time on efficiency or 
philosophical considerations, and use the solution that is easiest to code. 
In generic Python this means typically iterating over the data and building 
a new list (I'm sorry, I don't know how this translates into pandas):

data = [
   ("Canada", 20),
   ("China", 112),
   ...
]
excluded = {"Martinique", "Saint Kitts", ...}
cleaned_data = [row for row in data if row[0] not in excluded]

However, pandas is a specialist topic and if you expect to work more with it 
you may want to learn the proper idiomatic way to do it. You should then  
ask again on a mailing list that is frequented by the pandas experts -- 
python-tutor is mostly about the basics of generic Python.

Finally, as someone who knows Python well, just a little numpy, and nothing 
about pandas I decided to bang my head against the wall a few times until I 
came up with the following hack:

import pandas
data = """\
Canada20
China  112
Germany 10
Japan  12
Martinique 140
Mexico180
Saint Kitts90
Saint Martins133
Saint Helena 166
USA18
"""
rows = [line.rsplit(None, 1) for line in data.splitlines()]
names = [row[0] for row in rows]
values = [int(row[1]) for row in rows]

df = pandas.DataFrame(dict(name=names, value=values))

class Contain:
def __init__(self, items):
self.items = set(items)
def __ne__(self, other):
return other not in self.items
def __eq__(self, other):
return other in self.items

exclude = Contain([
'Martinique',
'Saint Kitts',
'Saint Martins',
'Saint Helena'])

cleaned_df = df[df.name != exclude]

print("Before:")
print(df)
print()
print("After:")
print(cleaned_df)

[The trick here is to convert the "in" into the "==" operator because the 
latter can return arbitrary objects while the former is limited to bool]

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


[Tutor] masking library files

2014-04-09 Thread ugajin

Is it common for files saved to a working directory to 'mask' library files 
located in the Python framework?

-A

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


Re: [Tutor] Delete unwanted rows

2014-04-09 Thread Mark Lawrence

On 09/04/2014 15:14, Peter Otten wrote:

Alexis Prime wrote:

However, pandas is a specialist topic and if you expect to work more with it
you may want to learn the proper idiomatic way to do it. You should then
ask again on a mailing list that is frequented by the pandas experts --
python-tutor is mostly about the basics of generic Python.



gmane.comp.python.pydata or 
https://groups.google.com/forum/#!forum/pydata but I'd definitely 
recommend the former.


--
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


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


Re: [Tutor] masking library files

2014-04-09 Thread Mark Lawrence

On 09/04/2014 15:17, uga...@talktalk.net wrote:

Is it common for files saved to a working directory to 'mask' library
files located in the Python framework?

-A



Yes.

--
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


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


Re: [Tutor] masking library files

2014-04-09 Thread Alan Gauld

On 09/04/14 15:17, uga...@talktalk.net wrote:

Is it common for files saved to a working directory to 'mask' library
files located in the Python framework?


Python looks in the local directory first so if you name a module with 
the name of one of the standard modules Python will, quite reasonably, 
assume you want your module to be used rather than the standard one.


The best solution is not to name your modules the same as the
standard library ones.

When it comes to non-standard libraries then it becomes a matter of 
looking at the sys.path value and the order of search defined there.

Which may, in turn, depend on how they were installed.

--
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] When to use classes

2014-04-09 Thread Cameron Simpson
On 08Apr2014 22:58, Ni hung  wrote:
> I am learning programming using python. I think of solving a problem using
> functions and for this reason all/most of my code consists of functions and
> no classes.  I have some understanding of classes/Object Oriented
> Programming. I can write simple classes but I do not understand when to use
> classes.

Loosely speaking, you can usefully make a class when there is a
particular type of object on which you are make an assortedment of
operations.

For example, if you have several functions looking like this:

  def modify_thing1(obj1, ...):

  def add_something(obj1, ...):

and so on, where obj1 is always the same kind of thing, representing
some well define idea you have when writing the code.

In that circumstance you might make a class looking like this:

  class ObjName(object):

def __init__(self):
  # "self" here is an "obj1" as used above
  # set whatever attributes an "obj1" should have to start with
  # you can pass in some of those values as parameters to the __init__ 
function

def modify(self, ...):
  # this is the same as "modify_thing1(obj1, ...)" earlier
  # using "self" as "obj1"

def add(self, ...):
  # this is the same as "add_something(obj1, ...)" earlier

Then your code looks like:

  obj1 = ObjName()
  ...
  obj1.modify(5)
  obj1.add(6)

or what have you.

This has several advantages:

  - all the code that affects this kind of object is in one place

  - you can remove all the specifics of how things are done from the main
code and keep them inside the class methods.
This makes the main code more readable (if you pick good method names)
and shorter (also more readable, usually).

  - later, if need be, you can change the inner workings of how
ObjNames work without changing the main code, or at least not
much - sometimes not at all

Anyway, that's an ok rule of thumb for when to make a class: when
you have a bunch of operations to do to one type of thing.

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


[Tutor] difference between expressions and statements

2014-04-09 Thread Jared Nielsen
Hi Pythons,
Could someone explain the difference between expressions and statements?
I know that expressions are statements that produce a value.
I'm unclear on functions and especially strings.
Are any of the following expressions?

print(42)
print("spam")
spam = 42
print(spam)

Is the first example producing a value or simply displaying an integer?
Does a string count as a value?
Is a variable assignment considered a value?
If I print a variable is that considered production of a value?

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


Re: [Tutor] difference between expressions and statements

2014-04-09 Thread Danny Yoo
> Could someone explain the difference between expressions and statements?
>
> I know that expressions are statements that produce a value.

Yes, that's pretty much it.  If you can point your finger at the thing
and say that it produces a value, it's an expression.


> Are any of the following expressions?
>
> print(42)
> print("spam")
> spam = 42
> print(spam)

See:

https://docs.python.org/2/reference/expressions.html

Technically, the only things that count as expressions have to fit the
shape of something described in that documentation link.



Your question about assignment being an expression or not is something
you can find out by seeing where "Assignment statements" show in:

https://docs.python.org/2/reference/index.html


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


[Tutor] 2014 PyCamps

2014-04-09 Thread Chris Calloway

Need some in-person and structured Python tutoring?

PyCamp is an ultra-low-cost, five-day, intensive Python boot camp 
program by a user group for user groups. PyCamp has taught Python 
fundamentals to thousands of beginners for nine years while sponsoring 
Python regional conferences, symposia, sprints, scholarships, and user 
groups. You can get up to speed on the most modern programming language 
at PyCamp.


This year choose from two PyCamps:

Wisconsin PyCamp 2014, June 13-17, University of Wisconsin-Oshkosh
http://tripython.org/wiscpy14
Wisconsin PyCamp 2014 is a training program of Plone Symposium Midwest.
http://midwest.plonesymp.org
Wisconsin PyCamp 2014 is all-day catered (breakfast, lunch, snacks).

or

PyOhio PyCamp 2014, July 21-25, The Ohio State University
http://tripython.org/pyohio14
PyOhio PyCamp 2014 is a pre-conference training program of PyOhio
http://pyohio.org
Scholarships for women and minorities are available for PyOhio PyCamp.

--
Sincerely,

Chris Calloway http://nccoos.org/Members/cbc
office: 3313 Venable Hall   phone: (919) 599-3530
mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Python Help

2014-04-09 Thread Adam Grierson
Hi

 

I'm using 3D climate data (ending in “.nc”). The cube contains time, longitude 
and latitude. I would like to look at the average output over the last 20 
years. The time field spans back hundreds of years and I only know how to 
collapse the entire field into a mean value. How can I tell python to collapse 
just the last 20 years into a mean value? 

 

Thank you

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


Re: [Tutor] difference between expressions and statements

2014-04-09 Thread Alan Gauld

On 09/04/14 17:49, Jared Nielsen wrote:

Hi Pythons,
Could someone explain the difference between expressions and statements?
I know that expressions are statements that produce a value.


Yep, that's it.


I'm unclear on functions and especially strings.


Unclear in what way? Both functions and strings are expressions,
in that they produce, or are, values.


Are any of the following expressions?
print(42)
print("spam")
spam = 42
print(spam)


Yes, 3 are expressions, and all 4 are statements containing expressions.


Is the first example producing a value or simply displaying an integer?


It does actually produce a value but its not the integer that is 
displayed. The default value for any function (including print() )

is None... You can prove that by trying:

>>> print( print(42) )
42
None

The 42 is the output displayed by the innermost print()
The None is the value returned by the inner print function.

The Python interpreter normally suppresses the None from a print 
function but because I explicitly told it to print the return from print 
it did it in this case.



Does a string count as a value?


Yes, certainly.


Is a variable assignment considered a value?


No, its a statement but not an expression.
(In Python at least, in some other languages the rules are different)


If I print a variable is that considered production of a value?


Yes, as above. But the value produced is the None returned
by the print function not the value that print displays.


HTH

And did I just do your homework? hmmm... I'll give
you the benefit of the doubt.

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

2014-04-09 Thread Alan Gauld

On 09/04/14 20:59, Adam Grierson wrote:


I'm using 3D climate data (ending in “.nc”). The cube contains time,
longitude and latitude. I would like to look at the average output over
the last 20 years. The time field spans back hundreds of years and I
only know how to collapse the entire field into a mean value. How can I
tell python to collapse just the last 20 years into a mean value?


This group is for teaching the fundamentals of the Python language and 
its standard library. You probably can solve this using standard Python 
but I suspect there will be more specific libraries around that you can 
install that will help with this problem. Those libraries will likely be 
a better place to ask.


That having been said, if you want a pure Puython solution we can try to 
help, but we need a lot more detail about what the data looks like and 
what exactly you expect out. Your description is a bit vague and while I 
might be able to find out what you mean by Googling a bit, I'm not that 
keen to spend my time that way. The more you help us the more we can 
help you...


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

2014-04-09 Thread Chris Calloway

On 4/9/2014 3:59 PM, Adam Grierson wrote:

I'm using 3D climate data (ending in “.nc”). The cube contains time,
longitude and latitude. I would like to look at the average output over
the last 20 years. The time field spans back hundreds of years and I
only know how to collapse the entire field into a mean value. How can I
tell python to collapse just the last 20 years into a mean value?


An ".nc" file extension is NetCDF. NetCDF can be served by a DAP server. 
A DAP server can be sent a DAP request by a Python DAP client to drill 
for results confined to particular variables, a geographic bounding box, 
and a stop and start timestamp. See:


http://pydap.org

Or you can simply subset the desired subarray of NetCDF data using SciPy:

http://docs.scipy.org/doc/scipy/reference/generated/scipy.io.netcdf.netcdf_file.html

Here's a tutorial:

snowball.millersville.edu/~adecaria/ESCI386P/esci386-lesson14-Reading-NetCDF-files.pdf

--
Sincerely,

Chris Calloway http://nccoos.org/Members/cbc
office: 3313 Venable Hall   phone: (919) 599-3530
mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] difference between expressions and statements

2014-04-09 Thread Ben Finney
Jared Nielsen  writes:

> Could someone explain the difference between expressions and
> statements?

For general programming terminology, the Wikipedia articles tend to be
good.

https://en.wikipedia.org/wiki/Expression_%28computer_science%29>
https://en.wikipedia.org/wiki/Statement_%28computer_science%29>

Roughly:

* An expression evaluates to some single value.

* A statement does some action.

> I know that expressions are statements that produce a value.

Expressions are not statements. A statement *may* be an expression.

Statements in Python can consist of an expression, or can consist of
other things.

> I'm unclear on functions and especially strings.

You're looking for a strict dichotomy which doesn't exist, and I think
that's confusing you.

> Are any of the following expressions?

They can all be statements.

> print(42)
> print("spam")

These are function calls. A function call evaluates to a value, so is
always an expression.

> spam = 42

Assignment is only a statement in Python. The statement is an
instruction to perform the assignment.

The left side is an expression evaluating to a reference; the right side
is an expression evaluating to a value.

> Is a variable assignment considered a value?

In Python, assignment (try not to think in terms of “variable”;
assignment is the act of binding a reference to a value) is always a
statement.

In other languages, assignment can return a value and is therefore an
expression. That is not the case in Python.

> Is the first example producing a value or simply displaying an
> integer?
> Does a string count as a value?

Yes to all these.

Learn more about statements – especially the fact that statements
consist sometimes of expressions alone, sometimes of other things
including expressions – at the Python Language Reference
https://docs.python.org/3/reference/expressions.html>
https://docs.python.org/3/reference/simple_stmts.html>.

-- 
 \ “If nature has made any one thing less susceptible than all |
  `\others of exclusive property, it is the action of the thinking |
_o__)  power called an idea” —Thomas Jefferson |
Ben Finney

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


Re: [Tutor] difference between expressions and statements

2014-04-09 Thread Dave Angel
Jared Nielsen  Wrote in message:
> Hi Pythons,
> Could someone explain the difference between expressions and statements?
> I know that expressions are statements that produce a value.
> I'm unclear on functions and especially strings.
> Are any of the following expressions?
> 
> print(42)
> print("spam")
> spam = 42
> print(spam)
> 
> Is the first example producing a value or simply displaying an integer?
> Does a string count as a value?
> Is a variable assignment considered a value?
> If I print a variable is that considered production of a value?
>

Can't answer till you specify Python version.  The other answers
 all seem to assume version 3.x. In version 2, these are all
 statements,  none are expressions.


-- 
DaveA

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


Re: [Tutor] masking library files

2014-04-09 Thread Dave Angel
uga...@talktalk.net Wrote in message:
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
> 

A message left in invisible ink.  Please post in text form, not
 html, as html offers too many ways to mess up the message.
 

-- 
DaveA

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


Re: [Tutor] masking library files

2014-04-09 Thread ugajin

 Please write in plain English if you want to be understood.

 

 

-Original Message-
From: Dave Angel 
To: tutor@python.org
Sent: Thu, 10 Apr 2014 2:00
Subject: Re: [Tutor] masking library files


uga...@talktalk.net Wrote in message:
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
> 

A message left in invisible ink.  Please post in text form, not
 html, as html offers too many ways to mess up the message.
 

-- 
DaveA

___
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