Issue
I am new to the Python language. I saw a StackOverflow question on how to run a version specific code in a python script. I have written the following code :
import sys
mylist = []
mylist.append(1)
mylist.append(2)
mylist.append(3)
str=""
if sys.version_info[0] == 2:
print("version 2\n")
for x in mylist:
str += "{}".format(x)
print(str)
else:
print("version 3 or above\n")
for x in mylist:
print(x, end='')
print()
But this code gives me an error as follows -
File "test.py", line 18 print(x, end='') SyntaxError: invalid syntax
If I run this code in Python2 it gives an error in the else part. Why is it entering the else block?
Solution
The SyntaxError
is happening before your code runs, python will check all lines of the codes and looking for syntax issues based on the version of python interpreter which is not ok in python2.x, that is why you get that error(Not entering the block, because your code does not start yet) solution is using __future__
and import print_function
.
Answered By - Mehrdad Pedramfar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.