【问题标题】:invalid syntax when running a function call expression using python 2.7.14使用 python 2.7.14 运行函数调用表达式时语法无效
【发布时间】:2018-04-01 04:16:27
【问题描述】:

无法在空闲 python 2.7.14 上运行函数调用表达式。下面的代码可能有什么问题?

fruit = ['apple', 'orange', 'grape', 'apple',
         'orange', 'grape', 'kiwi']  # init the array
#reports the frequency of every item in a list

def analyze_list(l):
    counts = {}
    for item in l:

        if item in counts:
            counts[item] = counts[item] + 1
            else:
                counts[item] = 1

                return counts

    #let analyze a list
    counts =  analyze_list(fruit)
    print counts

【问题讨论】:

  • 您知道 Python 中的缩进很重要,对吧?您的 if-else 缩进错误。

标签: python function call


【解决方案1】:

您的代码没有正确缩进,与 if 语句对应的 else 或 elif 语句必须在同一个缩进块上。

fruit = ['apple', 'orange', 'grape', 'apple', 'orange', 'grape', 'kiwi']  # init the array
#reports the frequency of every item in a list 
def analyze_list(l):
    counts = {}
    for item in l:

        if item in counts:
            counts[item] = counts[item] + 1
        else:
            counts[item] = 1

            return counts

    #let analyze a list
    counts =  analyze_list(fruit)
    print counts 

注意 if 语句与 else 语句是怎样的。

【讨论】:

    猜你喜欢
    • 2014-11-28
    • 2019-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-19
    • 1970-01-01
    相关资源
    最近更新 更多