1

When i try to use this function:

def dec_to_bin():
    decimal = raw_input('Input a number: ')
    a =  bin(decimal)
    print(a)

It gives an error:::::

a =  bin(decimal) TypeError: 'str' object can not be interpreted as an index

how can i fix this?

4

1 回答 1

9

The return value from raw_input is a str, not an int. You must first convert it to an int before passing it to bin.

a = bin(int(decimal))

This will fail with a ValueError if the string entered cannot be converted to an integer.

于 2013-03-30T08:24:21.800 回答