简体   繁体   中英

Invalid Syntax error python 3.5.2

I'm getting syntax error in this particular line.

print "Sense %i:" %(i),

Full code:

for i in range(len(meas)):
    p = sense(p, meas[i])
    r = [format(j,'.3f') for j in p]
    print "Sense %i:" % (i),
    print r,
    entropy(p)
    p = move(p, mov[i])
    r = [format(j,'.3f') for j in p]
    print "Move %i:" % (i),
    print r,
    entropy(p)
    print

Several things:

  • In Python 3, print is a function, no more a statement like it was with Python 2. So, you need to add parenthesis to call the function,
  • the % operator used for string formatting is deprecated. With Python 3, you should use the format method (or the format function),
  • the % operator usually take a tuple as a second parameter: the expression "(i)" is not a tuple but a constant. With Python, the singleton tuple has a trailing comma like this: "(i,)".
  • use the keyword argument end="" to replace the newline by an empty string (but I'm not sure this is what you want)

So, you can replace your code by:

print("Sense {}:".format(i), end="")

EDIT: add code from comment

Your code should be converted in Python 3 like bellow:

for i in range(len(meas)):
    p = sense(p, meas[i])
    r = [format(j,'.3f') for j in p]
    print("Sense {0}:".format(i), end="")
    print(r, end="")
    entropy(p)
    p = move(p, mov[i])
    r = [format(j,'.3f') for j in p]
    print("Move {0}:".format(i), end="")
    print(r, end="")
    entropy(p)
    print()

Try this:

print ("Sense %s:" %i)

Will work just fine

在python 3中,print是一个函数,您必须使用方括号: print("Sense %i:" %(i))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM