Meh*_*CER 1 python for-loop while-loop
这是问题所在.我有names.txt文件.该文件的内容如下.该问题要求显示此文件中的名称数量.我可以用while循环.它有效,没问题.但出于某种原因,如果我想用for循环这样做,它会给我错误的名字数量.
Julia Roberts
Michael Scott
Kevin Malone
Jim Halpert
Pam Halpert
Dwight Schrute
Run Code Online (Sandbox Code Playgroud)
这是while循环.它运行完美.
def main():
try:
# open the names.txt file in read mode.
infile=open("names.txt", "r")
# set an accumulator for number of names
numbers_of_name=0.0
# read the first line
line=infile.readline()
# read the rest of the file
while line!="":
numbers_of_name+=1
line=infile.readline()
# print the numbers of names in the names.txt file.
print("There are", int(numbers_of_name), "names in the names.txt file.")
# close the file
infile.close()
except IOError as err:
print (err)
# call the main function
main()
Run Code Online (Sandbox Code Playgroud)
控制台给了我正确的答案.
There are 6 names in the names.txt file.
Run Code Online (Sandbox Code Playgroud)
这是我的循环问题
def main():
try:
# open the names.txt file in read mode.
infile=open("names.txt", "r")
# set an accumulator for number of names
numbers_of_name=0.0
# read the rest of the file
for line in infile:
line=infile.readline()
numbers_of_name+=1
# print the numbers of names in the names.txt file.
print("There are ", numbers_of_name, "names in the names.txt file.")
# close the file
infile.close()
except IOError as err:
print (err)
# call the main function
main()
Run Code Online (Sandbox Code Playgroud)
这是输出.
There are 3.0 names in the names.txt file.
Run Code Online (Sandbox Code Playgroud)
应该有6个名字而不是3个名字:
在这个文件阅读代码中可能缺少什么?提前致谢.
问题是你在每次迭代中读取两行,当你这样做时:
for line in infile:
Run Code Online (Sandbox Code Playgroud)
line是文件中的第一行,当你这样做时:
line.readline()
Run Code Online (Sandbox Code Playgroud)
然后行现在是第二行,然后你添加一个你的名字计数
你应该做:
for line in infile:
numbers_of_name+=1
Run Code Online (Sandbox Code Playgroud)