0

I am learning Python and I run into a syntax problem. When I try to create a function that prints "Hello (name)", the quotation marks and the comma appear alongside the string.

For example:

def sayHello(name = 'John'):
  print('Hello ', name)

sayHello()

prints as:

('Hello ', 'John')

Any idea why it's the case?

Thanks!

jsrobertouimet
  • 103
  • 1
  • 9

2 Answers2

1

You code would work as expected in Python 3. Python 2 uses print statement, i.e command, rather than function. The command understands your argument as a tuple (pair).

Correct use of print command in Python 2

print 'Hello,' name

Alternatives are

print 'Hello, %s' % name

See Using print() in Python2.x

for details

Community
  • 1
  • 1
Serge
  • 3,387
  • 3
  • 16
  • 34
-1

In python, () means a tuple. It will print "()" if its empty, and "(value1, value2, ...)" if it contains values. In your example, you print a tuple which contains two values "Hello" and name.

If you want to print "Hello (name)", you could try:

print "Hello ", name
print "Hello " + name
Toby Zhou
  • 88
  • 10
  • As stated in [answer], please avoid answering unclear, broad, SW rec, typo, opinion-based, unreproducible, or duplicate questions. Write-my-code requests and low-effort homework questions are off-topic for [so] and more suited to professional coding/tutoring services. Good questions adhere to [ask], include a [mcve], have research effort, and have the potential to be useful to future visitors. Answering inappropriate questions harms the site by making it more difficult to navigate and encouraging further such questions, which can drive away other users who volunteer their time and expertise. – TigerhawkT3 Apr 13 '17 at 03:17
  • This answer doesn't even address the cause of this problem, and it contains inaccurate statements (`(xxx)` isn't a tuple; it's the variable `xxx` with parentheses around it - if it were a tuple, it would display as `(xxx,)`). – TigerhawkT3 Apr 13 '17 at 03:19
  • @TigerhawkT3 thank you for pointing out my problems, and I've edited the "xxx" part to make it clear. I'm quite new to stackoverflow and very sorry for my inaccurate statements. – Toby Zhou Apr 13 '17 at 03:28