【问题标题】:Define a function called articleStats() that takes a string parameter named fileName定义一个名为 articleStats() 的函数,它接受一个名为 fileName 的字符串参数
【发布时间】:2014-04-19 00:30:41
【问题描述】:

定义一个名为 articleStats() 的函数,它接受一个字符串参数 named fileName 表示文件的名称。该文件包含 用空格分隔的小写单词。该函数返回总数 所有文章的数量。一篇文章是以下单词之一:a, 那个,一个。

我知道这是一个非常简单的问题,但我真的很困惑 我做错了什么。 这是我目前所拥有的,但我知道这是错误的

def articleStats(filename):

filename.split()
for word in filename:
        if 'a' or 'the' or 'an' in word:
            print(len(filename))

articleStats('an apple a day keeps the doctor away')

【问题讨论】:

标签: python function parameters


【解决方案1】:

问题是if 'a' or 'the' or 'an' in word:。在 Python 中,字符串文字被评估为True,因此您的条件被视为:if True or True or 'an' in word

将此更改为if 'a' in word or 'the' in word or 'an' in word

为了更好地了解正在发生的事情,请运行以下代码以查看 Python 如何处理其他情况。

tests = [[], ['not empty list'], {}, {'not':'empty dict'}, 0, 1, '', 'not empty string']
for test in tests:
    print test, bool(test)

【讨论】:

    猜你喜欢
    • 2022-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    • 2020-08-18
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    相关资源
    最近更新 更多