我的if语句不起作用

2024-03-28 16:14:59 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的一段代码,我试图做一个拼字游戏类型,但出于某种原因,如果这个语句不工作。我打开的文件是一个包含238000个单词的列表,英文字典,tempword是由传递给这个函数的输入预定义的。所以在这里,我试着把tempword和文件中的每个单词进行比较,但是当它运行时,它不会添加到计数中,即使我知道这个单词在列表中。有什么想法吗?你知道吗

def checkvalidword(tempword):
    tally = 0
    file = open("words.txt")
    for x in file:
        if x == tempword:
            tally+=1
            print("Added to the tally")

Tags: 文件函数代码类型列表字典def语句
2条回答

为了比较这些值,应该使用.strip()if作为:

if x.strip() == 'abc':

因为在每行的末尾,都有一个新行字符\n。您可以将x^{}值打印为:

print repr(x)

您将看到如下内容:

'abc\n'

使用file.readlines()更好,因为它基于\n分割文件的内容。因此,您不必显式地strip新行字符。你知道吗

因为您正在从文件中读取行,所以每行都以'\n'结尾

试着这样做。你知道吗

def checkvalidword(tempword):
tally = 0
file = open("words.txt")
for x in file:
    if x.strip() == tempword:
        tally+=1
        print("Added to the tally")

注意x.strip()

相关问题 更多 >