0

我正在尝试使用下面代码中的指令编写一个 python 函数。

我的代码没有运行。我觉得它陷入了无限循环,请帮助!

为函数 process_madlib 编写代码,该函数接受字符串“madlib”并返回字符串“processed”,其中“NOUN”的每个实例被替换为随机名词,“VERB”的每个实例被替换为随机动词。

# Write code for the function process_madlib, which takes in 
# a string "madlib" and returns the string "processed", where each instance of
# "NOUN" is replaced with a random noun and each instance of "VERB" is 
# replaced with a random verb. 

from random import randint

def random_verb():
    random_num = randint(0, 1)
    if random_num == 0:
        return "run"
    else:
        return "kayak"

def random_noun():
    random_num = randint(0,1)
    if random_num == 0:
        return "sofa"
    else:
        return "llama"

def word_transformer(word):
    if word == "NOUN":
        return random_noun()
    elif word == "VERB":
        return random_verb()
    else:
        return word[0]

# Write code for the function process_madlib, which takes in 
# a string "madlib" and returns the string "processed", where each instance of
# "NOUN" is replaced with a random noun and each instance of "VERB" is 
# replaced with a random verb. You're free to change what the random functions
# return as verbs or nouns for your own fun, but for submissions keep the code the way it is!

def process_madlib(mad_lib):
    processed = ""
    index = 0

    while index < len(mad_lib):
        if mad_lib[index:index+4] == "NOUN":
            mad_lib.replace("NOUN", random_noun())
        elif mad_lib[index:index+4] == "VERB":
            mad_lib.replace("VERB", random_verb())
        else:
            index += 1


test_string_1 = "This is a good NOUN to use when you VERB your food"
test_string_2 = "I'm going to VERB to the store and pick up a NOUN or two."
print (process_madlib(test_string_1))
print (process_madlib(test_string_2))
4

1 回答 1

0

从函数返回一个值:

def process_madlib(mad_lib):
    processed = ""
    index = 0

    while index < len(mad_lib):
        if mad_lib[index:index+4] == "NOUN":
            mad_lib = mad_lib.replace("NOUN", random_noun())
        elif mad_lib[index:index+4] == "VERB":
            mad_lib = mad_lib.replace("VERB", random_verb())
        else:
            index += 1
    return mad_lib
于 2020-02-26T00:50:26.730 回答