0

I am a novice python learner, though I know printing text containing strings and variables but I want to ask a basic question regarding this. Here is my code:

x=5                                                                                        
print ("the value of x is ",x)                                      
print "the value of x is",x

The first print command prints ('the value of x is ', 5) while the second one prints, the value of x is 5. But print ('hello') & print 'hello' prints hello (the same), why?

1
  • 1
    Think about this, if (x + y) + 1 made a tuple out of x + y, that would ruin everything! That's why one-tuples are made like ('hello', ) with that trailing comma Commented Jun 1, 2013 at 8:16

3 Answers 3

2

Because ('hello') is just 'hello', not a 1-tuple.

Sign up to request clarification or add additional context in comments.

Comments

1

Print is a statement in py2x not function. so printing ("the value of x is ",x) actually prints a tuple:

>>> type(('hello'))
<type 'str'>
>>> type(('hello',))  # notice the trailing `,` 
<type 'tuple'>

In py2x just remove the () to get the correct output:

>>> print "the value of x is","foo" 
the value of x is foo

or you can also import py3x's print function:

>>> from __future__ import print_function
>>> print ("the value of x is","foo")
the value of x is foo

2 Comments

thanks, i understood what you said.Will you please suggest me what to do either continue python 2 or skip over to 3?
@ankushsharma Continue with py2.7 as most of the (external)libraries are still on py2x, and the differences between py2x and py3x can be found here:docs.python.org/3.0/whatsnew/3.0.html
0

Assuming Python 2.x, print is a statement and the comma makes the expression a tuple, which prints with parentheses. Assuming Python 3.x, print is a function so the first prints normally and the second is a syntax error.

1 Comment

Typo, thinking ahead..fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.