Michael B Hildebrand
Michael B Hildebrand

Reputation: 46

In Python, what does this end=" " do in a print statement?

I'm trying to get someone's code to run in Python. This is the code...

def printGen(cols, rows, array, genNo):
os.system("cls")

print("Game of Life -- Generation " + str(genNo + 1))

for i in range(rows):
    for j in range(cols):
        if array[i][j] == -1:
            print("#", end=" ")
        elif array[i][j] == 1:
            print(".", end=" ")
        else:
            print(" ", end=" ")
    print("\n")

Python is telling me there is a syntax error at the '=' sign with this statement:

print("#", end=" ")

Can anyone tell me why I'm getting a syntax error, and more importantly, what the statement does?

Upvotes: 0

Views: 5610

Answers (1)

John1024
John1024

Reputation: 113934

You are using the wrong version of python.

Running your code under Python 2 yields:

>>> print("#", end=" ")
  File "<stdin>", line 1
    print("#", end=" ")
                  ^
SyntaxError: invalid syntax

Running your code under Python 3 yields:

>>> print("#", end=" ")
# >>> 

For that code to work natively, you need to be using python 3.

Alternatively, to make it work under python 2:

>>> from __future__ import print_function
>>> print("#", end=" ")
# >>> 

Upvotes: 2

Related Questions