Reputation: 19
A simple question concerning brackets. I'm intrigued to know why brackets sometimes print, and sometimes remain 'invisible'? In this case I can give an example of the code and the answer to show what I mean.
If I put in:
name = "Larry"
print(name)
print("Hi", name)
raw_input("Enter to exit program")
Why do I get this answer:
Larry
('Hi', 'Larry')
Enter to exit program
Larry without brackets, nor single quotes. Yet ('Hi', 'Larry') is with brackets and single quotes?
Can someone point out what's happening please?
Upvotes: 1
Views: 281
Reputation: 45552
The most recent edition of Python for Absolute Beginners is the third edition published in January 2010, which is for Python 3. You are using Python 2.7. In Python 2.7 print
is a statement and needs no parenthesis. Thus when Python 2.7 sees print("Hi", name)
it sees print
and the tuple ("Hi", name)
. If you were using Python 3 it would interpret the parenthesis as part of a function call with two arguments. The correct solution to your problem is to use Python 3 as that is what your book is teaching you.
Python 2.7:
>>> name = "Larry"
>>> print(name)
Larry
>>> print("Hi", name)
('Hi', 'Larry')
Python 3:
>>> name = "Larry"
>>> print(name)
Larry
>>> print("Hi", name)
Hi Larry
It's possible to make Python 2.7 act like Python 3 by doing from __future__ import print_function
, but I would recommend against that as you will run into other incompatibilities as you go through your book.
Upvotes: 1
Reputation: 4399
The expression in brackets is interpreted as a special datatype, a tuple - a thing that collects some values together. Single and double quotes can be used alternatively in Python to denote strings of characters.
In Python 2.7 the brackets are unnecessary when you print
something and can lead to interpretation problems. Remove them and see what happens.
Compare with this code:
a = ('hello', 3) #a tuple
print a
print 'hello', 3
On the other hand, in Python 3 the brackets would be necessary.
Upvotes: 2