首页 > 解决方案 > Python:试图理解这个函数是如何工作的以及它的目的是什么

问题描述

我有一个任务来解释以下功能的工作原理。我是编程世界的新手,我真的很难理解这个函数的用例可能是什么。我也有点迷失试图理解函数的步骤。

我已经评论了此功能中发生的大多数操作,如果我有任何错误或误解,请随时纠正我。

def find(word, letter):
    # Function with 'word' an 'letter' as parameter
    index = 0
    # Set index to 0
    while index < len(word):
        # While index has a smaller letter count than then the given 'word', proceed
        if word[index] == letter:
            # If one of the indexed letters from 'word' is equal to 'letter', proceed
            return index
            # Return to index underneath here
        index += 1
        # Add the value of '1' to 'index' for every time the program loops through 'word'
    return -1
    # Here i have no clue

我真的很感谢所有帮助,很抱歉提出所有这些菜鸟问题,但我无处可去。

标签: python-3.x

解决方案


这个函数很简单,它的作用就是在word参数中查找字母参数,如果找到返回字母参数在word中的位置,如果没有找到返回-1表示没有找到。如果你是新手,可以从入门教程开始,虽然你可以在这里找到答案,但这不是正确的方法。


推荐阅读