Re: [Tutor] break and exit

2014-11-21 Thread Peter Otten
James Rieve wrote:

> I accidently used 'exit' in a loop where I meant to use 'break' and, in
> that case, the program seemed to work as expected but in some cases 'exit'
> seems to behave differently from 'break'. For example, in this code
> snippet using 'exit' or 'break' produces the same result:
> 
> for i in range(10):
> if i > 3:
> exit
> else:
> print(i)
> print('out of loop')
> 
> But in this case they behave differently:
> 
> for i in range(10):
> if i > 3:
> break   # try using exit here.
> else:
> print(i)
> else:
> print('for loop else statement')
> 
> print('out of loop')
> 
> Does anyone have any pointers to descriptions of 'exit', what it is, what
> it means, how It's used, etc.?

exit is not part of Python's syntax, it is (almost, see below) a normal 
function. Writing

exit

has no effect, instead of

> for i in range(10):
> if i > 3:
> exit
> else:
> print(i)
> print('out of loop')

you could have written

for i in range(10):
if i > 3:
pass
else:
print(i)
print('out of loop')

but if you invoke exit like a function

> for i in range(10):
> if i > 3:
  exit()
> else:
> print(i)
> print('out of loop')

the script will be terminated -- you can detect that by the fact that

out of loop

is not printed. Personally, I hardly ever use exit (or sys.exit() or `raise 
SystemExit`). If you want a script to stop in the middle of execution I 
recommend that instead of

print("some code")
if some_condition:
   exit()
print("more code")

you write

print("some code")
if not some_condition:
print("more code")

or (even better for all but tiny scripts) use a main function like so:

def main():
print("some code")
if some_condition:
return
print("more code")

if __name__ == "__main__":
main()

Now -- what actually is exit? Let's fire up the interactive interpreter:

$ python3
Python 3.4.0 (default, Apr 11 2014, 13:05:11) 
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> exit
Use exit() or Ctrl-D (i.e. EOF) to exit
>>> help(exit)
Help on Quitter in module _sitebuiltins object:

class Quitter(builtins.object)
 |  Methods defined here:
 |  
 |  __call__(self, code=None)
 |  
 |  __init__(self, name, eof)
 |  
 |  __repr__(self)
 |  
 |  --
 |  Data descriptors defined here:
 |  
 |  __dict__
 |  dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |  list of weak references to the object (if defined)

So exit is an instance of Quitter. The Quitter class has a __call__ method 
which is executed when you invoke an instance like a function. Let's have a 
look a the code:

>>> import inspect
>>> print(inspect.getsource(exit.__call__))
def __call__(self, code=None):
# Shells like IDLE catch the SystemExit, but listen when their
# stdin wrapper is closed.
try:
sys.stdin.close()
except:
pass
raise SystemExit(code)

So exit() tries to close sys.stdin and then raises a SystemExit exception. 
Unless you catch that exception the program ends.



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


Re: [Tutor] Empty GraphicsWindow

2014-11-21 Thread Alan Gauld

On 21/11/14 03:00, niyanax...@gmail.com wrote:

I need help figuring why my GraphicsWindow empty, I cannot figure out
why it is empty.
Here is my code :

# Import graphics from module
from graphics import GraphicsWindow


Since 'graphics' is not a standard part of Python can you tell
us where you are getting it from? Thee are at least 2 graphics
modules out there, probably more.


tileSize = 0

def main() :


 ...


 # Draw graphics window
 win = GraphicsWindow(roomWidth, roomLength)
 canvas = win.canvas()

 # Draw the checkered surface
 for row in range(numRows) :
 # If the row is even
 if row % 2 == 0 :
 # If the column is even set color to black, if odd yellow
 drawRow(canvas, row, gapX, numCols, gapY, "black", "yellow")

 # If the row is odd
 else:
 # If the column is even set color to yellow, if odd black
 drawRow(canvas, row, gapX, numCols, gapY, "yellow", "black")

 win.wait()


What does win.wait() do? Usually there is some kind of refresh() or 
update command to force a canvas to redraw itself. wait() sounds more 
like it just leaves the window in-situ until something closes it?


But without knowing anything about your library its hard to be sure.

You may have more luck finding an expert by contacting a forum for
your specific graphics package.

--
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 phopto-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] break and exit

2014-11-21 Thread Alan Gauld

On 21/11/14 04:10, James Rieve wrote:

I accidently used 'exit' in a loop where I meant to use 'break' and, in that
case, the program seemed to work as expected but in some cases 'exit' seems
to behave differently from 'break'. For example, in this code snippet using
'exit' or 'break' produces the same result:

for i in range(10):
 if i > 3:
 exit
 else:
 print(i)
print('out of loop')



Only superficially.
When you use exit Python doesn't do anything. But it repeats that non 
operation for every number in your range(). When you use break it is 
only executed once and Python leaves the for loop immediately.
So although what is printed is the same the results in terms of the work 
Pyhon does is very different.


You can demonstrate that by adding another print message

for i in range(10):
 if i > 3:
  exit
  print("I didn't expect this!")
 else:
  print(i)
print('out of loop')

Now swap exit and break.



for i in range(10):
 if i > 3:
 break   # try using exit here.
 else:
 print(i)
else:
 print('for loop else statement')

print('out of loop')


Because the for/else is only executed if the loop completes
normally - which it does with exit - so a break will bypass
that for/else clause.


Does anyone have any pointers to descriptions of 'exit', what it is,


Its the name of a function. So using it in isolation like that has the 
same effect as just putting any variable name on its own does:


for n in range(5):
n
else: print('loop completed')

The use of n here is like your use of exit. Its just a name.

But if you called exit using () the effect would be quite different
to break. It would then exit your whole program.


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 phopto-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] Dividing a float derived from a string

2014-11-21 Thread Stephanie Morrow
Alan,

I am getting a syntax error when I print the following:

input = raw_input("Insert a number: ")

try:
print float(input) * 12
except: TypeError, ValueError:
print False

The "try" is coming up as red.  Any idea why?

On Fri, Nov 21, 2014 at 12:23 AM, Alan Gauld 
wrote:

> On 20/11/14 21:20, Stephanie Morrow wrote:
>
>  input = raw_input("Insert a number: ")
>> if input.isdigit():
>>  print int(input) * 12
>> else:
>>  print False
>>
>> /However/, a colleague of mine pointed out that a decimal will return as
>> False.  As such, we have tried numerous methods to allow it to divide by
>> a decimal, all of which have failed.  Do you have any suggestions?
>> Additionally, we are using 2.7, so that might change your answer.
>>
>
> The simplest solution is simply to convert it to a floating point number
> instead of an integer. float() can convert both integer and floating
> point(decimals) strings top a floating point number.
>
> But how do you deal with non numbers?
> In Python we can use a try/except construct to catch anything that fails
> the conversion:
>
> try:
> print float(input)*12
> except:
> print False
>
> But that's considered bad practice, it's better to put the
> valid errors only in the except line like this:
>
> try:
> print float(input)*12
> except TypeError, ValueError:
> print False
>
> So now Python will look out for any ValueErrors and TypeErrors
> during the first print operation and if it finds one will instead
> print False. Any other kind of error will produce the usual Python error
> messages.
>
> You may not have come across try/except yet, but its a powerful technique
> for dealing with these kinds of issues.
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my phopto-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] Dividing a float derived from a string

2014-11-21 Thread Stephanie Morrow
This one worked!  Thank you very much! :D

On Fri, Nov 21, 2014 at 3:14 AM, Adam Jensen  wrote:

> On Thu, 20 Nov 2014 21:20:27 +
> Stephanie Morrow  wrote:
>
> > Hi there,
> >
> > I have been posed with the following challenge:
> >
> > "Create a script that will ask for a number. Check if their input is a
> > legitimate number. If it is, multiply it by 12 and print out the result."
> >
> > I was able to do this with the following code:
> >
> > input = raw_input("Insert a number: ")
> > if input.isdigit():
> > print int(input) * 12
> > else:
> > print False
> >
> > *However*, a colleague of mine pointed out that a decimal will return as
> > False.  As such, we have tried numerous methods to allow it to divide by
> a
> > decimal, all of which have failed.  Do you have any suggestions?
> > Additionally, we are using 2.7, so that might change your answer.
> >
> > Thank you in advance for any help you can provide!
> >
> > -Stephanie
>
> How about using a floating point type cast to convert the string to a
> number within a try/except block? Maybe something like this:
>
> try:
> x = float(input("Enter a number: "))
> print(x * 12)
> except ValueError:
> print("Not a valid number.")
>
> A little enhancement might involve removing any spaces from the string so
> something like '5.6 e -3' will also be valid input. Like this:
>
> x = float(input("Enter a number: ").replace(' ',''))
> ___
> 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] Dividing a float derived from a string

2014-11-21 Thread Alan Gauld


On 21/11/14 13:19, Stephanie Morrow wrote:


try:
print float(input) * 12
except: TypeError, ValueError:
print False

The "try" is coming up as red.  Any idea why?


Sorry, I left the colon in after the else.
I think that's what's confusing it...
It should read:

except TypeError, ValueError:

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 phopto-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] Dividing a float derived from a string

2014-11-21 Thread Peter Otten
Alan Gauld wrote:

> But that's considered bad practice, it's better to put the
> valid errors only in the except line like this:
> 
> try:
>  print float(input)*12
> except TypeError, ValueError:
>  print False

Careful, you need parens around the tuple of errors, otherwise this catches 
only TypeErrors and assigns the TypeError instance to ValueError:

>>> input = None
>>> try: print float(input) * 12
... except TypeError, ValueError: print False
... 
False
>>> ValueError
TypeError('float() argument must be a string or a number',)

This is a nasty gotcha best avoided by using Python 3.

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


[Tutor] urllib confusion

2014-11-21 Thread Clayton Kirkwood
Hi all.

 

Got a general problem with url work. I've struggled through a lot of code
which uses urllib.[parse,request]* and urllib2. First q: I read someplace in
urllib documentation which makes it sound like either urllib or urllib2
modules are being deprecated in 3.5. Don't know if it's only part or whole.

I've read through a lot that says that urllib..urlopen needs urlencode,
and/or encode('utf-8') for byte conversion, but I've seen plenty of examples
where nothing is being encoded either way. I also have a sneeking suspicious
that urllib2 code does all of the encoding. I've read that if things aren't
encoded that I will get TypeError, yet I've seen plenty of examples where
there is no error and no encoding.

 

Why do so many examples seem to not encode? And not get TypeError? And yes,
for those of you who are about to suggest it, I have tried a lot of things
and read for many hours.

 

Thanks,

 

Clayton

 

 

 

You can tell the caliber of a man by his gun--c. kirkwood

 

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


Re: [Tutor] Dividing a float derived from a string

2014-11-21 Thread Adam Jensen
> -Original Message-
> From: Tutor [mailto:tutor-bounces+hanzer=riseup@python.org] On
> Behalf Of Alan Gauld
> Sent: Thursday, November 20, 2014 7:24 PM

> But that's considered bad practice, it's better to put the valid errors
only in
> the except line like this:
> 
> try:
>  print float(input)*12
> except TypeError, ValueError:
>  print False
> 
> So now Python will look out for any ValueErrors and TypeErrors during the
> first print operation and if it finds one will instead print False. Any
other kind
> of error will produce the usual Python error messages.
> 
> You may not have come across try/except yet, but its a powerful technique
> for dealing with these kinds of issues.

I'm browsing the built-in
[exceptions](docs.python.org/3.4/library/exceptions.html) and reading about
the [float cast](docs.python.org/3.4/library/functions.html#float) and it
seemed like it might be a good idea to catch overflows, so:

try:
print(float(input('Enter a number: ').replace(' ','')) * 12)
except ValueError:
print('Not a valid number.')
except OverflowError:
print('Too big!')
except EOFError:
print('\nGoodbye.')

I guess TypeError isn't necessary since input() returns a string and that's
a valid type for float(). EOFError is there to handle ^D gracefully.
Curiously, a float cast on a very large number represented as a string
returns 'inf' rather than raising an overflow error. I didn't expect that. 




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


Re: [Tutor] urllib confusion

2014-11-21 Thread Joel Goldstick
On Fri, Nov 21, 2014 at 4:37 PM, Clayton Kirkwood  wrote:
> Hi all.
>
>
>
> Got a general problem with url work. I’ve struggled through a lot of code
> which uses urllib.[parse,request]* and urllib2. First q: I read someplace in
> urllib documentation which makes it sound like either urllib or urllib2
> modules are being deprecated in 3.5. Don’t know if it’s only part or whole.

The names of the modules changed I believe in v3.x.

But you can save yourself a lot of trouble by using the excelent 3rd
party package called requests:
http://docs.python-requests.org/en/latest/

Also, please use plaintext for your questions.  That way everyone can
read them, and the indentation won't get mangled
>
> I’ve read through a lot that says that urllib..urlopen needs urlencode,
> and/or encode(‘utf-8’) for byte conversion, but I’ve seen plenty of examples
> where nothing is being encoded either way. I also have a sneeking suspicious
> that urllib2 code does all of the encoding. I’ve read that if things aren’t
> encoded that I will get TypeError, yet I’ve seen plenty of examples where
> there is no error and no encoding.
>
>
>
> Why do so many examples seem to not encode? And not get TypeError? And yes,
> for those of you who are about to suggest it, I have tried a lot of things
> and read for many hours.
>
>
>
> Thanks,
>
>
>
> Clayton
>
>
>
>
>
>
>
> You can tell the caliber of a man by his gun--c. kirkwood
>
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



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


Re: [Tutor] urllib confusion

2014-11-21 Thread Alan Gauld

On 21/11/14 21:37, Clayton Kirkwood wrote:


urllib or urllib2 modules are being deprecated in 3.5. Don’t know if
it’s only part or whole.


urlib2 doesn't exist in Python3 there is only the urllib package.

As to urllib being deprecated, thats the first I've heard of
it but it may be the case - I don;t follow the new releases closely 
since I'm usually at least 2 releases behind. I only upgraded to 3.4 
because I was writing the new book and needed it to be as current as 
possible.


But the "What's New" document for the 3.5 alpha says:

"A new urllib.request.HTTPBasicPriorAuthHandler allows HTTP Basic 
Authentication credentials to be sent unconditionally with the first 
HTTP request, rather than waiting for a HTTP 401 Unauthorized response 
from the server. (Contributed by Matej Cepl in issue 19494.)"


And the NEWS file adds:

"urllib.request.urlopen will accept a context object
 (SSLContext) as an argument which will then used be
for HTTPS connection.  Patch by Alex Gaynor."

Which suggests urllib is alive and kicking...


I’ve read through a lot that says that urllib..urlopen needs urlencode,
and/or encode(‘utf-8’) for byte conversion, but I’ve seen plenty of
examples where nothing is being encoded either way.


Might those be v2 examples?
encoding got a whole lot more specific in Python v3.

But I'm not sure what you mean by the double dot.
urllib.urlopen is discontinued in Python3. You
should be using urllib.request.urlopen instead.
(But maybe thats what you meant by the ..?)


Why do so many examples seem to not encode? And not get TypeError?


Without specific examples it's hard to know.


--
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 phopto-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] urllib confusion

2014-11-21 Thread Clayton Kirkwood


>-Original Message-
>From: Joel Goldstick [mailto:joel.goldst...@gmail.com]
>Sent: Friday, November 21, 2014 2:39 PM
>To: Clayton Kirkwood
>Cc: tutor@python.org
>Subject: Re: [Tutor] urllib confusion
>
>On Fri, Nov 21, 2014 at 4:37 PM, Clayton Kirkwood 
>wrote:
>> Hi all.
>>
>>
>>
>> Got a general problem with url work. I’ve struggled through a lot of
>> code which uses urllib.[parse,request]* and urllib2. First q: I read
>> someplace in urllib documentation which makes it sound like either
>> urllib or urllib2 modules are being deprecated in 3.5. Don’t know if
>it’s only part or whole.
>
>The names of the modules changed I believe in v3.x.

I don't think so because I've seen both lib and lib2 in both new and old code, 
and current 4.3 documentation talks only of urllib.

>
>But you can save yourself a lot of trouble by using the excelent 3rd
>party package called requests:
>http://docs.python-requests.org/en/latest/

I've seen nothing of this.

>
>Also, please use plaintext for your questions.  That way everyone can
>read them, and the indentation won't get mangled
>>
>> I’ve read through a lot that says that urllib..urlopen needs
>> urlencode, and/or encode(‘utf-8’) for byte conversion, but I’ve seen
>> plenty of examples where nothing is being encoded either way. I also
>> have a sneeking suspicious that urllib2 code does all of the encoding.
>> I’ve read that if things aren’t encoded that I will get TypeError, yet
>> I’ve seen plenty of examples where there is no error and no encoding.
>>
>>
>>
>> Why do so many examples seem to not encode? And not get TypeError? And
>> yes, for those of you who are about to suggest it, I have tried a lot
>> of things and read for many hours.
>>
>>
>>
>> Thanks,
>>
>>
>>
>> Clayton
>>
>>
>>
>>
>>
>>
>>
>> You can tell the caliber of a man by his gun--c. kirkwood
>>
>>
>>
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>>
>
>
>
>--
>Joel Goldstick
>http://joelgoldstick.com



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