[Tutor] exceptions problem

Roelof Wobben rwobben at hotmail.com
Sat Sep 11 22:14:35 CEST 2010




----------------------------------------
> From: rwobben at hotmail.com
> To: bgailer at gmail.com
> Subject: RE: [Tutor] exceptions problem
> Date: Sat, 11 Sep 2010 18:51:12 +0000
>
>
>
>
> ----------------------------------------
>> Date: Sat, 11 Sep 2010 14:43:28 -0400
>> From: bgailer at gmail.com
>> To: tutor at python.org
>> Subject: Re: [Tutor] exceptions problem
>>
>> On 9/11/2010 12:12 PM, Roelof Wobben wrote:
>>>
>>>
>>> ----------------------------------------
>>>> Date: Sat, 11 Sep 2010 11:05:54 -0400
>>>> From: bgailer at gmail.com
>>>> To: tutor at python.org
>>>> Subject: Re: [Tutor] exceptions problem
>>>>
>>>> On 9/11/2010 6:56 AM, Peter Otten wrote:
>>>>> Steven D'Aprano wrote:
>>>>>
>>>>>> On Sat, 11 Sep 2010 09:56:41 am bob gailer wrote:
>>>>>>>> I never thought that you can use a float and a integer to look if
>>>>>>>> the number is a integer.
>>>>>>> You can't.
>>>> I made that comment in the context of the OPs function:
>>>>
>>>> def readposint():
>>>> x = raw_input("Please enter a positive integer :")
>>>> try:
>>>> if (int(x)<0 or (float(x) - int(x)> 0)): raise(ValueError)
>>>> except:
>>>> print x , "is not a positive integer. Try again."
>>>> return -1
>>>> return x
>>>>
>>>> The OP thought (incorrectly) that, given for example:
>>>> x = '3.1'
>>>> float(x) - int(x) would evaluate to 0.1
>>>>
>>>> In reality int(x) in this case raises an exception.
>>>> ValueError: invalid literal for int() with base 10: '3.1'
>>>>
>>>> Since the expression was in a try he could not tell exactly what was
>>>> happening.
>>>>
>>>> I also don't quite understand the use of raise in the try.
>>>>
>>>> I wish and hope that Roelof will learn how to do program walkthroughs
>>>> and use the interactive prompt to solve things himself. I applaud the
>>>> patience some of you have ih hand-holding him. I don't have that
>>>> patience. I wish him to learn to fish.
>>> Hello Bob,
>>>
>>> Oke, I try to fish.
>>
>> Thank you.
>>
>>>
>>> When I do
>>>
>>> x= "a"
>>> y= int(x)
>>> Then I get ValueError.
>>>
>>> When I do
>>>
>>> x= 1.2
>>> y=int(x)
>>> No exception is raised.
>>
>> As Dave pointed out you switched from string to numeric. Try instead x =
>> '1.2'

Then I get a ValueError when I do y=int('1.2')
So it will Raise the error.

Roelof 		 	   		  


More information about the Tutor mailing list