python互动
At this point, you should have a working Python 3 interpreter at hand. If you need help getting Python set up correctly, please refer to the previous section in this tutorial series.
此时,您应该手头有一个可用的Python 3解释器。 如果需要帮助以正确设置Python,请参阅本教程系列的上一节 。
Here’s what you’ll learn in this section: Now that you have a working Python setup, you’ll see how to actually execute Python code and run Python programs. By the end of this section, you’ll know how to:
这是您在本节中将学到的内容:现在,您已经可以使用Python设置,您将看到如何实际执行Python代码和运行Python程序。 在本节的最后,您将知道如何:
It’s time to write some Python code!
现在该写一些Python代码了!
There is a long-standing custom in the field of computer programming that the first code written in a newly installed language is a short program that simply displays the string Hello, World!
to the console.
在计算机编程领域有一个长期存在的习惯,即以新安装的语言编写的第一个代码是一个简短的程序,只显示字符串Hello, World!
到控制台。
Note: This is a time-honored tradition dating back to the 1970s. See Hello, World! for a brief history. You seriously risk upsetting the qi of the universe if you don’t abide by this custom.
注意:这是一个可以追溯到1970年代的悠久历史。 见你好,世界! 简要的历史。 如果不遵守这一习俗,您就有冒着破坏宇宙气的严重风险。
The simplest Python 3 code to display Hello, World!
is:
显示Hello, World!
的最简单的Python 3代码 是:
printprint (( "Hello, World!""Hello, World!" )
)
You will explore several different ways to execute this code below.
您将在下面探索几种不同的方法来执行此代码。
The most straightforward way to start talking to Python is in an interactive Read-Eval-Print Loop (REPL) environment. That simply means starting up the interpreter and typing commands to it directly. The interpreter:
开始与Python交谈的最直接的方法是在交互式的Read-Eval-Print Loop(REPL)环境中。 这只是意味着启动解释器并直接输入命令。 口译员:
The session continues in this manner until you instruct the interpreter to terminate. Most of the example code in this tutorial series is presented as REPL interaction.
会话将以这种方式继续,直到您指示解释器终止。 本教程系列中的大多数示例代码都以REPL交互的形式呈现。
In a GUI desktop environment, it is likely that the installation process placed an icon on the desktop or an item in the desktop menu system that starts Python.
在GUI桌面环境中,安装过程很可能在桌面上放置了一个图标,或者在启动Python的桌面菜单系统中放置了一个项目。
For example, in Windows, there will likely be a program group in the Start menu labeled Python 3.x, and under it a menu item labeled Python 3.x (32-bit), or something similar depending on the particular installation you chose.
例如,在Windows中,“ 开始”菜单中可能会存在一个标有Python 3.x的程序组,在其下有一个标有Python 3.x(32位)的菜单项,或者类似的内容,具体取决于您选择的特定安装。
Clicking on that item will start the Python interpreter:
单击该项目将启动Python解释器:
Alternatively, you can open a terminal window and run the interpreter from the command line. How you go about opening a terminal window varies depending on which operating system you’re using:
或者,您可以打开终端窗口并从命令行运行解释器。 打开终端窗口的方式因所使用的操作系统而异:
Using your operating system’s search function to search for “command” in Windows or “terminal” in macOS or Linux should find it.
应该使用操作系统的搜索功能在Windows中搜索“命令”或在macOS或Linux中搜索“终端”。
Once a terminal window is open, if paths have been set up properly by the Python install process, you should be able to just type python
. Then, you should see a response from the Python interpreter.
打开终端窗口后,如果Python安装过程已正确设置了路径,则应该只需键入python
。 然后,您应该看到Python解释器的响应。
This example is from the Windows Command Prompt window:
此示例来自Windows命令提示符窗口:
Technical Note: If you are on a Linux system and installed Python 3, it may be that both Python 2 and Python 3 are installed. In that case, it is possible that typing python
at the prompt will start Python 2. Starting Python 3 may require typing something else, like python3
.
技术说明:如果您在Linux系统上并安装了Python 3,则可能是同时安装了Python 2和Python 3。 在这种情况下,可能会在提示符下输入python
来启动Python2。启动Python 3可能需要输入其他内容,例如python3
。
If you installed a more recent version of Python 3 than the one that was included in the distribution, you may even need to specify the version you installed specifically—for example python3.6
.
如果您安装的Python 3版本比发行版中包含的版本更新,您甚至可能需要指定专门安装的版本,例如python3.6
。
If you are not seeing the >>>
prompt, then you are not talking to the Python interpreter. This could be because Python is either not installed or not in your terminal window session’s path. It’s also possible that you just haven’t found the correct command to execute it. You can refer to our installing Python tutorial for help.
如果您没有看到>>>
提示符,那么您就没有在与Python解释器对话。 这可能是因为未安装Python或未在终端窗口会话的路径中。 也有可能您只是没有找到正确的命令来执行它。 您可以参考我们的安装Python教程以获取帮助。
If you are seeing the prompt, you’re off and running! The next step is to execute the statement that displays Hello, World!
to the console:
如果看到提示,则说明您正在运行! 下一步是执行显示Hello, World!
的语句Hello, World!
到控制台:
>>>
prompt is displayed, and the cursor is positioned after it.print("Hello, World!")
exactly as shown.>>>
提示,并且光标位于其后。 print("Hello, World!")
。 The interpreter’s response should appear on the next line. You can tell it is console output because the >>>
prompt is absent:
口译员的答复应出现在下一行。 您可以说这是控制台输出,因为>>>
提示符不存在:
>>> >>> printprint (( "Hello, World!""Hello, World!" )
)
Hello, World!
Hello, World!
If your session looks like the above, then you have executed your first Python code! Take a moment to celebrate.
如果您的会话如上所示,则您已执行了第一个Python代码! 花一点时间庆祝。
Did something go wrong? Perhaps you made one of these mistakes:
出问题了吗? 也许您犯了以下错误之一:
You forgot to enclose the string to be printed in quotation marks:
You remembered the opening quotation mark but forgot the closing one:
>>> print("Hello, World!)
File "" , line 1
print("Hello, World!)
^
SyntaxError: EOL while scanning string literal
You used different opening and closing quotation marks:
You forgot the parentheses:
>>> print "Hello, World!"
File "" , line 1
print "Hello, World!"
^
SyntaxError: Missing parentheses in call to 'print'
You entered extra whitespace characters before the command:
您忘记将要打印的字符串用引号引起来:
>>> print ( Hello , World ! )
File "" , line 1
print ( Hello , World ! )
^
SyntaxError : invalid syntax
您记住了左引号,但忘记了右引号:
您使用了不同的开始和结束引号:
>>> print ( "Hello, World!')
File "" , line 1
print ( "Hello, World!')
^
SyntaxError : EOL while scanning string literal
您忘记了括号:
您在命令前输入了额外的空格字符:
>>> print ( "Hello, World!" )
File "" , line 1
print ( "Hello, World!" )
^
IndentationError : unexpected indent
(You will see in an upcoming section why this matters.)
(您将在接下来的部分中看到为什么这很重要。)
If you got some sort of error message, go back and verify that you typed the command exactly as shown above.
如果收到某种错误消息,请返回并确认是否完全按照上面所示键入命令。
When you are finished interacting with the interpreter, you can exit a REPL session in several ways:
与解释器的交互完成后,可以通过几种方式退出REPL会话:
Type exit()
and press Enter:
In Windows, type Ctrl+Z and press Enter:
>>> ^Z
C:Usersjohn>
In Linux or macOS, type Ctrl+D. The interpreter terminates immediately; pressing Enter is not needed.
输入 exit()
并按Enter :
在Windows中,输入Ctrl + Z ,然后按Enter :
>>> ^ Z
C:Usersjohn>
在Linux或macOS中,键入Ctrl + D。 口译员立即终止; 不需要按Enter 。
Entering commands to the Python interpreter interactively is great for quick testing and exploring features or functionality.
交互地向Python解释器输入命令对于快速测试和探索功能十分有用。
Eventually though, as you create more complex applications, you will develop longer bodies of code that you will want to edit and run repeatedly. You clearly don’t want to re-type the code into the interpreter every time! This is where you will want to create a script file.
但是最终,当您创建更复杂的应用程序时,您将开发更长的代码体,您需要对其进行编辑和重复运行。 您显然不想每次都在解释器中重新输入代码! 这是您要创建脚本文件的地方。
A Python script is a reusable set of code. It is essentially a Python program—a sequence of Python instructions—contained in a file. You can run the program by specifying the name of the script file to the interpreter.
Python脚本是一组可重用的代码。 本质上,它是一个Python程序(一系列Python指令)包含在一个文件中。 您可以通过为解释器指定脚本文件的名称来运行程序。
Python scripts are just plain text, so you can edit them with any text editor. If you have a favorite programmer’s editor that operates on text files, it should be fine to use. If you don’t, the following are typically installed natively with their respective operating systems:
Python脚本只是纯文本,因此您可以使用任何文本编辑器进行编辑。 如果您有喜欢的对文本文件进行操作的程序员编辑器,则应该可以使用。 如果您不这样做,则通常会在其各自的操作系统中本地安装以下软件:
Using whatever editor you’ve chosen, create a script file called hello.py
containing the following:
使用您选择的任何编辑器,创建一个名为hello.py
的脚本文件, hello.py
包含以下内容:
Now save the file, keeping track of the directory or folder you chose to save into.
现在保存文件,跟踪您选择保存到的目录或文件夹。
Start a command prompt or terminal window. If the current working directory is the same as the location in which you saved the file, you can simply specify the filename as a command-line argument to the Python interpreter: python hello.py
启动命令提示符或终端窗口。 如果当前工作目录与保存文件的位置相同,则只需将文件名指定为Python解释器的命令行参数即可: python hello.py
For example, in Windows it would look like this:
例如,在Windows中,它将如下所示:
C:UsersjohnDocumentstest>C:UsersjohnDocumentstest> dir
dir
Volume in drive C is JFS
Volume in drive C is JFS
Volume Serial Number is 1431-F891
Volume Serial Number is 1431-F891
Directory of C:UsersjohnDocumentstest
Directory of C:UsersjohnDocumentstest
05/20/2018 01:31 PM .
05/20/2018 01:31 PM .
05/20/2018 01:31 PM ..
05/20/2018 01:31 PM ..
05/20/2018 01:31 PM 24 hello.py
05/20/2018 01:31 PM 24 hello.py
1 File(s) 24 bytes
1 File(s) 24 bytes
2 Dir(s) 92,557,885,440 bytes free
2 Dir(s) 92,557,885,440 bytes free
C:UsersjohnDocumentstest>python hello.py
C:UsersjohnDocumentstest> python hello.py
Hello, World!
Hello, World!
If the script is not in the current working directory, you can still run it. You’ll just have to specify the path name to it:
如果脚本不在当前工作目录中,则仍然可以运行它。 您只需要指定其路径名即可:
In Linux or macOS, your session may look more like this:
在Linux或macOS中,您的会话可能看起来像这样:
jfs@jfs-xps:~$ jfs@jfs-xps:~$ pwd
pwd
/home/jfs
/home/jfs
jfs@jfs-xps:~$ ls
jfs@jfs-xps:~$ ls
hello.py
hello.py
jfs@jfs-xps:~$ python hello.py
jfs@jfs-xps:~$ python hello.py
Hello, World!
Hello, World!
A script file is not required to have a .py
extension. The Python interpreter will run the file no matter what it’s called, so long as you properly specify the file name on the command line:
脚本文件不需要具有.py
扩展名。 只要您在命令行上正确指定文件名,Python解释器就会运行该文件,无论它叫什么名称。
But giving Python files a .py
extension is a useful convention because it makes them more easily identifiable. In desktop-oriented folder/icon environments like Windows and macOS, this will also typically allow for setting up an appropriate file association, so that you can run the script just by clicking its icon.
但是给Python文件添加.py
扩展名是一个有用的约定,因为它使它们更易于识别。 在Windows和macOS之类的面向桌面的文件夹/图标环境中,这通常还允许设置适当的文件关联,以便您只需单击脚本图标即可运行该脚本。
An Integrated Development Environment (IDE) is an application that more or less combines all the functionality you have seen so far. IDEs usually provide REPL capability as well as an editor with which you can create and modify code to then submit to the interpreter for execution.
集成开发环境(IDE)是一种或多或少结合了您到目前为止所见过的所有功能的应用程序。 IDE通常提供REPL功能以及一个编辑器,您可以使用该编辑器创建和修改代码,然后提交给解释器以执行。
You may also find cool features such as:
您可能还会发现一些很棒的功能,例如:
Most Python installations contain a rudimentary IDE called IDLE. The name ostensibly stands for Integrated Development and Learning Environment, but one member of the Monty Python troupe is named Eric Idle, which hardly seems like a coincidence.
大多数Python安装都包含一个称为IDLE的基本IDE。 这个名字表面上代表集成开发和学习环境,但是Monty Python团伙的一个成员叫Eric Idle ,这似乎不太巧合。
The procedure for running IDLE varies from one operating system to another.
运行IDLE的过程因一个操作系统而异。
Go to the Start menu and select All Programs or All Apps. There should be a program icon labeled IDLE (Python 3.x 32-bit) or something similar. This will vary slightly between Win 7, 8, and 10. The IDLE icon may be in a program group folder named Python 3.x. You can also find the IDLE program icon by using the Windows search facility from the start menu and typing in IDLE
.
转到“开始”菜单,然后选择“ 所有程序”或“ 所有应用程序” 。 应该有一个标有IDLE(Python 3.x 32位)或类似名称的程序图标。 在Win 7、8和10之间,这会稍有不同。IDLE图标可能位于名为Python 3.x的程序组文件夹中。 您也可以通过使用Windows搜索工具从开始菜单中找到IDLE程序图标并输入IDLE
。
Click on the icon to start IDLE.
单击该图标以启动IDLE。
Open Spotlight Search. Typing Cmd+Space is one of several ways to do this. In the search box, type terminal
and press Enter.
打开Spotlight搜索。 键入Cmd + Space是执行此操作的几种方法之一。 在搜索框中,键入terminal
,然后按Enter 。
In the terminal window, type idle3
and press Enter.
在终端窗口中,输入idle3
,然后按Enter 。
IDLE is available with the Python 3 distribution but may not have been installed by default. To find out whether it is, open a terminal window. This varies depending on the Linux distribution, but you should be able to find it by using the desktop search function and searching for terminal
. In the terminal window, type idle3
and press Enter.
IDLE在Python 3发行版中可用,但默认情况下可能未安装。 要确定是否存在,请打开一个终端窗口。 这取决于Linux发行版,但是您应该可以通过使用桌面搜索功能并搜索terminal
来找到它。 在终端窗口中,输入idle3
,然后按Enter 。
If you get an error saying command not found
or something to that effect, then IDLE is apparently not installed, so you’ll need to install it.
如果您收到一条错误消息,说明command not found
或具有某种意义的command not found
,则显然未安装IDLE,因此您需要安装它。
The method for installing apps also varies from one Linux distribution to the next. For example, with Ubuntu Linux, the command to install IDLE is sudo apt-get install idle3
. Many Linux distributions have GUI-based application managers that you can use to install apps as well.
从一个Linux发行版到另一个Linux发行版,安装应用程序的方法也有所不同。 例如,在Ubuntu Linux上,安装IDLE的命令是sudo apt-get install idle3
。 许多Linux发行版都有基于GUI的应用程序管理器,您也可以使用它们来安装应用程序。
Follow whatever procedure is appropriate for your distribution to install IDLE. Then, type idle3
in a terminal window and press Enter to run it. Your installation procedure may have also set up a program icon somewhere on the desktop to start IDLE as well.
请按照适合您的发行版的任何步骤安装IDLE。 然后,在终端窗口中键入idle3
,然后按Enter以运行它。 您的安装过程可能还会在桌面上的某个地方设置程序图标,以启动IDLE。
Whew!
ew!
Once IDLE is installed and you have started it successfully, you should see a window titled Python 3.x.x Shell, where 3.x.x corresponds to your version of Python:
安装完IDLE并成功启动之后,您应该会看到一个名为Python 3.xx Shell的窗口,其中3.xx对应于您的Python版本:
The >>>
prompt should look familiar. You can type REPL commands interactively, just like when you started the interpreter from a console window. Mindful of the qi of the universe, display Hello, World!
again:
>>>
提示符应该看起来很熟悉。 您可以以交互方式键入REPL命令,就像从控制台窗口启动解释器时一样。 留意宇宙的气息,向世界展示Hello, World!
再次:
The interpreter behaves more or less the same as when you ran it directly from the console. The IDLE interface adds the perk of displaying different syntactic elements in distinct colors to make things more readable.
解释器的行为与您直接从控制台运行它的行为大致相同。 IDLE界面增加了以不同的颜色显示不同的语法元素的便利,使内容更易读。
It also provides context-sensitive help. For example, if you type print(
without typing any of the arguments to the print function or the closing parenthesis, then flyover text should appear specifying usage information for the print()
function.
它还提供了上下文相关的帮助。 例如,如果您键入print(
而不键入print函数或右括号的任何参数,则应显示飞越文本,为print()
函数指定用法信息。
One other feature IDLE provides is statement recall:
IDLE提供的另一个功能是语句重新调用:
You can also create script files and run them in IDLE. From the Shell window menu, select File → New File. That should open an additional editing window. Type in the code to be executed:
您还可以创建脚本文件并在IDLE中运行它们。 从Shell窗口菜单中,选择File→New File 。 那应该打开一个附加的编辑窗口。 输入要执行的代码:
From the menu in that window, select File → Save or File → Save As… and save the file to disk. Then select Run → Run Module. The output should appear back in the interpreter Shell window:
从该窗口的菜单中,选择文件→保存或文件→另存为…,然后将文件保存到磁盘。 然后选择运行→运行模块 。 输出应重新出现在解释器“ Shell”窗口中:
OK, that’s probably enough Hello, World!
. The qi of the universe should be safe.
好的,这可能就够了Hello, World!
。 宇宙的气应该是安全的。
Once both windows are open, you can switch back and forth, editing the code in one window, running it and displaying its output in the other. In that way, IDLE provides a rudimentary Python development platform.
一旦两个窗口都打开,您就可以来回切换,在一个窗口中编辑代码,运行它并在另一个窗口中显示其输出。 这样,IDLE提供了基本的Python开发平台。
Although it is somewhat basic, it supports quite a bit of additional functionality, including code completion, code formatting, and a debugger. See the IDLE documentation for more details.
尽管它有些基础,但它支持很多其他功能,包括代码完成,代码格式化和调试器。 有关更多详细信息,请参见IDLE文档 。
Thonny is free Python IDE developed and maintained by the Institute of Computer Science at the University of Tartu, Estonia. It is targeted at Python beginners specifically, so the interface is simple and uncluttered as well as easy to understand and get comfortable with quickly.
Thonny是由爱沙尼亚塔尔图大学计算机科学研究所开发和维护的免费Python IDE。 它专门针对Python初学者,因此界面简单而整洁,易于理解,并且很快就可以适应。
Like IDLE, Thonny supports REPL interaction as well as script file editing and execution:
与IDLE一样,Thonny支持REPL交互以及脚本文件的编辑和执行:
Thonny performs syntax highlighting and code completion in addition to providing a step-by-step debugger. One feature that is particularly helpful to those learning Python is that the debugger displays values in expressions as they are evaluated while you are stepping through the code:
Thonny除了提供逐步调试器之外,还执行语法突出显示和代码完成。 对于那些学习Python的人特别有用的一项功能是,调试器在您单步执行代码时会在表达式中显示值时对它们进行显示:
Thonny is especially easy to get started with because it comes with Python 3.6 built in. So you only need to perform one install, and you’re ready to go!
Thonny特别容易上手,因为它内置了Python 3.6。因此,您只需执行一次安装,就可以开始了!
Versions are available for Windows, macOS, and Linux. The Thonny website has download and installation instructions.
版本适用于Windows,macOS和Linux。 Thonny网站上有下载和安装说明。
IDLE and Thonny are certainly not the only games going. There are many other IDEs available for Python code editing and development. See our Python IDEs and Code Editors Guide for additional suggestions.
IDLE和Thonny当然不是唯一的比赛。 还有许多其他IDE可用于Python代码编辑和开发。 有关其他建议,请参见我们的《 Python IDE和代码编辑器指南》 。
As you saw in the previous section, there are websites available that can provide you with interactive access to a Python interpreter online without you having to install anything locally.
正如您在上一节中所看到的,有可用的网站可以为您提供交互式的Python解释器在线访问权限,而无需您在本地安装任何内容。
This approach may be unsatisfactory for some of the more complicated or lengthy examples in this tutorial. But for simple REPL sessions, it should work well.
对于本教程中的一些更复杂或冗长的示例,此方法可能无法令人满意。 但是对于简单的REPL会话,它应该可以正常工作。
The Python Software Foundation provides an Interactive Shell on their website. On the main page, click on the button that looks like one of these:
Python软件基金会在其网站上提供了一个Interactive Shell。 在主页上 ,单击类似于以下按钮之一的按钮:
Or go directly to https://www.python.org/shell.
或直接转到https://www.python.org/shell 。
You should get a page with a window that looks something like this:
您应该获得一个带有如下窗口的页面:
The familiar >>>
prompt shows you that you are talking to the Python interpreter.
熟悉的>>>
提示符向您显示您正在与Python解释器通信。
Here are a few other sites that provide Python REPL:
以下是提供Python REPL的其他一些站点:
Larger applications are typically contained in script files that are passed to the Python interpreter for execution.
较大的应用程序通常包含在脚本文件中,该脚本文件传递给Python解释器以执行。
But one of the advantages of an interpreted language is that you can run the interpreter and execute commands interactively. Python is easy to use in this manner, and it is a great way to get your feet wet learning how the language works.
但是,解释型语言的优点之一是您可以运行解释器并以交互方式执行命令。 Python很容易以这种方式使用,这是让您专心学习语言工作原理的好方法。
The examples throughout this tutorial have been produced by direct interaction with the Python interpreter, but if you choose to use IDLE or some other available IDE, the examples should still work just fine.
本教程中的示例都是通过与Python解释器直接交互而产生的,但是,如果您选择使用IDLE或其他可用的IDE,则这些示例仍然可以正常工作。
Continue to the next section, where you will start to explore the elements of the Python language itself.
继续到下一部分,您将在这里开始探索Python语言本身的元素。
翻译自: https://www.pybloggers.com/2018/05/interacting-with-python/
python互动