In Python 2.7 both the following will do the same
print("Hello, World!") # Prints "Hello, World!"
print "Hello, World!" # Prints "Hello, World!"
However the following will not
print("Hello,", "World!") # Prints the tuple: ("Hello,", "World!")
print "Hello,", "World!" # Prints the words "Hello, World!"
In Python 3.x parenthesis on print is mandatory, essentially making it a function, but in 2.7 both will work with differing results. What else should I know about print in Python 2.7?
In Python 2.x print is actually a special statement and not a function*.
This is also why it can't be used like: lambda x: print x
Note that (expr) does not create a Tuple (it results in expr), but , does. This likely results in the confusion between print (x) and print (x, y) in Python 2.7
(1) # 1 -- no tuple Mister!
(1,) # (1,)
(1,2) # (1, 2)
1,2 # 1 2 -- no tuple and no parenthesis :) [See below for print caveat.]
However, since print is a special syntax statement/grammar construct in Python 2.x then, without the parenthesis, it treats the ,'s in a special manner - and does not create a Tuple. This special treatment of the print statement enables it to act differently if there is a trailing , or not.
Happy coding.
*This print behavior in Python 2 can be changed to that of Python 3:
from __future__ import print_function
It's all very simple and has nothing to do with forward or backward compatibility.
The general form for the print statement in all Python versions before version 3 is:
print expr1, expr2, ... exprn
(Each expression in turn is evaluated, converted to a string and displayed with a space between them.)
But remember that putting parentheses around an expression is still the same expression.
So you can also write this as:
print (expr1), (expr2), ... (expr3)
This has nothing to do with calling a function.
Here we have interesting side effect when it comes to UTF-8.
>> greek = dict( dog="σκύλος", cat="γάτα" )
>> print greek['dog'], greek['cat']
σκύλος γάτα
>> print (greek['dog'], greek['cat'])
('\xcf\x83\xce\xba\xcf\x8d\xce\xbb\xce\xbf\xcf\x82', '\xce\xb3\xce\xac\xcf\x84\xce\xb1')
The last print is tuple with hexadecimal byte values.
Basically in Python before Python 3, print was a special statement that printed all the strings if got as arguments. So print "foo","bar" simply meant "print 'foo' followed by 'bar'". The problem with that was it was tempting to act as if print were a function, and the Python grammar is ambiguous on that, since (a,b) is a tuple containing a and b but foo(a,b) is a call to a function of two arguments.
So they made the incompatible change for 3 to make programs less ambiguous and more regular.
(Actually, I think 2.7 behaves as 2.6 did on this, but I'm not certain.)
Related
In Python you can see the value of a variable without printing it, like:
>>> a = 'hello world'
>>> a
hello world
This is different from printing print(a), yet I'm still able to see a similar output. What it the technical term for this type of variable printing?
As an example of the difference, below shows how a Jupyter Notebook prints a dataframe for both types of printing:
You're executing code in a REPL; the P stands for "print".
It's being implicitly printed by the console.
It's not Python but the Python shell's (IDLE) behavior you're seeing. The way it's built, it prints the type or value of the item you specify. The actual Python would be to have this code inside a .py file:
a = 'hello world'
a
and you do python test.py then you'd see nothing, because the value returned by a would be silently discarded. The cli works as if there's an implicit print() statement there.
What you are seeing if the repr of the last expression returned by the interpreter to the global namespace in interactive mode. This is fundamentally different from the a print output, although they do go to the same stream.
For simple objects such as integer they look the same.
>>> x = 1
>>> print(x)
1
>>> x
1
The difference is that print send the string representation of the object to the STDOUT. Inputting a variable and hitting enter shows you the repr of the object. To me the big difference is that the later can be easily captured by adding an assignment to the expression, i.e. y = x. While the print output is more complicated to capture.
That is why I use the phrase "returns the value for x" or "returns x". This indicates that if you wanted to capture the return as another variable, you could.
Here is a short example to show the difference between print and repr.
>>> class Foo:
... def __repr__(self):
... return f'<Foo at 0x{id(self):x}>'
... def __str__(self):
... return 'Foo-object'
...
>>> f = Foo()
>>> print(f)
Foo-object
>>> f
<Foo at 0x17416af3c18>
In Python 2.7 both the following will do the same
print("Hello, World!") # Prints "Hello, World!"
print "Hello, World!" # Prints "Hello, World!"
However the following will not
print("Hello,", "World!") # Prints the tuple: ("Hello,", "World!")
print "Hello,", "World!" # Prints the words "Hello, World!"
In Python 3.x parenthesis on print is mandatory, essentially making it a function, but in 2.7 both will work with differing results. What else should I know about print in Python 2.7?
In Python 2.x print is actually a special statement and not a function*.
This is also why it can't be used like: lambda x: print x
Note that (expr) does not create a Tuple (it results in expr), but , does. This likely results in the confusion between print (x) and print (x, y) in Python 2.7
(1) # 1 -- no tuple Mister!
(1,) # (1,)
(1,2) # (1, 2)
1,2 # 1 2 -- no tuple and no parenthesis :) [See below for print caveat.]
However, since print is a special syntax statement/grammar construct in Python 2.x then, without the parenthesis, it treats the ,'s in a special manner - and does not create a Tuple. This special treatment of the print statement enables it to act differently if there is a trailing , or not.
Happy coding.
*This print behavior in Python 2 can be changed to that of Python 3:
from __future__ import print_function
It's all very simple and has nothing to do with forward or backward compatibility.
The general form for the print statement in all Python versions before version 3 is:
print expr1, expr2, ... exprn
(Each expression in turn is evaluated, converted to a string and displayed with a space between them.)
But remember that putting parentheses around an expression is still the same expression.
So you can also write this as:
print (expr1), (expr2), ... (expr3)
This has nothing to do with calling a function.
Here we have interesting side effect when it comes to UTF-8.
>> greek = dict( dog="σκύλος", cat="γάτα" )
>> print greek['dog'], greek['cat']
σκύλος γάτα
>> print (greek['dog'], greek['cat'])
('\xcf\x83\xce\xba\xcf\x8d\xce\xbb\xce\xbf\xcf\x82', '\xce\xb3\xce\xac\xcf\x84\xce\xb1')
The last print is tuple with hexadecimal byte values.
Basically in Python before Python 3, print was a special statement that printed all the strings if got as arguments. So print "foo","bar" simply meant "print 'foo' followed by 'bar'". The problem with that was it was tempting to act as if print were a function, and the Python grammar is ambiguous on that, since (a,b) is a tuple containing a and b but foo(a,b) is a call to a function of two arguments.
So they made the incompatible change for 3 to make programs less ambiguous and more regular.
(Actually, I think 2.7 behaves as 2.6 did on this, but I'm not certain.)
Ran into some interesting Python behavior today. I though I was writing
print("{}".format("some value"))
but instead I wrote
print("{}").format("some value")
and funnily enough it worked. So my question is, how does this work?
Digging deeper
This behavior seems to be python2 specific.
Python2.7
>>> print("{}").format("testing")
testing
Python3.4
>>> print("{}").format("testing)
File "<stdin>", line 1
print("{}").format("testing)
^
SyntaxError: EOL while scanning string literal
It also seems like the print function of python2 doesn't have a return value but Python3 does? so that confuses me even more.
Python2.7
>>> type(print("testing))
File "<stdin>", line 1
type(print("testing))
^
SyntaxError: invalid syntax
>>> a = print("testing")
File "<stdin>", line 1
a = print("testing")
^
SyntaxError: invalid syntax
Python3.4
>>> type(print("{}"))
{}
<class 'NoneType'>
>>> a = print("{}")
{}
>>> a
>>> type(a)
<class 'NoneType'>
In Python 2, print is a statement, not a function (unless you do from __future__ import print_function at the top of your module). This means that the parentheses around the thing you're printing are not part of a function call, but just treated as grouping parentheses. In the situation you describe ("{}") is the same as "{}" (the parens do nothing), so the format call works just like you'd expect if you wrote "{}".format(...).
In Python 3, print is a function, so the parentheses are not optional and can't be put in the wrong place. print returns None, so you're almost certainly going to get an error if you do print(something).something_else, since None doesn't have a something_else attribute.
In Python 2.7, print is a statement; this means that
print("{}").format("testing")
prints one expression, the result of the expression ("{}").format("testing"). That is, the format method is called on the (parenthesized) string before the print statement is evaluated. If you use
from __future__ import print_function
in the 2.7 examples, you'll get identical behavior to Python 3.
You're missing the closing quote after some strings (e.g. "testing).
As others are saying, Python 2 doesn't have a print() function, it has a print statement. Your strings (even if they were properly closed) are not what and where you think they are.
In Python 2, print is a statement keyword like raise, not a function. Parentheses aren't used for its arguments, and so print("{}").format("testing") is parsed as though you'd written print ("{}").format("testing"), which is the same as print(("{}").format("testing")). Because print is a statement, it cannot be used as an expression, and therefore it cannot have a return value.
If you want print in Python 2 to act like Python 3's print function, place this line at the top of your file:
from __future__ import print_function
I'm brushing up on my Python and I'm a little confused about something, the following code does not work as intended:
def a():
print "called a"
def b():
print "called b"
dispatch = {'go':a, 'stop':b}
dispatch[input()]()
When I type the word go into the console, I get "NameError: name 'go' is not defined", but when I type 'go' (with the quotes) it works fine. Is input() not returning a string? And if not, then shouldn't using str() convert the input to a string?
When I change the code to:
dispatch[(str(input())]()
I still get the same behaviour.
note: I'm using Python2.7 if it makes a difference.
Sorry if this is obvious, it's been a few years since I've used Python!
input() in Python 2.7 is equivalent to:
eval(raw_input())
Hence, you should use raw_input() in python 2.7 to avoid such errors, as it will not try to evaluate the input given.
Because you add in quotation marks, Python interprets this as a string.
Also, note that raw_input() will return a string, so there will be no point in calling str() around it.
Note that in Python 3, input() acts like raw_input() did in Python 2.7
You want raw_input(). input() evaluates the user's input as Python code.
Use raw_input(). input() is equivalent to eval(raw_input()), so when you type go without quotes, python tries to eval go and fails. With the quotes, it eval's the string (ie. returns it) which will work to index your dict.
raw_input will work in every case.
You can also use this:
def go():
print "called a"
def stop():
print "called b"
input()() # Equivalent to eval(raw_input())()
# OR
my_function = input()
my_function() # Might be easier to read
# Another way of doing it:
val = raw_input()
globals()[val]()
I just installed Python 2.7.2 on Windows XP with the idea of learning how to program.
Several of the tutorial books I'm using give examples of print commands which, when I try them, I get different answers.
I expected both of these to return the same thing -
>>> print("Hello, World!")
Hello, World!
>>> print("Hello", "World")
('Hello', 'World')
>>>
I've tried searching around for answers, but I'm not even sure how to explain where I'm going wrong.
Since print is a statement in Python 2.x, you're getting expected behavior. (a,b) is a tuple, so print (a,b) will print it as a tuple.
On the other hand, print is a function in Python 3.x, so
print("hello world")
and
print("hello", "world")
will yield the same answer.
This is one breaking change when going from Python 2.x to 3.x. Understanding the difference is important. Type help() in your interpreter and then print. You will get different descriptions based on your Python version.
I'd suggest checking out this page, which describes in a quick and nice way what worked before and what works now.
In the first case, you are calling the print method passing "Hello World!" as an argument. In Python 2.7 you don't need the braces, so you could also write it as
print "Hello World!"
In the second case you create a tuple ("Hello", "World") and pass that one to print. Therefore the tuple is printed. You are not passing two parameters to print. You are passing just one tuple.
It is not what you think it is. It's one argument and it is a tuple.
x=("Hello", "World")
>>> type(x)
<type 'tuple'>
And the reason that it works like this is because print is not a function but a statement.
Note: In python 3 print is a function.
in Python 2.x, print is a statement and not function. Statements have no paranethesis
print 'Hello World'
That's a bit tricky and will change in Python 3. You can activate this behavior in python 2 by adding the following import at the beginning of your sctipt:
from __future__ import print_fuction
Then, print will become a function and you'll call it like this
print('Hello World')
The difference you see in your example is that ('Hello', 'World') is a tuple while ('Hello World') is a string.
As mentionned by the Python doc :
A tuple consists of a number of values separated by commas
There is no coma in ('Hello world') so it is not a tuple. But ('Hello world',) has a coma before the end of the paranthesis and is a tuple.
The parenthesis in ('Hello world') are valid but are not really useful here.
You sould be careful with this when getting started. Tuples are identified by comas not parenthesis. Except for () which is the empty tuple. As we say in french, "this exception is the confirmation of the rule"
The difference in those two lines:
print("Hello, World!")
-> One string is printed, is says 'Hello, World!'
print("Hello", "World")
-> Two strings are given and both are printed. First 'Hello' and then 'World'