[Tutor] Can't figure out syntax error
Kent Johnson
kent37 at tds.net
Fri Jun 10 04:29:55 CEST 2005
as.20.schellenberg at spamgourmet.com wrote:
> Hi there,
>
> I'm in the process of learning Python, and need some help deciphering
> the reason why the following code doesn't work:
Ziyad has answered your immediate question but I have a few more comments.
>
> import sys, string
>
> def dec2bin(decNum):
> # validate the input as a postive integer number
> for char in decNum:
> if str(char).isdigit() == False:
char is already a string so you don't have to call str(char), just use char directly:
if char.isdigit() == False:
but you don't have to compare to False, either, just say
if not char.isdigit():
in fact you can call isdigit() on the whole string, it will test if all the characters are digits. So instead of the loop just write
if not decNum.isdigit():
> print "Not a postive integer number given when calling the dec2bin
> function."
> sys.exit()
>
> bin = "" # initialize the new binary result (as a string)
> num = int(decNum)
OK, num is an integer now.
>
> if num == 0: # take care of the zero case
> bin = "0"
>
> while int(num) != 0: # the rest of the cases
> nextBin = int(num) % 2 # check if this column should be a 0 or 1
> bin = str(nextBin) + bin # add the result to the front of the result
> string
> int(num) = int(num) / 2 # this is integer division, so we truncate
> the decimal part
You don't have to keep saying int(num), num is already an int and dividing by 2 gives a new int. You can just use num directly.
>
> return bin # return the binary result
>
> # testing
> x = "13"
> print dec2bin(x)
Kent
More information about the Tutor
mailing list