help with a function

Ben Finney bignose+hates-spam at benfinney.id.au
Wed May 17 04:28:56 CEST 2006


Lance Hoffmeyer <lance at augustmail.com> writes:

> def even_odd_round(num):
>  	if(round(num,2) + .5 == int(round(num,2)) + 1):
>  	     if(int(num,0) % 2):		#an odd number	
>  	     	rounded_num = round(num,2) + .1
>   	     else:                              #an even number
>  	       	rounded_num = round(num,2) - .1
>     	rounded_num = int(rounded_num)
>     	return rounded_num
> 
> even_odd_round(5.5)
> 
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
>   File "<interactive input>", line 3, in even_odd_round
> TypeError: int() can't convert non-string with explicit base
> >>>

Two problems.

One is the simple fact reported by the error message: you're
attempting to specify that a number object (already represented inside
Python as a number) should be converted using a particular base. (Why
you've chosen 0 as the base is beyond me.)

That only makes sense with a string of digit characters, where Python
needs to be told what numeric base each digit is (decimal, octal,
hexadecimal, whatever). It makes no sense for objects that are already
numbers, since they're not represented as digits in a base.

The other problem is specifying a base at all. Why not just convert
the object to an int using the default base?

If you're confused about how built-in types or functions work, you
should become familiar with the help system in the interpreter:

    help(int)

-- 
 \          "Any sufficiently advanced bug is indistinguishable from a |
  `\                                       feature."  -- Rich Kulawiec |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list