Search code examples
python-3.xprintingenthoughtcanopy

Why does the Canopy Python3 IDE return quotes around text when using print function?


I am trying to simply print text in Canopy and here is what's going on.

Input:

k = 3
Print ('Candidate =',k)

Output:

('Candidate =', 3)

Why are the parenthesis and quotations in the output? I just want it to print: Candidate = 3


Solution

  • In Python 2, print is a statement. As a statement, parentheses are not part of the syntax for it (just like with return). So when Python sees print (a, b), it will parse the (a, b) part separately. And for the parser, this is a tuple:

    value = ('Candidate =', k)
    print value
    

    When you print a tuple, it will print parentheses, and inside, a list of all values—with their repr value. And a string’s repr value, is enquoted:

    >>> print repr('Candidate =')
    'Candidate ='
    

    So, to get the result you want, you need to pass 'Candidate =' and k to the print statement, without putting it in a tuple. So you just need to remove the parentheses:

    >>> print 'Candidate =', k
    Candidate = 3
    

    Note that in Python 3, print became a function, so it actually requires parentheses and your original code works like you wanted it. If you want the print function in Python 2 (instead of print being a statement), you can put the following at the top of your code, to make it so:

    from __future__ import print_function