0

When I code:

x = 4
y = 10

print("X is", x, "and Y is", y)

I get as a result:

('X is', 4, 'and Y is', 10)

Instead of:

X is 4 and Y is 10

Why is this happening? Please help.

Shawn
  • 47,241
  • 3
  • 26
  • 60
  • You are creating a tuple. – user1767754 Nov 29 '17 at 04:47
  • You do get: `X is 4 and Y is 10`, at least in Python 3 which expects `(..)` for `print`. What version of Python is this? – Spencer Wieczorek Nov 29 '17 at 04:48
  • You're using Python 2, and that `print` statement is printing a tuple. If you want to use the `print` _function_ instead (and you should), put this at the start of your script: `from __future__ import print_function`. – PM 2Ring Nov 29 '17 at 04:49
  • I'm sure this question has been asked before, but I can't find a good duplicate target, although this one is fairly close: https://stackoverflow.com/questions/6182964/why-is-parenthesis-in-print-voluntary-in-python-2-7 – PM 2Ring Nov 29 '17 at 04:59

2 Answers2

2

You must be using python 2, where print is a keyword instead of a function. It is interpreting the comma-separated items inside the parentheses as a tuple, and so it is printing the tuple.

Just remove the parentheses and it will work as you expect.

John Gordon
  • 29,573
  • 7
  • 33
  • 58
0

Just do it the modern way with string formatting

print "x is {0} and y is {1}".format(x, y)

Or old school

print "x is " + str(x) + " and y is " + str(y)

or use

print("X is %d and Y is %d" % (x, y))
Mahesh Karia
  • 2,045
  • 1
  • 12
  • 23
user1767754
  • 23,311
  • 18
  • 141
  • 164
  • Thanks for the Edit Mahesh :D I was about to press edit to do this, saved me time! – user1767754 Nov 29 '17 at 04:51
  • The modern way is to stop using Python 2 and migrate to Python 3. ;) But if you can't do that for some reason, it's a Good Idea to use the `__future__` import, to make it easier to write code that runs correctly on both versions. – PM 2Ring Nov 29 '17 at 05:01
  • I agree @PM2Ring with `__future__` is the way to go if you do packages, but if someone just started with Python, i like your first idea more.. – user1767754 Nov 29 '17 at 05:04