Please Explain This Output
Solution 1:
This is one of the few non-backwards compatible changes between Python3 and Python2.
In Python2, print
was a statement. In Python3 it was converted to a function call. Statements in Python are things like this:
x = 3importthisfrom math import pi
Function calls look like this:
some_list.sort()
counter.most_common()
The parenthesis ()
are what means "call this thing".
If you're learning Python you should learn with Python3, but if you can't install that or you don't want to for whatever reason, you can get this behavior in Python2 with the __future__
import:
Python 2.7.10 (default, Oct 232015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type"help", "copyright", "credits"or"license"for more information.
>>> from __future__ import print_function
>>> print('the future', 'looks better')
the future looks better
If it's in a Python script it must be the first non-comment line in the file, but in the repl (interactive interpreter, the thing with the >>>
prompt), you can do the import at any time.
Solution 2:
In python 2.7 we have
print('hello', 'world')
print ('hello', 'world')
print ('hello , world')
output:
('hello', 'world')
('hello', 'world')
hello , world
Print is a statement. Which passes the parameter just like that. So if we have one object inside the parenthesis it works fine. But if there are multiple objects inside the parenthesis they get passed as a tuple object. And A tuple will get printed like a tuple.
Basically
print('a', 'b')
is same as
a = ('a', 'b')
print(a)
# orprint a
# output : ('a', 'b')
And that's what you would expect.
On the other hand in python 3 Print is a function. So you have to call it. Basically now 'hello', 'world' is not a tuple. Rather multiple arguments being passed separately to print function.
print('hello', 'world')
output:
hello world
To achieve the same effect in 3.5 we will have to do this
print(('hello', 'world'))
output:
('hello', 'world')
You can read up more here: http://sebastianraschka.com/Articles/2014_python_2_3_key_diff.html
Solution 3:
Because you are trying to use print in python 2.7, pythont hinks that you are asking it to print a tuple. To output just hello world in python 2.7, you can do something like:
print"Hello", "World"# without the parentheses!
Or
print"%s %s" % ("Hello", "World")
Or even
from __future__ import print_functionprint("Hello", "World")
If you were or will be using python 3 instead of python 2, you already have the print function available without the special import. If you want to read more about tuples, I would recommend that you look at tuples in this link
Post a Comment for "Please Explain This Output"