Reputation: 33
I am trying to create a function and I keep on getting the same error message. And this is something that I have had a problem with for a while. The (key) input is supposed to be an integer. The same integer that's (x). Like input 200 for key/x and the output would be '11001000'. The error message I keep getting is:
"TypeError: 'int' object is not iterable"
I am trying to make it so that all of the numbers are integers. I am trying to make a function that executes the same thing that "{0:b}".format(200)
would deliver. So the code that I have come up with is:
def createBinKeyFromKey(key):
for x in key:
return "{o:b}".format(x)
I have also tried to use while loop to execute it correctly and not get an error message, but that hasn't worked so far.
I would like to call an integer. As in the place where it says (key), the input there would be an integer. And then it would return the binary string of the integer. For example I would input createBinKeyFromKey(200) in python shell and it would return '11001000'
Upvotes: 1
Views: 2492
Reputation: 250931
You can't iterate over an integer, to get a range of numbers use range()
or xrange()
.
range()
creates a whole list first, while xrange()
returns an iterator(memory efficient)
here:
def createBinKeyFromKey(key):
for x in range(key):
yield "{0:b}".format(x) #use yield as return will end the loop after first iteration
Using yield
makes it a generator function.
demo:
>>> list(createBinKeyFromKey(10))
['0', '1', '10', '11', '100', '101', '110', '111', '1000', '1001']
>>> for x in createBinKeyFromKey(5):
... print x
0
1
10
11
100
help on range
:
>>> range?
range(stop) -> list of integers
range(start, stop[, step]) -> list of integers
Return a list containing an arithmetic progression of integers.
range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
When step is given, it specifies the increment (or decrement).
For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!
These are exactly the valid indices for a list of 4 elements.
Upvotes: 3