同步阅读进度,多语言翻译,过滤屏幕蓝光,评论分享,更多完整功能,更好读书体验,试试 阅读 ‧ 电子书库
A Simple Interactive Loop
Suppose you’re asked to write a Python program that interacts with a user in a console window. Maybe you’re accepting inputs to send to a database, or reading numbers to be used in a calculation. Regardless of the purpose, you need to code a loop that reads one or more inputs from a user typing on a keyboard, and prints back a result for each. In other words, you need to write a classic read/evaluate/print loop program.
In Python, typical boilerplate code for such an interactive loop might look like this:
while True:
reply = input('Enter text:')
if reply == 'stop': break
print(reply.upper())
This code makes use of a few new ideas:
In effect, this combination of statements essentially means “read a line from the user and print it in uppercase until the user enters the word ‘stop.’” There are other ways to code such a loop, but the form used here is very common in Python code.
Notice that all three lines nested under the while header line are indented the same amount—because they line up vertically in a column this way, they are the block of code that is associated with the while test and repeated. Either the end of the source file or a lesser-indented statement will terminate the loop body block.
When run, here is the sort of interaction we get from this code:
Enter text:spam
SPAM
Enter text:42
42
Enter text:stop
Note
Version skew note: This example is coded for Python 3.0. If you are working in Python 2.6 or earlier, the code works the same, but you should use raw_input instead of input, and you can omit the outer parentheses in print statements. In 3.0 the former was renamed, and the latter is a built-in function instead of a statement (more on prints in the next chapter).
请支持我们,让我们可以支付服务器费用。
使用微信支付打赏