Sub topic 1
Trying Python Code in the Interactive Shell
Prerequisites
Assume you know basic Python syntax, can open a terminal or command prompt, and have Python 3 installed. The command may be python, python3, or py, depending on your platform.
Starting the interactive interpreter
The interactive interpreter, often called the REPL, reads Python code, evaluates it, prints a result when appropriate, and then waits for more input. Start it from your terminal:
python3On Windows, try:
pyA version message appears, followed by the primary prompt:
>>>Type an expression and press Enter:
>>> 2 + 3
5The REPL evaluates the expression and displays its value immediately. This makes it useful for small experiments and checking how Python works.
Leaving the shell
Call exit() or quit() at the prompt:
>>> exit()You can also send an end-of-file signal. Press Ctrl-D on macOS or Linux. Press Ctrl-Z, then Enter, on Windows. The terminal prompt returns.
How expressions are displayed
The shell automatically displays the value of an expression. It usually displays that value using its representation, or repr, which is an unambiguous text form useful for debugging.
Assignments do not display a value because the assignment statement itself has a result of None, and the REPL suppresses None:
>>> message = "hello\n"
>>> message
'hello\n'The quotes and escaped newline show the representation of the string, not the text a user would normally read.
`print()` versus the echoed representation
print() writes readable text to standard output. It does not show quotes or escape characters in the same way:
>>> print(message)
hello
>>>The blank line comes from the newline already stored in message, followed by the newline that print() adds. By contrast, entering message asks the REPL to display the string's representation.
Exercise
What does the REPL display for x = print("hi"), and why?
Show answer
It prints hi while evaluating print(). Entering x displays nothing because print() returns None, which the REPL suppresses.