【问题标题】:Cant figure out why function returns "None"无法弄清楚为什么函数返回“无”
【发布时间】:2017-11-05 05:27:34
【问题描述】:

所以我正在尝试为类编写一个函数,该函数接受一个字符串并遍历其中的每个字符,每次遇到“a”“b”或“c”时,它应该将 3 5 和 7 添加到“值”变量(即 a=3 b=5 和 c=7)。然后在字符串的末尾我需要返回 value%11 的剩余部分。

这是我目前所拥有的:

(ps. hash_func 中的所有打印语句都是为了让我可以看到发生了什么)

def hash_func(string):
    value=0
    string_length= range(len(string))
    for i in (string_length):
        current_charecter= string[i]
        print (current_charecter)
        if current_charecter== 'a':
            value=value + 3
            print (value)
        elif current_charecter== 'b':
            value=value + 5
            print (value)
        elif current_charecter== 'c':
            value=value + 7
            print (value)
        elif current_charecter!= 'a' or 'b' or 'c':
            value=value+0
        else:
            value=value%11
            print (value)



print(hash_func("banana")) #this is the call to the function that is given by the grader, it should equal 3

函数返回:

b
5
a
8
n
a
11
n
a
14
None

(它只返回“无”而没有额外的打印语句)

所以我知道它正在添加值并正确跳过不是 a b 或 c 的字母,我似乎无法弄清楚“无”的来源。

据我了解,当函数或变量不包含任何内容时,将返回 none 值,所以我不确定为什么在我的函数执行所有内容(大部分)正确后返回它。

如果有人能破译我的密码并告诉我我犯的愚蠢错误,我将不胜感激!

【问题讨论】:

  • 请不要破坏您的帖子。发布问题后,您已将内容授权给整个 Stack Overflow 社区(根据 CC-by-SA 许可)。如果您想取消此帖子与您帐户的关联,请参阅What is the proper route for a disassociation request?
  • 抱歉,您不能这样做:D,人们已经花时间回答,为他人创建有用的内容。您需要按照上面链接的正确路线。
  • 另外,没有人会复制这项工作。他们可能会复制答案的内容,但不会复制问题的内容。

标签: python-3.x


【解决方案1】:

您的问题的答案是,您的函数不返回任何内容,因此默认返回 None

还要注意你的代码是错误的,这里是解释

def hash_func(string):
    value = 0

    # It will iterate over the chars in the string and set ch to each char in
    # turn
    for ch in string:
        if ch == 'a':
            value += 3  # same thing as value = value + 3
        elif ch == 'b':
            value += 5
        elif ch == 'c':
            value += 7

        print(ch, value)

        # You don't need this and it's wrong also (note 1)
        # elif ch != 'a' or 'b' or 'c':
        #    value += 0

    # After you've iterated over the string, only then do you modulo it.
    # Otherwise you're performing a modulo every time you run into a character
    # that's not 'a', 'b' or 'c'
    return "Hash is " + str(value % 11)

print(hash_func("banana"))

注意 1:当您有 if statement 时,您可以使用 else 来匹配与之前条件不匹配的任何内容。如果您检查ch == 'a',则无需检查ch != 'a'

还有,做

ch == 'a' or X or Y

没有按照你的想法去做。

它实际上在做什么

is ch equal to 'a'? Yes, ok condition is true
otherwise, is X true? or condition is true
otherwise, is Y true? or condition is true
otherwise condition is false

https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not

如果你想检查 ch is one of 'a', 'b', or 'c') 是否可以使用 ch in ('a', 'b', 'c') 之类的东西

另外供大家参考,

def better_hash_func(string):
    values = {'a': 3,
              'b': 5,
              'c': 7}
    value = 0
    for ch in string:
        if (ch in values.keys()):
            value += values[ch]
    return "Hash is " + str(value % 11)


def even_better_hash_func(string):
    values = {'a': 3,
              'b': 5,
              'c': 7}

    # We use the sum function to sum the list
    value = sum(
        [values[ch]                     # This is list comprehension
            for ch in string            # It create a list, by iterating over
                if ch in values.keys()  # some iterable (like a list)
        ]                               # This is very similar to a for loop,
    )                                   # but it takes a value you produce each
                                        # iteration and adds that
                                        # to a new list that is returned by the
                                        # list comprehension.
    return "Hash is " + str(value % 11)

有关列表理解的更多信息:http://www.pythonforbeginners.com/basics/list-comprehensions-in-python

【讨论】:

    【解决方案2】:

    它返回None,因为它不返回任何其他内容。停止打印返回值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-06
      • 1970-01-01
      • 2020-08-14
      • 2014-06-28
      • 2017-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多