Interactive Python
2026-08-01
A quick way to start with Python, is to use it interactively. This means, using it in some form of REPL (Read Eval Print Loop). In such an environment, the values of expressions are printed automatically, making it useful as a calculator. The only downside is that your input and results are lost when you exit this environment.
Start Stop
First choice to make, is which of many Python REPLs to use. You can start a command-line REPL in a terminal emulator; start a command-line REPL as a GUI; start a Docker container with a command-line REPL; navigate in your browser to an online REPL… the choices are legion.
To keep things simple, we shall first consider the ‘stock’ standard CPython command-line REPL running in a terminal emulator or the Windows Console, though the stock IDLE graphical console has a ‘nicer’ interface, but is not always installed. And later, the IPython REPL, which is a more productive and friendlier REPL. It too, has a GUI console counterpart, called qtconsole.
From this point, we assume that the python and/or python3 executable is on your PATH by your own actions, or that you have activated a virtual environment, which will ensure python is on your PATH.
CPython REPL
If you have Python installed, and it is on your PATH, or you have a virtual environment enabled, simply running python or python3 on the command-line, will ‘drop’ you into the standard Python interactive environment. You will be presented with something like this:
Python 3.14.6 ···
Type "help", "copyright", "credits" or "license" for more information.
>>> ▄
The first line will give you some information about the version of
Python installed, and for which operating system it has been compiled.
That can vary, so focus on the 3.14.… part, which is the
most important and says we are running Python 3.14. If yours says
3.15.…, that is fine as well; if older that
3.10, you have a problem.
The >>> part is called a prompt, which
indicates that Python is ready for the ‘read’ part of REPL. The
▄ shows the position of your cursor. Whatever you type now,
must be legal Python syntax, but it is good to see what Python will do
if you type something like hello (which is not valid):
- hello
- Traceback (most recent call last):
- File "
", line 1, in - NameError: name 'hello' is not defined. Did you mean: 'help'?
- ▄
Python interprets your input when you press the Enter or CR (carriage return) key. Some call it the newline or linefeed key (NL or LF), which is unnecessarily confusing, but more on that later. This represents the ‘eval’ part in REPL.
The output depends on what you entered; in the above example, we
entered garbage as far as Python is concerned, and it tells us that in
no uncertain terms with an error message. The important parts
in the message are the line number line 1, and the type of
error NameError, which says clearly that hello is not a defined (valid) identifier.
Now we are back at the prompt, which means Python performed the ‘loop’ part in REPL. We can enter expressions, which the REPL will evaluate, and print the result of automatically.
repl
— Automatic printing of expression
statements
2 + 3 * 5- 17
- ▄
The result of the expression is automatically (R)ead, (E)valuated, the result (P)rinted on the next line, and the prompt displayed for the next (L)oop.
Important
❗ This will not work in a script. When a script is
interpreted, a statement that
consists only of an expression like above, will be legal, but
will have no effect. We will have to use
print(2 + 3 * 5) to get the same effect (which will work in
a REPL as well).
You can now type exit()CR to terminate the Python REPL — we have established that it works. In Python 3.14, the parentheses are not necessary. In Unix-like shells, pressing Ctrl-D will also exit the REPL. In Windows, you can press Ctrl+ZCR to exit the REPL.
IPython REPL
A much friendlier Python REPL can be found by way of IPython. This requires the ipython package to be installed with pip, preferably in a virtual environment.
- pip install ipython
- ipython
This will provide you with an ipython
executable command, which should be on your
PATH. Running the ipython
command, will result in something like this:
Python 3.14.6 ···
Type 'copyright', 'credits' or 'license' for more information
IPython 9.16.0 -- An enhanced Interactive Python. Type '?' for help
In [1]: ▄
The number in the IPython prompt will increase with each line executed when you pressed CR. The output will also be numbered in relation to the input number:
In [1]: 2 + 3 * 5
Out[1]: 17
In [2]: ▄
You can refer to previous output with _N where
N is the number in Out[N]. So, if we continue
from above:
In [2]: _1 * 3
Out[2]: 51
In [3]: ▄
s prior to 3.14 The _1 is replaced with the result of Out[1], which was 17, and multiplied by 3, gives 51 (which later can be referred to as _2).
To exit the IPython REPL, you can press Ctrl+D on both Unix-like and Windows environments; or you can type exitCR — no need for parentheses to follow exit as in versions of Python REPLs prior to 3.14.
IPython has many magic commands or just ‘magics’, all starting with %, designed to make your interactive use more productive; here a are a few useful ones:
- %ls — list files in current directory.
- %reset — delete all names (variables, functions, etc.)
- %clear — clear the screen (or %cls on Windows).
- %cd — change working directory.
- %pwd — print working directory.
- %run
script.py— run ascript.pyPython file in the current directory. - %edit
script.py— edit a file in your default system editor, or your configured editor (set in the EDITOR environment variable). - %edit — edit command-line in a temporary file, execute when leaving editor.
Interaction
Python REPLs allow you to enter Python statements and expressions, which the interpreters evaluate. In the case of expressions, they will print the results automatically. But there is more…
Command-Line Editing
You can edit a command-line by moving the cursor with the arrow keys (Left/Right). You can delete characters to the left with backspace (BS). Pressing Ctrl-C will abandon the current line.
Depending on your terminal emulator, you should be able to mark visible characters by dragging your mouse while pressing Left-Click. Once marked, you can copy the marked text to your clipboard. Many terminal emulators, including Windows Terminal, allow you to press Shift-Ctrl-C to perform the copy. Windows Console and Windows Terminal, also will copy the marked text to the clipboard with a Right-Click mouse button.
You can paste text in many terminal emulators, commonly with Shift-Ctrl-V. Windows Console and Terminal will also paste with a mouse Right-Click (as long as nothing is marked).
Command-Line History
When you press the cursor Up key, you will have an opportunity to edit and re-evaluate a previous statement. The more you press Up, the older the statements in your command-line history will appear. You can edit any. The cursor Down key, will show more recent statements. Pressing CR on any historical statement, even after editing it, will cause Python to re-evaluate that statement.
IPython will persist your history in a file; so when you load IPython tomorrow, you can still access old statements. The number of line of history saved, is configurable.
Completion
In most REPLs, you seldom have to type out complete keywords or function names. You only need to type a few starting characters, and the press the Tab key, which will either complete it for you if there is only one possible completion; or it will show you a list of possibilities (you have to press Tab twice in the CPython REPL).
If more than one completion is possible, IPython will show a list of matching possibilities. You can select an appropriate completion by pressing Tab to select successive options. Shift-Tab will select backwards. Press CR to accept a completion.
IPython Edit
If you are using IPython, you can use the %edit ‘magic command’ to
edit a new statement. This will open your default editor, which depends
on your operating system and configuration. You can set an
EDITOR environment variable to control which editor is
used.
After editing a statement in the editor opened with %edit, once the temporary file has been saved and you exited the editor, IPython will load the content, and immediately interpret it.
IPython also allows you to use: ‘%edit file.py’ to edit a Python source file. It will automatically run the source file after you exited from the editor. You can explicitly use ‘%run file’ or ‘%run file.py’ to run any Python script in the current directory.
You can run external commands in IPython with ‘!command’. You can even pass arguments to the command.
Basic Statements
A statement in Python is generally terminated by a newline (NL), but there are exceptions as a matter of convenience. Statements are not automatically assumed to be complete under the following conditions:
- Between paired delimiters like […], (…) and {…}
- Between the delimiters of a long, or tripple-quoted, string: " " " … " " ", or ' ' ' … ' ' '.
- After a backslash + newline sequence (\NL).
- After a colon (:) as part of statement syntax.
A statement must be complete and error-free before it will be successfully evaluated.
You can explicitly continue a statement on the following line by ending a line with \NL (backslash + newline). The REPL will change the prompt to a continuation prompt, in order to show you that the statement is not yet complete. There cannot be spaces or comments after the \.
repl — Explicit statement
continuation
print("ABC
DEF
GHI")- ABCDEFGHI
Between paired delimiters, excluding single and double quotes, you can continue a statement without an explicit continuation backslash. The following statement is split across three lines, producing the same output as the example above. We can even add comments:
repl — Delimiter statement
continuation
print( #← first line of statement.
"ABCDEFGHI" #← second line of statement.
) #← last line of statement.- ABCDEFGHI
One can break lines between other paired delimiters like
{} and [].
repl — More implicit statement
continuations
L = [ 12,
34,
56 ]print(L)D = {
'A':12,
'B':23,
'C':34,
}print(D)
The leading spaces have no syntactic meaning (semantics) in the above examples, but in other places they are significant. We call such places blocks.
Expression Statements
Python has several categories of statements, but a very common one, is the expression statement. It consists of any legal expression. For an expression statement to be useful, it should call a function, or modify program state.
repl — Expression statement
examples
123 + 654 #← no call, no state change.- 777
#← REPL will print result.
- 777
print(a) #← function call.
‘Useless’ expression statements are allowed. Only in a REPL, will the results of such expressions be printed automatically — in a script, they will just be ignored.
Technically, a function call does not involve an operator, but you can think of it as an operator: it performs a task and returns a result, just like an operator. A statement consisting of a single function call, is thus an expression statement (not a function call statement).
Assignment Statements
Unlike some C-like languages, where the equal sign (=) is an operator that copies values and return results, in Python the equal sign is part of an assignment statement. There are several assignment statements.
Simple Assignment
The most basic and common assignment statement syntax, pairs an identifier on the left, of an equal sign (=), with an exprression on the right. Effectively, the identifier labels the result of the exprression.
ident = expr
This is the most common form of assignment. It will create the identifier if it does not exist. A referenced to the exprression will be allocated to the identifier. In Python, the exprression, will always be an object automatically allocated memory.
Chained Assignment
Python supports chained assignment, which means a single statement syntax that assigns the value of an expression to more than identifier. These names will be created if necessary.
ident1 = ident2 = ident3 … identn = expr
Any number of names can appear on the left, separated by equal signs (=).
repl — Chained
assigments
a = b = c = 123 #← a, b, and c reference `123`.
The variables a, b and c, will all ‘label’ the same object.
Iterable Unpacking
It is possible to have several names on the left of a single assignment, as long as there is an iterable expression on the right. Abstractly, an iterable is a collection of values that can be ‘visited’ one-by-one. The number of items in the iterable must match the number of names on the left. This syntax is called iterable unpacking (though some call it tuple unpacking).
ident1, ident2, … identn = iterable
The result of the right hand expression can be of any type, as long as the type supports iteration. This is true for functions like range. Types like list and tuple, including their literals are also iterable.
repl
— Tuple
unpacking
a, b, c = 11, 22, 33 #← (tuple) a=11, b=22, c=33.a, b, c = [ 11, 22, 33 ] #← (list) a=11, b=22, c=33.a, b, c = range(3) #← (range) a=0, b=1, c=2.T = 11, 22, 33a, c, c = T #← (tuple) a=11, b=22, c=33.a, b, c = 11, 22, 33, 44 #← ERROR (too many on right).a, b, c = 11, 22 #← ERROR (too few on right).
As long as the expression on the right is an iterable of three values, the unpacking will work as expected. It does not matter if the expression is a literal tuple, a literal list, the result of a function call, or a sequence variable (like L above).
Extended Iterable Unpacking
A special syntax allows one of the names on the left, to be prefixed with an asterisk (*). This name will always be a list, and will ‘consume’ all the items on the right, that was not allocated to other names. It is possible for such a variable to be an empty list. This syntax is called extended iterable unpacking.
repl — Extended iterable
unpacking
*a, b, c = 11, 22, 33, 44 #← a=[11,22], b=33, c=44.-
a, *b, c = 11, 22, 33, 44 #← a=11, b=[22,33], c=44. -
a, b, *c = 11, 22, 33, 44 #← a=11, b=22, c=[33,44].
Augmented Assignments
As a convenient shorthand, Python allows for the assignment's equal sign to be prefixed with a binary operator, e.g.: +=, *=, %=, etc. The op in the syntax below can be any binary operator:
ident op= expr ident = ident op expr
repl — Augmented
assignments
expr = 12ident1 = ident2 = 34ident1 = ident1 + expr #← long way.ident2 += expr #← augmented assignment.print(ident1, ident2) #▷ 46 46
We strongly recommend you use these augmented assignment statements, since they reduce repetition of names, which in turn leaves fewer opportunities for errors.
Identifiers
Formally, we call the names of ‘things’, identifiers. Anything with a name, must follow identifier naming rules. Simplified: an idenifier must start with an alphabetic character, following which, more alphabetic characters, decimal digits, and underscores can follow, to arbitrary length.
Dictionaries
All identifiers are stored in dictionaries. Some identifiers, like those of the built-in functions, are stored in the ‘global’ dictionary. We can inspect dictionaries with the built-in dir function.
repl — Built-ins name
dictionary
import builtinsprint( dir(builtins) )
Calling dir() without arguments in a REPL, will show names in the current module's dictionary. You can get a reference to this dictionary object, using the global function.
In the short term, ignore all names starting with double underscores that may be present in dictionaries. In the output of the following examples, we omitted those names for clarity.
repl — Dictionary
inspections
dir() #←only `__*` names.X = 123 #←add `X` to dictionary.dir() #▷ ['X']print( X ) #▷ 123print( globals()['X'] ) #▷ 123list(globals()) #▷ ['X']
The last statement tries to emphasise the fact that all names are stored in a dictionary. Python just provide some automatic name lookups, that is why ‘print( X )’ produces the same result as the more inconvenient: ‘print( globals()['X'] )’.
Note
Namespaces & Scopes
In Python, a dictionary is often used to represent a namespace. A dictionary is a mapping from keys (like names), to corresponding values (objects). Different dictionaries can represent different namespaces and since dictionaries can contain other dictionaries as values, it is possible to represent nested namespaces. This is how all scopes work in Python.
Named Values
In Python, each entry in a dictionary not only contains an identifier, but also a reference to a value, also known as an object. And that is all. This rule has no exceptions.
An identifier is effectively just a label for an object. The identifier itself has not type, and is only a temporary label for some value. This is very unlike many other programming languages.
The term variable is thus a bit of a misnomer in Python. It is a convenient term, but can be misinterpreted. A variable, i.e., some identifier, as we have seen, is just an entry in a dictionary; all it ‘stores’, is a reference to some object. We can change the reference, but that is all that can ‘vary’.
A ‘variable’ (i.e., a dictionary entry), has no type. The object it currently references, does have a type. This name is only temporarily associated with or ‘has a reference to’, a value — it can be changed at any time.
repl — Named values (identifiers) as
variables
x = 123 #← associate `x` with `123`.print( type(x) ) #▷ intx = 1.23 #← change reference in `x`.print( type(x) ) #▷ floatx = "ABC" #← change reference in `x`.print( type(x) ) #▷ strp = print #← associate `p` with `print`.p("Hello") #▷ Helloprint = bin #← associate `print` with `bin`.p( print(123) ) #▷ 0b1111011
Changing the references of built-in names like the names of built-in functions, is never a good idea. We only want to emphasise the important points:
- all names (identifiers) are entries in dictionaries;
- all names have a temporary associations to values via references.
You are welcome to call ‘names’ ‘variables’, when you know the name references some value, but do misunderstand how names AKA identifiers actually work.
Deleting Names
Names can be only be removed from dictionaries with the del statement. The del is not a built-in function. It has no return result, unlike a function, which always have a return result.
repl —
Delete
names
x = 123 ; print( x ) #▷ 123del xprint( x ) #← ERROR (`x` does not exist)
The last statement tries to look up the name x in the current dictionary, but fails, since we deleted it in the previous statement.
Help
Inside a Python REPL, you can request help for any built-in function, standard library module, or keyword by default. If you have extra modules installed, or even your own, you can still request help, but you must first import the module.
Topical Help
Python has a built-in function called help. To call this function you must append the
function call operator: () or ('‹arg›'). For
an argument, you can enter an standard library
module name, a built-in function name, or even a keyword.
repl —
Topical
help
help('keywords') #← show list of keywords.help('modules') #← show list of standard modules.help('topics') #← specific topics help understands.help('PRECEDENCE') #← show operator precedence table.help('import') #← help for the `import` statement.help('while') #← help for the `while` statement.help('print') #← help for `print` built-in function.
There seems to be no simple way to get a list of built-in functions, but these two statements will show a list of them.
repl — List built-in function
names
show built-in functions
import builtins as bi, inspect as it[f for f in dir(bi) if it.isbuiltin(getattr(bi, f))]
Interactive Help
When calling help() Without an argument, you will enter interactive help, which will display a message with some suggestions. The prompt will change to indicate that your are now inside an interactive help REPL. Type quit to exit the interactive help, or press Ctrl-D.
You can, for example, get a list of keywords by entering keywordsCR. Any of the example above you can enter as: ‘commandCR’:
repl — Start interactive help
REPL
- help()
help — Interactive help
REPL
- keywords
- modules
- topics
- PRECEDENCE
- quit
- ▄
Notice how the prompt changes when you are inside the interactive help REPL.
To inspect the documentation for the any module, we must first import the module. In general terms, the process is:
To display documentation for the math module, as an example:
repl — Show math module
documentation
import mathhelp(math) #←module documentation.help(math.sqrt) #←function documentation.
Text IO
As we have seen Python REPLs will automatically print the results of expression statements. This is not always ideal, since we have no control over how it outputs the results. Plus, this REPL-only feature does not work in scripts.
Text Output
The premier ‘tool’ for writing output, is the print function. It is documented as follows:
print( *objects, sep=' ', end='\n', file=None, flush=False )
The ‘*objects’ part means that you can pass print any number of arguments. It will print each of those arguments separated by the value of the sep parameter, which by default is space (SP or ␣ ). After all arguments have been send to output, the value of end (by default NL or '\n') is added.
The other parameters have default values as indicated, which means they are optional. To pass them however, we must use keyword-argument syntax, which means me must specify the name of the parameter: parm=arg.
repl — Print function
examples
print("ABC", "DEF", 123) #▷ ABC␣DEF␣123print("ABC", 'DEF' sep='!') #▷ ABC!DEFprint("ABC", end='#')) #← ABC ← with no newline.print("DEF") #▷ ABCDEF ← result of last two.
By default, the output ‘file’ is standard output. Practically, this will mean your screen… unless you have changed the default using your shell's redirection or piping features. This works in PowerShell on Windows as well.
The standard output file is represented by sys.stdout. You can change the default output ‘file’ of print by passing the ‘file=expr’ keyword argument. The most immediate use of this, is to write error messages your program produces to standard error, or sys.stderr.
repl — Set output for
print
import sysprint("Hello") #← write to sys.stdout.print("Hello", file=sys.stdout) #← write to sys.stdout.print("Error", file=sys.stderr) #← write to sys.stderr.
You would rarely, if ever, need to the pass the flush keyword argument. The only viable option is True (since the default is False). Output is normally automatically flushed at the end of a line at the latest, or before any input.
repl — Flush keyword
argument
print("Hello", flush=True)
The keyword arguments you pass to print can appear in any order.
Text Input
We can also perform text input using the input function. It allows for an optional prompt to be displayed before waiting for input. The input function returns a str result, minus a trailing newline.
It is possible for input to return an empty string. When Ctrl-D is pressed (or Ctrl-ZCR on Windows), it signals end-of-file, and an exception will be raised.
repl — Text
input
print("Name?: ", end='') #← prompt user.name = input() #← wait for input.print(f"You entered: {name}") #← use input.name = input("Name?: ") #← prompt & wait for input.print(f"You entered: {name}") #← use input.
You do not always need text input; sometimes you want the user to enter, for example, an integer value. So, if the user enters 123, input will return a str value: "123". It looks like a number, but in the computer, it is just a sequence of characters — we cannot perform arithmetic on strings.
Strings that ‘look like’ integers can be converted to strings using int. When the string does not ‘look like’ an integer, int will raise a ValueError exception. Which means you have to ‘handle’ the exception, otherwise your program will crash immediately.
Until we have discussed exceptions in more depth, you can either ignore the possibility, or use the following pattern:
repl — Input error handling
pattern
import systry:
height = input("Height?: ") #← input height.
print(f"Height: {height}") #← use height.
except: #← handle any exception.
print("Bad input", file=sys.stderr)
The first print line will not execute if an exception was raised — execution will continue on the line after except: . If no exception was raised, statements after except, will not execute.
The file=sys.stderr part, is just a good convention: error messages should be written to standard error, which in Python, means: sys.stderr.
If you need to input a floating point value, substitute int above, with float.