- The Python Apprentice
- Robert Smallshire Austin Bingham
- 418字
- 2021-07-02 22:16:51
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
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.
- C語言程序設計(第3版)
- Python Deep Learning
- Python從入門到精通(精粹版)
- 基于Java技術的Web應用開發
- Cassandra Design Patterns(Second Edition)
- Learning Linux Binary Analysis
- Learning Neo4j 3.x(Second Edition)
- 從學徒到高手:汽車電路識圖、故障檢測與維修技能全圖解
- Python機器學習經典實例
- FPGA Verilog開發實戰指南:基于Intel Cyclone IV(進階篇)
- MySQL程序員面試筆試寶典
- Python Machine Learning Blueprints:Intuitive data projects you can relate to
- .NET 4.0面向對象編程漫談:應用篇
- Mastering Leap Motion
- PHP動態網站開發實踐教程