Joe Barry
Joe Barry

Reputation: 37

Python error - can't assign to literal

FileName = 'Binarydata.dat'
BinaryFile = open(FileName, 'r')
for '0' in BinaryFile:
    print('')
else:
    print('@')
BinaryFile.close() 

I am receiveing the error SyntaxError - can't assign to literal when trying to run this code. This is just a small part of the code. The rest is working correctly. I can't figure out why this is not working.

Upvotes: 0

Views: 9463

Answers (3)

Richante
Richante

Reputation: 4388

for '0' in BinaryFile:

Where you have '0' should be a variable, not a literal.

Probably what you mean to do is:

for line in BinaryFile:
  if line == '0':
    print('')
  else:
    print('@')

Upvotes: 14

Makoto
Makoto

Reputation: 106389

If you're looking for '0', then you can write:

for ch in BinaryFile:
    print('' if ch == '0' else '@')

Remember: The for in Python is a for-each loop. There has to be a variable bound over the contents of the iterable.

Upvotes: 1

James R
James R

Reputation: 4656

Probably in the entire stacktrace you saw something like:

    for '0' in BinaryFile:
SyntaxError: can't assign to literal

When python loops over BinaryFile, it assigns each iteration to a variable. In this case, you trying to assign the first iteration to '0', which is a string.

It should look like this instead:

    for a_variable in BinaryFile:

In this case, the element of BinaryFile will be assigned to a_variable. On the next iteration, the next variable will be assigned to a_variable.

This will continue until the object BinaryFile raises StopIteration error, at which point the iteration ends.

Upvotes: 3

Related Questions