简体   繁体   English

无法弄清楚为什么函数返回“ None”

[英]Cant figure out why function returns “None”

So I'm trying to write a function for class that takes a string and goes through each character in it, every time it encounters an 'a' 'b' or 'c' it should add 3 5 and 7 to the "value" variable (ie. a=3 b=5 and c=7). 因此,我正在尝试为类编写一个函数,该函数接受字符串并遍历其中的每个字符,每次遇到“ a”,“ b”或“ c”时,都应在“值”上加上3 5和7变量(即a = 3 b = 5和c = 7)。 Then at the end of the string I need to return the remainder of value%11. 然后,在字符串的末尾,我需要返回剩余值%11。

this is what I have so far: 这是我到目前为止所拥有的:

(ps. all the print statements in the hash_func are just so I could see what was going on) (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

and the funtion returns: 函数返回:

b
5
a
8
n
a
11
n
a
14
None

(It just returns "None" w/o the extra print statements) (它只返回“ None”,没有多余的打印语句)

So I know it is adding the values and skipping the letters that arent ab or c correctly, I just cant seem to figure out where the "None" is coming from. 所以我知道它是在添加值并正确跳过arent ab或c字母,我似乎无法弄清楚“ None”的来源。

As I understand it the none value is returned when a function or variable doesn't contain anything so Im not sure why it's being returned after my function executes everything (mostly) correct. 据我了解,当函数或变量不包含任何东西时,不返回任何值,所以我不确定为什么在我的函数执行所有(大部分)正确的函数后会返回它。

If anyone can decipher my code and tell me the stupid mistake I'm making I would be very grateful! 如果有人能破译我的代码并告诉我我犯的愚蠢错误,我将不胜感激!

The answer to your question, your function returns nothing, hence None is returned by default. 问题的答案,您的函数不返回任何内容,因此默认情况下None返回None

Also note you code is wrong, here is the explanation 还要注意你的代码是错误的,这里是解释

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"))

note 1 : When you have an if statement you use the else to match on anything that doesn't match the previous conditions. 注意1 :如果具有if statement可以使用else来匹配不符合先前条件的任何内容。 If you check if ch == 'a' there is no need to check ch != 'a' . 如果检查ch == 'a' ,则无需检查ch != 'a'

Also, doing 另外,

ch == 'a' or X or Y

does not do what you think it does. 不按照您的想法去做。

What it's actually doing is 它实际上是在做

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

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

If you wanna check if ch is one of 'a', 'b', or 'c') you can use something like, ch in ('a', 'b', 'c') 如果要检查ch is one of 'a', 'b', or 'c') ,则可以使用ch in ('a', 'b', 'c')

Additionally for your reference, 另外,供您参考

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)

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

It returns None because it doesn't return anything else. 它返回None因为它不返回任何其他内容。 Stop printing the return value. 停止打印返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM