首页 > 解决方案 > 如何修复 def 函数运行问题

问题描述

我正在尝试为一个开始的 python 类完成分配,该类要求我们编写一个 def 函数,该函数接受一个字符串作为参数并返回对该单词复数的最佳猜测。我已经写出了代码,但是当我尝试运行它时,它会询问我的输入,但无论我输入什么,它都会返回PS C:\Users\OneDrive\Documents>文件保存在我计算机上的位置。它没有返回任何语法错误,所以我错过了会触发 def 函数的东西吗?请帮助我了解我所缺少的。

singular_word = input("Please enter a word to be pluralized ")
def pluralize_word(singular_word):
    if singular_word[-1] == "x" or "s" or "z":
        es_ending = singular_word[:] + "es"
        print(es_ending)
        return True
    elif singular_word[-2:] == "ch":
        ch_es_ending = singular_word[:-2] + "es"
        print(ch_es_ending)
        return 
    elif singular_word[-1] == "y":
        ies_ending = singular_word[:-1] + "ies"
        print(ies_ending)
        return
    elif singular_word[-1] == "o":
        oes_ending = singular_word[:] + "es"
        print(oes_ending)
        return
    elif singular_word[-1] == "f":
        ves_ending = singular_word[:-1] + "ves"
        print(ves_ending)
        return
    elif singular_word[-2:] == "fe":
        fe_ves_ending = singular_word[:-2] + "ves"
        print(fe_ves_ending)
        return
    else:
        print(singular_word[:] + "s")
        return 

标签: pythonfunction

解决方案


您定义了一个名为 的函数pluralize_word,但您从不调用它!你需要类似的东西

pluralize_word(singular_word)

这需要放在函数定义之后。


还有第二个问题,如下:

singular_word[-1] == "x" or "s" or "z"

以上检查是否singular_word[-1] == "x"为真。如果不是,则检查是否"s"为真。这不是一回事singular_word[-1] == "s" "s"总是正确的,所以你永远不会超越第一种情况(es总是添加)。

你要

singular_word[-1] == "x" or singular_word[-1] == "s" or singular_word[-1] == "z"

或者,正如@John Gordon 建议的那样,您可以在这种情况下使用以下较短的检查:

singular_word[-1] in "xsz"

推荐阅读