On 04/20/2015 08:44 PM, Jim Mooney wrote:
Why does the compiler choke on this? It seems to me that the enhanced
subtraction resolves to a legitimate integer in the exponent, but I get a
syntax error:
B = '11011101'
sum = 0
start = len(B)
for char in B:
sum += int(char) * 2**(start -= 1) ## syntax error
print(sum)
As others have said, the augmented assignment, like the regular
assignment, is not permissible inside an expression. It is a type of
statement.
You could solve this easily enough by:
B = '11011101'
sum = 0
start = len(B)
for index, char in enumerate(B):
sum += int(char) * 2**(start - index)
print(sum)
But I'd think that:
B = '11011101'
sum = 0
for char in B:
sum = sum * 2 + int(char)
print(sum)
reads much better, as well as being much faster.
--
DaveA
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor