为什么while循环粘在raw_input上?(蟒蛇)

Sou*_*ena 3 python raw-input while-loop

在下面的代码中,我试图使用python脚本创建一个"更多"命令(unix),方法是将文件读入列表并一次打印10行,然后询问用户是否要打印下10行(打印更多. ).问题是raw_input一次又一次地要求输入,如果我给'y'或'Y'作为输入并且不继续while循环并且如果我给任何其他输入while循环制动.我的代码可能不是最好的学习python.

import sys
import string
lines = open('/Users/abc/testfile.txt').readlines()
chunk = 10
start = 0

while 1:
    block = lines[start:chunk]
    for i in block:
        print i
    if raw_input('Print More..') not in ['y', 'Y']:
        break
    start = start + chunk
Run Code Online (Sandbox Code Playgroud)

我得到的输出代码是: -

--
10 lines from file

Print More..y
Print More..y
Print More..y
Print More..a
Run Code Online (Sandbox Code Playgroud)

Tim*_*ker 5

您构建的切片错误:切片中的第二个参数给出了停止位置,而不是块大小:

chunk = 10
start = 0
stop = chunk
end = len(lines)
while True:
    block = lines[start:stop]     # use stop, not chunk!
    for i in block:
        print i
    if raw_input('Print More..') not in ['y', 'Y'] or stop >= end:
        break
    start += chunk
    stop += chunk
Run Code Online (Sandbox Code Playgroud)