# sample.pydefread_data():# Read data from a file or database...return[1,2,3,4,5,6,7,8,9,10]sample=read_data()defmean(data):returnsum(data)/len(data)average=mean(sample)
该脚本读取文件或数据库的一些示例数据,并提供计算数据平均值的函数。
继续使用以下命令运行脚本:
$ python-isample.py
Once you press Enter, this command runs the code in sample.py and takes you directly to an interactive session. You’ll recognize this session because your screen will present the REPL’s primary prompt (>>>).
从此时起,您可以检查、测试和调试代码sample.py如所须:
>>>
>>> globals(){ '__name__': '__main__', ... 'read_data': <function read_data at 0x104dd4860>, 'sample': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'mean': <function mean at 0x104fe3ec0>, 'average': 5.5}>>> mean([2,3,3,2])2.5>>> mean([])Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".../sample.py", line 10, in meanreturnsum(data)/len(data)~~~~~~~~~~^~~~~~~~~~~ZeroDivisionError: division by zero
>>> number=-42>>> ifnumber<0:... print("negative")... elifnumber>0:... print("positive")... else:... print("equal to 0")...negative
在此代码片段中,您首先定义一个变量来保存数字。接下来,您开始条件语句。
Once you type the colon character (:) and press Enter, you get three dots (...) on your screen. These dots represent the REPL’s secondary prompt. This prompt on your screen means that you can enter the required indented blocks of your current compound statement.
Note: To break out of the REPL’s secondary prompt, you must press Enter twice. This action will take you back to the primary prompt.
在输入缩进代码块时,请记住标准 REPL 不支持自动缩进:
>>>
>>> ifnumber<0:... print("negative")
File "<stdin>", line 2print("negative")^IndentationError: expected an indented block after 'if' statement on line 1
Note that you can always access the content of a given variable by typing the variable’s name and pressing Enter after it, as you did with numbers. However, if the variable is currently set to None, then you won’t get anything on your screen. You’ll have to use print(), as you did with value.
>>> greeting="Hello, World!
File "<stdin>", line 1greeting="Hello, World!^SyntaxError: unterminated string literal (detected at line 1)>>> 42/0Traceback (most recent call last):
File "<stdin>", line 1, in <module>ZeroDivisionError: division by zero>>> sum()Traceback (most recent call last):
File "<stdin>", line 1, in <module>TypeError: sum() takes at least 1 positional argument (0 given)
大多数版本的Python解释器在运行时都支持代码编辑交互的模式。这些编辑功能包括代码历史记录和基本代码完成。如果您通常使用类 Unix 系统,例如 Linux 和 macOS,那么您可能会熟悉其中的一些功能,这些功能存在于重击和科恩贝壳。
这些编辑功能是使用GNU 阅读线库,它支持多种有用的编辑样式。
Note: A quick way to check whether you have code editing features available in your current setup is to press Ctrl+P in the REPL’s prompt. This shortcut should show the last code instruction in your history. If nothing happens or ^P appears on the screen, then the code editing features aren’t available. Otherwise, you’re ready to go!
While in interactive mode, you can browse this history by using the arrow keys on your keyboard. With the Up key, you can go back in history. With Down, you can go forward in history.
Once you find the desired line of code, you can press Enter to confirm your selection and reuse the target instruction:
Note how the code in your REPL’s history immediately becomes available for reuse. To navigate the code history, use the Up and Down keys until you find the desired snippet.
The navigation starts from the end of the history file and goes up. Every time you press the Up key, you jump to the previous line of code in your history.
Once you find the line of code that you want to reuse or modify, press Enter to accept it. Remember that every line in your code history keeps the original indentation that you used when you first typed the code, which is convenient and saves time.
代码完成
The standard REPL provides basic completion capabilities for variable, object, and module names. This feature is automatically enabled when you start an interactive session. To invoke the available code completions, you can type the starting characters of a given name and press the Tab key. This action triggers the completion search.
If the search finds a match, then the name will automatically be completed for you. If the search finds more than one match, then you’ll have to press Tab again to get the entire list of matching names. If nothing appears after pressing Tab twice, then your search didn’t find any result.
代码完成系统在运行搜索时会查看以下对象:
Python关键词
内置功能, 班级, 和目的名字
当前定义的名称,例如变量, 功能, 和类
进口模块和包裹名字
以下是 REPL 代码完成系统在实践中如何工作的示例:
When you type the first character or characters of your target name and press Enter, you get an automatic completion if the REPL finds a unique match. When the completion system finds more than one name that matches your search, you need to press Tab again to get the list of matching names.
You can type a few more characters and press Tab again, or you can just type the complete name or keyword.
当涉及到访问属性时点符号, 像obj.attr,代码补全系统将建议目标对象的属性和方法的补全:
Once you type the name of an object followed by a dot, you can press Tab to quickly inspect the list of attributes and methods of that object. Then you can start typing the name of your target attribute or method and press Tab again for completion.
Leaning useful keyboard shortcuts can significantly boost your productivity and efficiency when you’re working in a REPL session. For example, pressing Ctrl+C on the REPL’s primary or secondary prompt cancels the input and returns to the primary prompt:
When you press Ctrl+C on the primary or secondary prompt, the interpreter raises a KeyboardInterrupt exception and immediately returns to the primary prompt.
If you press Ctrl+C while some piece of code is running, then the interpreter raises a KeyboardInterrupt exception, interrupting the code’s execution and returning to the primary prompt.
当您启动一个您不愿意完成的长时间运行的任务或当您意外遇到一个问题时,后一种行为非常有用。无限循环:
>>>
>>> whileTrue:... print("Hello!")...Hello!Hello!Hello!^CTraceback (most recent call last):
File "<stdin>", line 2, in <module>KeyboardInterruptHello!
This example presents an infinite while loop. You can break the loop by pressing Ctrl+C on your keyboard. After this key combination, you’re again back to the primary prompt, and your REPL session is ready for new input.
标准 REPL 提供了许多其他有趣且有用的键盘快捷键。下表显示了其中一些:
Keyboard Shortcut
Description
Ctrl+L
Clears the screen, reprinting the current line at the top
Ctrl+D
Exits the current REPL session
Ctrl+C
Raises a KeyboardInterrupt exception and loops back to the primary prompt
Ctrl+B
Moves the cursor back one character
Ctrl+F
Moves the cursor forward one character
Del or Backspace
Deletes the character to the right or left of the cursor, respectively
Ctrl+D
Deletes the character underneath the cursor
Ctrl+A
Moves the cursor to the start of the line
Ctrl+E
Moves the cursor to the end of the line
Ctrl+K
Kills, or deletes, the text from the current cursor position to the end of the line
>>> help(str)Help on class str in module builtins:class str(object) | str(object='') -> str | str(bytes_or_buffer[, encoding[, errors]]) -> str | | Create a new string object from the given object. If encoding or | errors is specified, then the object must expose a data buffer | that will be decoded using the given encoding and error handler. | Otherwise, returns the result of object.__str__() (if defined) | or repr(object). | encoding defaults to sys.getdefaultencoding(). | errors defaults to 'strict'. | | Methods defined here: | | __add__(self, value, /) | Return self+value. | | __contains__(self, key, /) | Return key in self....
In this example, you use the str class object as an argument to help(). This way, you access the class’s help page. You can use the Up and Down keys to move through the page. When you get the desired information, you can press the Q key to exit the help viewer.
>>> help("pathlib")Help on module pathlib:NAME pathlibMODULE REFERENCE https://docs.python.org/3.11/library/pathlib.html The following documentation is automatically generated from the Python source files. It may be incomplete, incorrect or include features that are considered implementation detail and may vary between Python implementations. When in doubt, consult the module reference at the location listed above....
In help mode, you can enter keywords, module names, function names, or any other name. The help system will search for the target name and present the associated documentation page. To try this functionality out, go ahead and type sys on the help> prompt, then press Enter. You’ll get the following page on your screen:
>>>
help> sysHelp on built-in module sys:NAME sysMODULE REFERENCE https://docs.python.org/3.11/library/sys.html The following documentation is automatically generated from the Python source files. It may be incomplete, incorrect or include features that are considered implementation detail and may vary between Python implementations. When in doubt, consult the module reference at the location listed above....
Again, to exit the page, you can press the Q key on your keyboard. The help system allows you to search for different topics. Just type the desired topic and press Enter. If the topic has a documentation page, then you’ll get it on your screen. Otherwise, you’ll get an ImportError that’ll bring you back to the primary prompt:
>>>
help> keywordsHere is a list of the Python keywords. Enter any keyword to get more help.False class from orNone continue global passTrue def if raiseand del import returnas elif in tryassert else is whileasync except lambda withawait finally nonlocal yieldbreak for nothelp> iterableTraceback (most recent call last):...ImportError: No Python documentation found for 'iterable'.Use help() to get the interactive help utility.Use help(str) for help on the str class.
Once you’ve found the required information, then you can exit the help system by typing q or quit and then pressing Enter. This way, you’ll be back to your REPL session.
Returns the list of names in the current local scope when you call it with no argument. Attempts to return a list of valid attributes for the object passed as an argument.
vars()
Returns the .__dict__ attribute for a module, class, instance, or any other object with this attribute. The .__dict__ attribute holds a list of names pertaining to the underlying object.
locals()
Returns a dictionary representing the names in the current local scope.
globals()
Returns the dictionary representing the current module namespace.
type()
Returns the type of an object when you call it with one argument.