【问题标题】:I need an explanation about functions that we created我需要一个关于我们创建的函数的解释
【发布时间】:2019-02-07 08:16:43
【问题描述】:

为什么我们在这里使用len(command),如果有人能解释我们在这里做了什么,那就太好了(整个事情,它变得复杂了..)

def get_input():
    command = input(": ").split()
    verb_word = command[0]
    if verb_word in verb_dict:
        verb = verb_dict[verb_word]
    else:
        print("Unknown verb{}" .format(verb_word))
        return

    if len(command) >= 2:
        noun_word = command[1]
        print(verb(noun_word))
    else:
        print(verb("nothing"))

def say(noun):
    return 'You said "{}"' .format(noun)

verb_dict = {
    "say" : say,
}
while True:
    get_input()

我无法理解这里的全部内容,我需要解释一下我们上面创建的函数..

【问题讨论】:

    标签: python command


    【解决方案1】:

    len 是一个内置函数:

    >>> len
    <built-in function len>
    

    它决定了一个可迭代对象的 length:

    >>> len([0,1,2])
    3
    >>> len('hello')
    5
    

    在所示代码的情况下,它正在确定command 的长度,大概是str。因此,len(command) 返回command 字符串的字符数。

    【讨论】:

    • 为什么我们写了 command[0] 那么如果你解释说我会感谢你的话,我们怎么能使用那个命令 ^^ 对不起,我是编码新手..
    • 我不确定 为什么 它是这样写的,但 command[0] 转换为(对于字符串)字符串的第一个字符。即如果command = 'hello', command[0] == 'h'
    猜你喜欢
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-01
    相关资源
    最近更新 更多