用于检查变量字符串是否以元音开头的函数?

2024-04-20 07:33:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一种MadLibs的事情,我需要检查我的三个变量是否以元音开头,然后在前面加上“a”或“an”。 我有这个

def vowelcheck(variable):
    if variable[0] == "a" or variable[0] == "e" or variable[0] == "i" or variable[0] == "o" or variable[0] == "u":
        variable = "an " + variable
    else:
        variable = "a " + variable;

然后呢

vowelcheck(noun1)
vowelcheck(noun2)
vowelcheck(noun3)

在变量之后,但它对单词没有任何作用。 我能做些什么来改变它?你知道吗


Tags: oranifdef单词事情variableelse
2条回答

函数的“variable”参数是noune1、noune2和nound2的副本。您确实修改了“variable”,但它不修改名词。你知道吗

请尝试:

def vowelcheck(variable):
    if variable[0] == "a" or variable[0] == "e" or variable[0] == "i" or variable[0] == "o" or variable[0] == "u":
        variable = "an " + variable
    else:
        variable = "a " + variable
    return variable

noun1, noun2, noun3 = (vowelcheck(noun1), vowelcheck(noun2), vowelcheck(noun3))

在Python中,函数参数是通过值传递的,而不是通过引用传递的。所以您只更改局部变量variable,而不是传入的字符串。你知道吗

尝试以下操作:

def vowelcheck(word):
    if word[0] in "aeiou":
        return "an " + word
    else:
        return "a " + word


noun1 = vowelcheck(noun1)
noun2 = vowelcheck(noun2)
noun3 = vowelcheck(noun3)

相关问题 更多 >