Issue
I was messing around with both Python 3.8 and 2.7 and found out that the print function in Python 3 doesn't allow leading zeros in print. See below:
>>> print(01)
File "<stdin>", line 1
print(01)
^
SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers
I suppose this happens because Python 3.x differentiate data types even when printing, this is why the following works:
>>> print('01')
01
I explicitly asked to print a string. Though in Python 2.7 there is no error with the following statement:
>>> print '01'
01
It just returns what I asked. Does it mean that Python 2.x always converts print values into strings?
Solution
In original python 2, print
is a statement, and does not return
a value at all.
>>> x=print 'hi'
File "<stdin>", line 1
x=print 'hi'
^
SyntaxError: invalid syntax
If you use the future-compatible print function in python 2.7, say, it behaves exactly like Python 3.
In Python 3, print
, a function, always returns None
. It prints to a file (often the standard output), but the value returned from the function is None
.
>>> x=print(1)
1
>>> x
>>> type(x)
<type 'NoneType'>
As for 1
vs 01
, in Python 2, a number with a leading zero is octal:
>>> 010
8
This syntax is illegal in Python 3, so you get SyntaxError: invalid token
. This happens before the print
statement ever sees what's going on, so it has nothing to do with print
.
If you want to write a number in octal in Python3, the correct syntax is 0o...
as in:
>>> 0o10
8
Answered By - kojiro
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.