认为Python [9.2-练习3]为什么只禁止某些单词?

问题描述 投票:0回答:1

这里是本练习的代码:

import math

words_file =  open('words.txt')
word = words_file.readline()

def avoids():
forbidden_letters = input('Enter the forbidden letters: ')

for word in words_file:
    for letter in word:
        if letter in forbidden_letters:
            print('Forbidden')
        else:
            print(word)

avoids()

为什么当我输入禁止的字母(在此示例中,我输入的是:aei)时,为什么这样的输出?

Enter the forbidden letters: aei
Forbidden
Forbidden
aah

aah

Forbidden
Forbidden
aahed
...

这是words.txt文件。这是Think Python Lesson

python python-3.x
1个回答
0
投票

而不是打印出每个字母是否被禁止使用的字母,而是使用变量来跟踪是否找到了禁止使用的字母,然后仅在检查完所有字母之后,打印出是否您发现了一个被禁止或未被禁止的。

扰流器示例代码。 (单击编辑以查看其正确格式。)

对于words_file中的单词:禁止=错误对于文字中的字母:如果字母在禁忌字母中:禁止=真#(可选)在此处添加break语句以退出此for循环#更早。我们已经找到了一封禁信,所以有#检查其余部分无用。打破#现在您已经检查了所有字母,在此处打印结果如果禁止:打印('禁止')其他:打印(单词)

© www.soinside.com 2019 - 2024. All rights reserved.