对于下面的问题,我无法使用while循环语句。这是给a的txt文件. 在
'Write a program that allows the user to navigate through the lines of text in any text file. The program prompts the user for a filename and copies the lines of text from the file into a list. The program then prints the number of lines in the file and prompts the user for a line number. Actual line numbers range from 1 to the number of lines in the file. If the input is 0, the program quits. Otherwise, the program prints the text in that line number.'
请看我的代码。在
enterfile = input("Enter the file name: ")
file = open(enterfile, 'r')
linecount = 0
for line in file:
linecount = linecount + 1
print("The number of lines in this txt. file is", linecount)
linenum = 0
while True:
num = int(input("Please enter a line number or press 0 to quit: "))
if num >=1 and num <= linecount:
file = open(enterfile, 'r')
for lines in file:
linenum = linenum + 1
if linenum == num:
print(lines)
else:
if num == 0:
print("Thanks for using the program")
break
运行程序时,输入行号后行号不会打印。在
显然,我没有正确地使用while循环。有人能告诉我我做错了什么吗?我可以在这里使用def函数吗?在
谢谢!在
在
While True:
循环内移动linenum = 0
行。在当程序重新进入循环时,
linenum
变量必须重置为0(linenum = 0
)。否则,linenum
变量将始终递增,并且其值大于num
,并且永远不会触发if语句以该数字打印行。在循环中包含
linenum = 0
的代码:替代方法:
^{pr2}$函数的作用是:返回一个包含行的列表,然后根据用户输入打印索引值。在
似乎你在输入后错过了作业的第一步
有了它,你就会
现在,忘记您有一个文件,您可以使用}分别获得总行数和特定行数
len(lines)
和{相关问题 更多 >
编程相关推荐