First and foremost i am very new into Python. I am using a notebook version of Ipython called jupyter and its provided by my University, so I don't know whether this is a standard version or not.
I was busy in a slide course about Python and encountered this exercice:
This is the code I used and the syntax error I get
in the Ipython environment
I don't get why it is not working.
Thank you in advance
Olivier
print([object, ...][, sep=' '][, end='\n'][, file=sys.stdout]) is a function in Python 3.x, which has a sep keyword argument (among others).
If you are using Python 2.7 (try print "Hello!" - if it runs, you have Python 2.x), print is a statement there, which means that if you want to get the behaviour as in your slide (make print a function), you need to import print_function from __future__ module.
That way you can use print("Hi!", "Hello!", sep='\t') as in your slide.
As mentioned by #Kevin in his comment below this post, if your course uses Python 3.x, you would be better off to upgrade to this version since things like async, yield from or lzma are not available in Python 2.x.
Related
I was wondering if anyone has suggestions for writing a backwards-compatible input() call for retrieving a filepath?
In Python 2.x, raw_input worked fine for input like /path/to/file. Using input works fine in this case for 3.x, but complains in 2.x because of the eval behavior.
One solution is to check the version of Python and, based on the version, map either input or raw_input to a new function:
if sys.version_info[0] >= 3:
get_input = input
else:
get_input = raw_input
I'm sure there is a better way to do this though. Anyone have any suggestions?
Since the Python 2.x version of input() is essentially useless, you can simply overwrite it by raw_input:
try:
input = raw_input
except NameError:
pass
In general, I would not try to aim at code that works with both, Python 2.x and 3.x, but rather write your code in a way that it works on 2.x and you get a working 3.x version by using the 2to3 script.
This code is taught in many Python education and training programs now.
Usually taught together:
from __future__ import print_function
if hasattr(__builtins__, 'raw_input'):
input = raw_input
First line: imports the Python 3.x print() function into Python 2.7 so print() behaves the same under both versions of Python. If this breaks your code due to older print "some content" calls, you can leave this line off.
Second and third lines: sets Python 2.7 raw_input() to input() so input() can be used under both versions of Python without problems. This can be used all by itself if this is the only compatibility fix you wish to include in your code.
There are more from __future__ imports available on the Python.org site for other language compatibility issues. There is also a library called "six" that can be looked up for compatibility solutions when dealing with other issues.
The way you are handling it is just fine. There are probably more similar ways using the sys module, but just in keep in mind that if you are program is doing something more than trivial with strings and files, it is better to have two versions of your program instead of having a backwards compatible python3 program.
You could import the function:
from builtins import input
Unfortunately though this method requires an external dependency via pip install future
I am making code that works on both Python 2 and Python 3.
But there was no problem in theory, but there was a Python problem.
Now I'm build and use both Python 2.7.5 and Python 3.7.4.
This is part of my code
ex)
if sys.version_info < (3,):
print(keys),;
print(values)
else:
print(keys,'/ ', end='')
print(values)
This code that checks Python version with sys.version, corresponding 'if' will be working.
But, of course there is a syntax error.
Python 2 does not support [end=''].
In my opinion...
Even if you actually ignore it and act on it, there's no problem code.
I tried 'Try-except', but syntax errors were not ignored.
How can both Python2 and Python3 not change lines while weaving compatible codes?
Import the package print_function and try
from __future__ import print_function
In this particular case, just get the Python 3 print function in both Python 2 and Python 3 by adding:
from __future__ import print_function
to the very top of your file, then only use the Python 3 syntax.
As for avoiding the SyntaxError from actually incompatible constructs that can't be fixed with a __future__ import, the only solutions are putting the incompatible code in separate modules (a public module can do version testing to import the implementations from the private module appropriate to the Python version), or evaling a string containing the code for the appropriate version (exec won't typically work, because it also changed from keyword statement to built-in function in the transition; eval+compile is the same in both though).
There is no way to just "turn off syntax checking", because invalid syntax definitionally means the parser has encountered an unrecoverable error; you don't want it to try to stumble onwards, guessing at what everything else means in the context of the garbage state it was left in.
The print function's syntax has been changed in newer versions of python. The problem is that at home, I have the newer version of python while at office the old one. How can I have the same program run on both the newer and old python versions?
If you're using iPython/ Jupyter, run
%autocall 1
After that, you can use
print "yo"
like in Python 2.
Many 2 vs 3 porting issues are covered well here.
In general, I think it's more hassle than it's worth to try to keep a single .py file that runs under both versions. But if you want to try, that link shows usable workarounds.
While it's true that Python 2 supports, for example,
print("abc", 3)
the results aren't the same: in Python 2 that prints the tuple ('abc', 3). And Python 2's print doesn't support Python 3's optional keyword arguments at all (like file=).
You can use new print syntax on older version of python.
You can use the new print function in old scripts like this:
# This line goes at the top of the file ...
from __future__ import print_function
# And then you can use the new-style print function anywhere
print("hello")
I was wondering if anyone has suggestions for writing a backwards-compatible input() call for retrieving a filepath?
In Python 2.x, raw_input worked fine for input like /path/to/file. Using input works fine in this case for 3.x, but complains in 2.x because of the eval behavior.
One solution is to check the version of Python and, based on the version, map either input or raw_input to a new function:
if sys.version_info[0] >= 3:
get_input = input
else:
get_input = raw_input
I'm sure there is a better way to do this though. Anyone have any suggestions?
Since the Python 2.x version of input() is essentially useless, you can simply overwrite it by raw_input:
try:
input = raw_input
except NameError:
pass
In general, I would not try to aim at code that works with both, Python 2.x and 3.x, but rather write your code in a way that it works on 2.x and you get a working 3.x version by using the 2to3 script.
This code is taught in many Python education and training programs now.
Usually taught together:
from __future__ import print_function
if hasattr(__builtins__, 'raw_input'):
input = raw_input
First line: imports the Python 3.x print() function into Python 2.7 so print() behaves the same under both versions of Python. If this breaks your code due to older print "some content" calls, you can leave this line off.
Second and third lines: sets Python 2.7 raw_input() to input() so input() can be used under both versions of Python without problems. This can be used all by itself if this is the only compatibility fix you wish to include in your code.
There are more from __future__ imports available on the Python.org site for other language compatibility issues. There is also a library called "six" that can be looked up for compatibility solutions when dealing with other issues.
The way you are handling it is just fine. There are probably more similar ways using the sys module, but just in keep in mind that if you are program is doing something more than trivial with strings and files, it is better to have two versions of your program instead of having a backwards compatible python3 program.
You could import the function:
from builtins import input
Unfortunately though this method requires an external dependency via pip install future
I'm using the new print from Python 3.x and I observed that the following code does not compile due to the end=' '.
from __future__ import print_function
import sys
if sys.hexversion < 0x02060000:
raise Exception("py too old")
...
print("x",end=" ") # fails to compile with py24
How can I continue using the new syntax but make the script fails nicely? Is it mandatory to call another script and use only safe syntax in this one?
The easy method for Python 2.6 is just to add a line like:
b'You need Python 2.6 or later.'
at the start of the file. This exploits the fact that byte literals were introduced in 2.6 and so any earlier versions will raise a SyntaxError with whatever message you write given as the stack trace.
There are some suggestions in this question here, but it looks like it is not easily possible. You'll have to create a wrapper script.
One way is to write your module using python 2.x print statement, then when you want to port it into python 3, you use 2to3 script. I think there are scripts for 3to2 conversion as well, although they seems to be less mature than 2to3.
Either way, in biggers scripts, you should always separate domain logic and input/output; that way, all the print statements/functions are bunched up together in a single file. For logging, you should use the logging module.