Re: [Tutor] (no subject)

2014-07-21 Thread Alan Gauld

On 21/07/14 01:34, Marc Tompkins wrote:


noticed that you often advise it.  I don't know who _does_ think this
is a desirable pattern; I'd love to hear their argument for it - it
must be really good.



Nope, it doesn't need to be "really good", it just needs to
have enough advantage over the alternatives for people
to prefer it.

In the case of while loops the options are:

1) while True:

while True:
read input
if end condition: break
process loop

2) While test

read input
while test:
   process loop
   read input


The argument against the latter form is simply
that you have to maintain the read input line
in two places.

So far as I can tell, that's it. But it seems
to be enough to make it the default Python while
idiom. Now that doesn't mean that you should not
use form 2 in Python, form 1 is only justified
if you need to repeat the call (or the test).
There are many cases where form 2 would be
better,. and sadly sometimes we see
form 1 being used when it should not.

But even more often we see while loops being
used where they should not. A for loop is
usually a better option if the number of
iterations is known.

Loop choice is one area where Python is not
as expressive as other languages but the
two(*) we have are adequate if not ideal.


(*)And you can extend those somewhat using
generators and itertools.

--
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] Is this possible for a newbie?

2014-07-21 Thread Joseph Lee

Hi,
Answers are below.


- Original Message -
From: keith papa Am a newbie to programming and I started learning python days 
ago.  I have this idea I want to execute, am a big sport and 
fantasy fan and I wanted to create something that will make it 
things a little easy for me.  My idea is simple I want to create 
a program that I can enter name and some information about a 
player, for example:


NFL plays:

Jamaal Charles RB : ATT 259 , YDS 1,287 , AVG 5.0, TD 12, REC 70

Tony Romo QB: CMP% 63.9, YDS 3,828 , TD 31, INT 10, Rating 96.7

Dez Bryant WR: REC 93, YDS 1,233, AVG 13.3, LNG 79, TD 13

and other players information.

I want to be able to ask the program which QB is best on my list 
and it give me the names of all the QB on my list, or ask for WR 
on my list and it gives me all the WR on my list, and also I want 
to be able to crossed out name simply by typing the players name.
What do I need to lean in order to accomplish this? string, 
variable functions?

feel free to ask any questions.

JL:
I think learning about tuples and dictionaries might be your 
friends.  There is a data type called tamed tuple that assigns 
names to fields, so you can ask your program to give you needed 
info by sorting by field names.

Hope this helps.
Cheers,
Joseph


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


Re: [Tutor] (no subject)

2014-07-21 Thread LN A-go-go
Dear Gurus,
Thank-you thank-you, one more time, thank-you.
I am over that hurdle and have the other: converting the list of characters 
that was just created by the split - into integers so I can manipulate them.  I 
was trying to convert to a string, then to integers.  I have been scouring the 
web for casting integers, converting to strings and also trying to look up the 
error messages: I apologize for the mess - I was trying everything.

Sigh,
Python in the hands of the naïve

LN.

>>> numlist = data_value
>>> numlist
['36', '39', '39', '45', '61', '54', '61', '93', '62', '51', '47', '72', '54', 
'36', '62', '50', '41', '41', '40', '62', '62', '58', '57', '54', '49', '43', 
'47', '50', '45', '41', '54', '57', '57', '55', '62', '51', '34', '57', '55', 
'63', '45', '45', '42', '44', '34', '53', '67', '58', '56', '43', '33']
>>> print sum(numlist)
Traceback (most recent call last):
  File "", line 1, in 
    print sum(numlist)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> orange_drinkers = int(data_value)
Traceback (most recent call last):
  File "", line 1, in 
    orange_drinkers = int(data_value)
TypeError: int() argument must be a string or a number, not 'list'
>>> int(data_value)
Traceback (most recent call last):
  File "", line 1, in 
    int(data_value)
TypeError: int() argument must be a string or a number, not 'list'
>>> numstring = raw_input(">")
>
>>> type(numlist)

>>> b = str(numlist)
>>> c = []
>>> for digit in b:
 c.append (int(digit))
 
Traceback (most recent call last):
  File "", line 2, in 
    c.append (int(digit))
ValueError: invalid literal for int() with base 10: '['
>>> i = 0
>>> str(numlist)
"['36', '39', '39', '45', '61', '54', '61', '93', '62', '51', '47', '72', '54', 
'36', '62', '50', '41', '41', '40', '62', '62', '58', '57', '54', '49', '43', 
'47', '50', '45', '41', '54', '57', '57', '55', '62', '51', '34', '57', '55', 
'63', '45', '45', '42', '44', '34', '53', '67', '58', '56', '43', '33']"
>>> int(x[,numlist])
SyntaxError: invalid syntax
>>> int(x[numlist])
Traceback (most recent call last):
  File "", line 1, in 
    int(x[numlist])
TypeError: 'int' object has no attribute '__getitem__'
>>> for x in numlist:
 i.append (int(x))
 
Traceback (most recent call last):
  File "", line 2, in 
    i.append (int(x))
AttributeError: 'int' object has no attribute 'append'
>>> 




  


On Sunday, July 20, 2014 6:21 PM, Wolfgang Maier 
 wrote:
  


On 20.07.2014 22:37, Marc Tompkins wrote:
>
> First of all, I would take advantage of the "with" construction, like so:
>
> with open('C:/Python27/egund919/Program1/BOJ_B.txt','r') as infile:
>      #do stuff with infile
>
> When the block of code inside of the "with" section finishes, Python
> will take care of closing the file for you - even if your program
> encountered an error.  MAJOR advantage over doing it yourself.
>

Yes, definitely, as you have experienced yourself now.

> Second, there's no need to import "string" anymore; all of the
> functions defined in that module are native methods of strings.
> "line" is a string, so you can just do "line.split()".  split()
> returns a list; you can get the first item in that list with
> line.split()[0], the second item with line.split()[1], etc.
>

I fully agree on the string method part. As for the use of 
line.split()[0] and [1], see my comment in the code below.

> Third, free your mind from the shackles of counting how many objects
> are in a list and using that counter as the index of your loops - this
> is not the Python way!  Instead, let Python take care of the counting
> and indexing for you.
>

True (see the earlier suggestion of using enumerate()), but I'm sure 
you'll learn this over time.

> Fourth (and here I differ from some of the others on this list,
> notably Alan G) - I don't like the "while True: / break" paradigm.
> Your mileage may vary, but I find it makes it harder to understand
> what the program is actually trying to achieve.  In your case, you
> read a line from the file, then check whether it contains anything; I
> like to move the readline() to the bottom of the loop.

In my opinion, this is less readable than the original code. I know that 
some people (usually coming from C or other languages with more 
expressive while loops) don't like it, but there's nothing wrong, in 
general, with using while True with break. It's perfectly pythonic.

Direct use of the file object in a for loop has been suggested already 
and THAT's more readable.

>
> Having said all that, here's my suggested version:
>
> state_name = []
> data_value = []
> with open('C:/Python27/egund919/Program1/BOJ_B.txt','r') as infile:
>      line = infile.readline()  # Doing this twice because you
> apparently want to discard the first line...?
>      line = infile.readline()
>      while line:
>          state_name.append(line.split()[0])
>          data_value.append(line.split()[1])

Rewriting the original

            States, OJ = string.split(line)

as

            states

[Tutor] Unhandled exception

2014-07-21 Thread yarteydegre...@gmail.com
I just want to know if an unhandled exception is a bug in my programs! 

Degreat

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


Re: [Tutor] (no subject)

2014-07-21 Thread Wolfgang Maier

On 21.07.2014 01:48, LN A-go-go wrote:> Dear Gurus,
> Thank-you thank-you, one more time, thank-you.
> I am over that hurdle and have the other: converting the list of
> characters that was just created by the split - into integers so I can
> manipulate them.  I was trying to convert to a string, then to
> integers.  I have been scouring the web for casting integers, converting
> to strings and also trying to look up the error messages: I
> apologize for the mess - I was trying everything.
>
> Sigh,
> Python in the hands of the naïve
>
> LN.
>
 numlist = data_value
 numlist
> ['36', '39', '39', '45', '61', '54', '61', '93', '62', '51', '47', '72',
> '54', '36', '62', '50', '41', '41', '40', '62', '62', '58', '57', '54',
> '49', '43', '47', '50', '45', '41', '54', '57', '57', '55', '62', '51',
> '34', '57', '55', '63', '45', '45', '42', '44', '34', '53', '67', '58',
> '56', '43', '33']
 print sum(numlist)
> Traceback (most recent call last):
>File "", line 1, in 
>  print sum(numlist)
> TypeError: unsupported operand type(s) for +: 'int' and 'str'
 orange_drinkers = int(data_value)

First thing you have to do in programming is to state your problem 
correctly: you do not want to convert your list to an integer 
representation.
This is what you are attempting in your last line above: convert the 
data_value list to a single integer, and obviously, that cannot work.


Instead, what you want to do is to convert every element in your list to 
an integer. You already know how to do this in a for loop:


int_list = []
for element in data_value:
int_list.append(int(element))

However, for simple transformations like this, Python has a very 
powerful construct called list comprehensions (read about them here: 
https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions 
, they're really great), which allow you to replace the for loop with a 
simple:


int_list = [int(element) for element in data_value]

You can even combine the comprehension with sum on one line like this:

print sum([int(element) for element in data_value])

Yet, while all of the above should help you learn Python programming 
patterns, your original code already had the best solution:


data_value = []
..
while True:
line = infile.readline()
if not line: break
..
States, OJ = string.split(line)
XNUM = int(OJ)
..
data_value.append(XNUM)

, i.e. converting each value to an int before adding it to the original 
list.


Best,
Wolfgang

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


Re: [Tutor] Unhandled exception

2014-07-21 Thread Alan Gauld

On 21/07/14 07:57, yarteydegre...@gmail.com wrote:

I just want to know if an unhandled exception is a bug in my programs!


No, its not. Maybe.

Exceptions can happen for all sorts of reasons, for
some you can do something if they happen.
In those cases handling the exception makes sense.

In other cases the exception can't be usefully handled
so there is little point in creating a handler. Just
allow the exception to happen and display the stack
trace.

So if you can reasonably expect an exception to happen
and can do something sensible about it (like trying
to open a non existent file, say) you should handle
it and not doing so would arguably be a bug.

But if you can't do anything sensible with the
exception (an out of memory error for example(*))
you might as well just let it happen.

The final twist is that your client might not like
to see user-hostile error messages. I that case
use a general except clause and log the error
where you can find it but the user gets a
nice friendly message instead.

(*)Of course in critical apps running out of
memory could be seen as a bug. But nonetheless
not catching the exception when it happens is
not the problem. Memory errors usually need to be
prevented not handled after the fact.

--
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] Unhandled exception

2014-07-21 Thread Ben Finney
"yarteydegre...@gmail.com"  writes:

> I just want to know if an unhandled exception is a bug in my programs! 

That's a good question, thanks for asking.

In some programming languages, exceptions are something to avoid and
reduce where possible. But that's not the case for Python.

In Python, exceptions are a fundamental part of the program flow. When a
function call (or some other part of a program) encounters a
circumstance where “this is the result” doesn't make sense, the correct
idiom is to raise an exception with rich information about what the
exceptional situation was.

For example, a procedure for “divide number foo by number bar” should
usually return a numeric result. If one of the values is not a number,
though, no result makes sense; a ValueError exception is raised. If they
*are* both numbers, but the second (the denominator) is zero, there's
still no sensible result to return; instead, it makes more sense to
raise a ZeroDivisionError.

Another example: a procedure for “get me the next item from this
sequence” should usually return the item as a value. If the sequence
*has* no more items, though, no value makes sense to return; a
StopIteration exception is raised.

An example you are likely familiar with: Your Python program can run at
a text console, or maybe you're writing some Python code at the
interactive Python shell. This usually reads a line of text from your
console, and goes on to process the result as a line of text. If you
want to stop the session, though, you can press the console's
“interrupt” key (Ctrl+C, or Ctrl+Z on some systems). No particular line
of text makes sense as a result, so a KeyboardInterrupt exception is
raised.

In all these cases, the exception is raised because no return value
makes sense, and *something* needs to deal with the fact that the
typical path through the code can't continue. Exceptions are normal :-)

So, in light of all that: If your code is written to expect specific
exceptions, you can catch them (by the type of exception) and handle
them at an appropriate point. If not, they end your program at the top
level reporting that the exception was unhandled.

Whether they are an *error* is a matter of what your intention was. If
you weren't intending the program to encounter that exception, then yes!
But exceptions are a normal part of Python control flow, and often they
are exactly what is needed.

-- 
 \ “The Things to do are: the things that need doing, that you see |
  `\ need to be done, and that no one else seems to see need to be |
_o__)   done.” —Richard Buckminster Fuller, 1970-02-16 |
Ben Finney

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


Re: [Tutor] Unhandled exception

2014-07-21 Thread yarteydegre...@gmail.com
Thanks, Alan and Ben! I really appreciate your explanations.

Degreat

- Reply message -
From: "Ben Finney" 
To: 
Subject: [Tutor] Unhandled exception
Date: Mon, Jul 21, 2014 11:16


"yarteydegre...@gmail.com"  writes:

> I just want to know if an unhandled exception is a bug in my programs! 

That's a good question, thanks for asking.

In some programming languages, exceptions are something to avoid and
reduce where possible. But that's not the case for Python.

In Python, exceptions are a fundamental part of the program flow. When a
function call (or some other part of a program) encounters a
circumstance where “this is the result” doesn't make sense, the correct
idiom is to raise an exception with rich information about what the
exceptional situation was.

For example, a procedure for “divide number foo by number bar” should
usually return a numeric result. If one of the values is not a number,
though, no result makes sense; a ValueError exception is raised. If they
*are* both numbers, but the second (the denominator) is zero, there's
still no sensible result to return; instead, it makes more sense to
raise a ZeroDivisionError.

Another example: a procedure for “get me the next item from this
sequence” should usually return the item as a value. If the sequence
*has* no more items, though, no value makes sense to return; a
StopIteration exception is raised.

An example you are likely familiar with: Your Python program can run at
a text console, or maybe you're writing some Python code at the
interactive Python shell. This usually reads a line of text from your
console, and goes on to process the result as a line of text. If you
want to stop the session, though, you can press the console's
“interrupt” key (Ctrl+C, or Ctrl+Z on some systems). No particular line
of text makes sense as a result, so a KeyboardInterrupt exception is
raised.

In all these cases, the exception is raised because no return value
makes sense, and *something* needs to deal with the fact that the
typical path through the code can't continue. Exceptions are normal :-)

So, in light of all that: If your code is written to expect specific
exceptions, you can catch them (by the type of exception) and handle
them at an appropriate point. If not, they end your program at the top
level reporting that the exception was unhandled.

Whether they are an *error* is a matter of what your intention was. If
you weren't intending the program to encounter that exception, then yes!
But exceptions are a normal part of Python control flow, and often they
are exactly what is needed.

-- 
 \ “The Things to do are: the things that need doing, that you see |
  `\ need to be done, and that no one else seems to see need to be |
_o__)   done.” —Richard Buckminster Fuller, 1970-02-16 |
Ben Finney

___
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] Unhandled exception

2014-07-21 Thread Dave Angel
"yarteydegre...@gmail.com"  Wrote in message:
> 
> 

I'm glad they were able to help.  But please let me point out a
 few procedural issues, for nex time. 
You started a whole new thread just to say thanks.  You should
 only start one to ask a new question or start a new discussion.  
 Otherwise use reply-list or whatever your program calls it, maybe
 reply-all and remove the recipients other than the list.
 

You sent this message in html, not in text mode. Always tell your
 mail to use text here.

You top-posted, rather than putting your comments after the
 relevant quotation. 

Thanks for listening. 


-- 
DaveA

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