Reputation: 9
I have this bit of code that I am stuck with and I am not sure why it won't execute the else statement. If x is "100" I would like to to convert decimal value to 6 bits otherwise for x = "115", "130", "145" I would like convert decimal value to 8 bits.
string_list = ["100", "115", "130", "145"]
if (x == "100" for x in string_list):
dec_to_bin = "{0:06b}".format()
else:
dec_to_bin = "{0:08b}".format()
However, it doesn't carry on the else statements and print everything in 6 bits.
I want the answer to be something like this
100 6bits
115 8bits
130 8bits
145 8bits
Upvotes: 1
Views: 2884
Reputation: 27008
To get that output from those input data then:
string_list = ["100", "115", "130", "145"]
for e in string_list:
n = 6 if e == '100' else 8
print(f'{e} {n}bits')
Output:
100 6bits
115 8bits
130 8bits
145 8bits
Alternatively:
string_list = ["100", "115", "130", "145"]
for e in string_list:
n = 6 if e == '100' else 8
print(f'{e} {int(e):0{n}b}')
Output:
100 1100100
115 01110011
130 10000010
145 10010001
Note:
Not sure of the relationship between "100" and 6 because the binary representation of 100 (base 10) requires 7 bits
Upvotes: 0
Reputation: 458
The else
statement is never executed. Your fist statement is an if
statement.
You want to assess is a specific item is equal to '100'
, and do something if it is. However the line if (x == "100" for x in string_list)
actually generates an item called generator
which is not None
. Hence the fact that the if statement is always executed : your generator is always truthy.
You should try and parse the list, and only then for each item use an if/else
statement :
for item in string_list :
if item == '100':
# action
else :
# other action
Upvotes: 0
Reputation: 51
As @Sayse mentioned in comment, the usage of for
loop is incorrect:
Try this:
string_list = ["100", "115", "130", "145"]
res = []
for x in string_list:
if x == "100":
dec_to_bin = "{0:06b}".format(int(x))
else:
dec_to_bin = "{0:08b}".format(int(x))
res.append(dec_to_bin)
print(res) #Will print ['1100100', '01110011', '10000010', '10010001']
Upvotes: 1
Reputation: 7967
When you write your if
statement by passing (x == "100" for x in string_list)
in the condition you are creating a generator which is not None
, hence trigerring the if
statement.
It is not iterating over each element as you are hoping it would. For it to iterate over each element, write the if statement inside the for loop.
Upvotes: 0
Reputation: 76
You're putting the condition which returns a True/False response after the if in parantheses, so it doesn't iterate through every element. You are basicly writing "if there is an x=="100" in string_list, do this". For it to work for every element, just write it:
for x in string_list:
if x == "100":
dec_to_bin = ...
else:
dec_to_bin = ...
Upvotes: 0