I am confused about the difference between 'n' and print('n')

python, string

Solution

You are running the python interpreter in interactive mode, which echos values back at you. Expressions are evaluated and if they return something other than `None`, the interpreter does the equivalent of:

print(repr(result))

That is the `'n'` you see printed.

`print()` on the other hand, writes directly to your terminal output, after converting the value to a string (the result of the `str()` function, but for a string value, there is no difference as it already is a string object).

This is different from running the Python code in a script; there there is no prompt, and if you put just `'n'` on one line, the Python interpreter would just ignore that line as it doesn't alter any state. `print('n')` on the other hand still would write the string to your console or terminal.

The interactive mode is there to help you figure out what python expressions do, and by using `repr()` you can distinguish between different types of objects. Try print `1` and `"1"`, so an integer number, and a string with the digit `1` in it:

>>> print(1)
1
>>> print("1")
1

You cannot tell the difference between these two. But their representation does differ:

>>> 1
1
>>> "1"
'1'

Representations for most Python standard types will use a notation that can be reused in your Python code, as-is.

Problem

I am still confused when entering this command in the Python shell: ``` >>> 'n' 'n' >>> print('n') n ``` What does `'n'` (first output) mean? And what does the other one `n` mean? Why doesn't Python just print `n` as output of `'n'` same as `print('n')` produced? I think `print('n')` means: I (Python) print `n` as a character Then how about the first one? if `>>> 'n'` means the same, why doesn't it just print `n` as well?

Original source