[Tutor] Exeption errors

Lloyd Kvam pythonTutor at venix.com
Sat Aug 21 20:29:34 CEST 2004


One quibble.  It is best to limit the try block to exactly what we mean
to be testing.  I'd recommend changing the code to look like this.

while True:
    x=raw_input("Enter a number: ")
    try:
         x=int(x)
    # put the except immediately after what we mean to try
    except ValueError:
         print "that is not a number"
    # put the rest of the "normal processing" in a try/else block
    else:
         if x==1:
             break

         print "Thats not 1"

On Sat, 2004-08-21 at 14:00, Kent Johnson wrote:
> Kevin,
> 
> You have to get the try block into the loop, so the loop will continue 
> after an exception is raised. This is a little tricky because the loop 
> condition (int(x) != 1) itself is raising the exception.
> 
> One solution is to use an infinite loop with a break condition, like this:
> while True:
>      x=raw_input("Enter a number: ")
>      try:
>          x=int(x)
>          if x==1:
>              break
> 
>          print "Thats not 1"
>      except ValueError:
>          print "that is not a number"
> 
> I prefer this form of the loop anyway because it doesn't duplicate the 
> input code. In general instead of this:
> x = doSomething()
> while not someCondition(x):
>    x = doSomething()
> 
> I prefer this:
> while True:
>    x = doSomething()
>    if someCondition(x):
>      break
> 
> Kent
> 
> At 01:23 PM 8/21/2004 -0400, Kevin wrote:
> >I am playing around with Exeption Errors this is the code I did:
> >x=raw_input("Enter a number: ")
> >try:
> >     while int(x) != 1:
> >         print "Thats not 1"
> >         x=raw_input("Enter a number: ")
> >except ValueError:
> >         print "that is not a number"
> >
> >it works to a point when I type in a number that is not a one it will keep 
> >saying Thats not 1, but when I put in a letter it will say that is not a 
> >number and then exit the program. How do I make it look again?
> >
> >Thanks
> >Kevin
> >
> >
> >---
> >Outgoing mail is certified Virus Free.
> >Checked by AVG anti-virus system 
> >(<http://www.grisoft.com>http://www.grisoft.com).
> >Version: 6.0.740 / Virus Database: 494 - Release Date: 8/16/04
> >_______________________________________________
> >Tutor maillist  -  Tutor at python.org
> >http://mail.python.org/mailman/listinfo/tutor
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 

Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582
-- 

Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582



More information about the Tutor mailing list