python - 为什么 while 循环停留在 raw_input? (Python)

标签 python while-loop raw-input

在下面的代码中,我试图通过将文件读入列表并一次打印 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

我得到的这段代码的输出是:-

--
10 lines from file

Print More..y
Print More..y
Print More..y
Print More..a

最佳答案

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

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

关于python - 为什么 while 循环停留在 raw_input? (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13267107/

相关文章:

java - 在 Java 中如何重置 While 循环而不破坏它?

python - 为什么我不能用 numba (cuda python) 获得一维数组的正确总和?

python - 这真的会生成随机 float 吗? (Python)

python - 在特定版本的 OpenCV 中使用 python

c++ - 在 Windows 上模拟原始输入

python - 在 python 中。当字典位于类中时,如何让用户更改字典值?

python - 有没有更好的方法来检查输入是否为数字?输入可以是 int 或 float

python - 为什么类型(字节())<'str' >

python - 如何在 5 次尝试后退出 while-true 循环?

java - Java While 循环中的奇怪行为