官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 海伦市| 左贡县| 蓝田县| 沧州市| 青州市| 海宁市| 梨树县| 海宁市| 抚顺县| 调兵山市| 五台县| 桐梓县| 芮城县| 封开县| 祁阳县| 谢通门县| 曲阳县| 花莲市| 板桥市| 曲阜市| 岫岩| 雅安市| 汤原县| 宜州市| 桦川县| 泽普县| 西平县| 万全县| 浙江省| 龙口市| 吕梁市| 庄河市| 绥化市| 龙州县| 绥化市| 延安市| 姚安县| 上思县| 隆回县| 喀喇沁旗| 怀安县|