【发布时间】:2020-11-18 04:41:21
【问题描述】:
您好,我正在检查:
- 如果用户确定文件中存在输入,如果存在,则在文件中查找该输入的行号。
- 如果不存在,则告诉用户输入不存在。
我的 while 循环工作正常,它会找到字符串的行号(如果存在)。但是我的 if 语句有一个逻辑错误,它总是将语句传递给 else。我是 python 新手,如果有人可以提供帮助,那就太好了!
import sys
f=open("/Users/emirmac/Desktop/file.txt","r")
count=1
l=0
inputWord=input("Enter a word: ")
while(l)!="":
l=f.readline()
Line=l.split()
if inputWord in Line:
print("Line number",count,":",l)
count+=1
f.close()
if inputWord in Line:
print(inputWord,"is the",count, "most common word.")
else:
print("Sorry,",inputWord,"is not one of the 4000 most common words.")
【问题讨论】:
标签: python loops file if-statement while-loop