Starting Python command line REPL

Now that Python is installed and running, you can immediately start using it. This is a good way to get to know the language, as well as a useful tool for experimentation and quick testing during normal development.

This Python command line environment is a Read-Eval-Print-Loop. Python will READ whatever input we type in, EVALuate it, PRINT the result and then LOOP back to the beginning. You'll often hear it referred to simply as the "REPL".

When started, the REPL will print some information about the version of Python you're running, and then it will give you a triple-arrow prompt. This prompt tells you that Python is waiting for you to type something.

Within an interactive Python session you can enter fragments of Python programs and see instant results. Let's start with some simple arithmetic:

>>> 2 + 2
4
>>> 6 * 7
42

As you can see, Python reads our input, evaluates it, prints the result, and loops around to do the same again.

We can assign to variables in the REPL:

>>> x = 5

Print their contents simply by typing their name:

>>> x
5

 Refer to them in expressions:

>>> 3 * x
15

Within the REPL you can use the special underscore variable to refer to the most recently printed value, this being one of very few obscure shortcuts in Python:

>>> _
15

Or you can use the special underscore variable in an expression:

>>> _ * 2
30
Remember that this useful trick only works at the REPL; the underscore doesn't have any special behavior in Python scripts or programs.

Notice that not all statements have a return value. When we assigned 5 to x there was no return value, only the side-effect of bringing the variable x into being. Other statements have more visible side-effects.

Try the following command:

>>> print('Hello, Python')
Hello, Python

You’ll see that Python immediately evaluates and executes this command, printing the string Hello, Python and returning you to another prompt. It's important to understand that the response here is not the result of the expression evaluated and displayed by the REPL, but is a side-effect of the print() function.

As an aside, print is one of the biggest differences between Python 2 and Python 3. In Python 3, the parentheses are required, whereas is Python 2 they were not. This is because in Python 3, print() is a function call. More on functions later.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset