擅长:python、mysql、java
<p>在<code>While True:</code>循环内移动<code>linenum = 0</code>行。在</p>
<p>当程序重新进入循环时,<code>linenum</code>变量必须重置为0(<code>linenum = 0</code>)。否则,<code>linenum</code>变量将始终递增,并且其值大于<code>num</code>,并且永远不会触发if语句以该数字打印行。在</p>
<p><strong>循环中包含<code>linenum = 0</code>的代码</strong>:</p>
<pre><code>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)
while True:
linenum = 0
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
</code></pre>
<hr/>
<p><strong>替代方法:</strong></p>
^{pr2}$