Sub topic 2
Reusing the Last Result with `_`
Assume you know basic Python syntax, can run a terminal command, and have Python 3 installed. The interactive shell, or REPL, evaluates one input at a time and displays expression results immediately.
Reusing the last result with `_`
In the standard Python shell, _ refers to the last value that the shell displayed. It is useful for quick calculations:
>>> 2 + 3
5
>>> _ * 10
50The underscore stores the result of an expression, not every value created by Python. If you assign a value to _, you replace this automatic reference. Functions that return None, such as print(), do not produce a displayed result, so they do not give _ a useful new value.
Multi-line statements and the `...` prompt
The primary prompt is >>>. When Python needs more input, it shows the continuation prompt, .... An empty line ends an indented block.
>>> for i in range(3):
... print(i * i)
...
0
1
4The same pattern works for function definitions, conditional statements, and try blocks. Keep indentation consistent. The block does not run until you enter the terminating blank line.
Importing and trying out modules
Use import to load a module. You can then call its functions directly through the module name:
>>> import math
>>> math.sqrt(16)
4.0Imports remain available for the rest of the session. If an import fails, read the exception and check the module name, installation, and active Python environment.
Exploring objects with `help()`, `dir()`, and `type()`
Use type() to identify an object's class. Use dir() to list names available on an object or module. Use help() for documentation:
>>> type(math.sqrt(16))
<class 'float'>
>>> 'sqrt' in dir(math)
True
>>> help(math.sqrt)dir() lists possible attributes, including implementation details. It is a discovery tool, not a complete explanation of how an object should be used.
Exercise
What does _ contain after >>> 8 + 2 displays 10, followed by >>> print("done")?
Show answer
In the standard shell, _ still refers to 10 because print() returns None and the shell does not display it.