Python, код может застрять в бесконечном цикле

Я пытаюсь написать функцию Python с инструкцией по приведенному ниже коду.

Мой код не запускается. Я чувствую, что это зациклился, пожалуйста, помогите!

Напишите код для функции process_madlib, которая принимает строку "madlib" и возвращает строку "обработано", где каждый экземпляр "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))

1 ответ

Решение

Вернуть значение из функции:

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
Другие вопросы по тегам