简体   繁体   English

Python,代码可能陷入无限循环

[英]Python, code may be stuck in infinite loop

I am trying to write a python function with the instruction on the code below.我正在尝试使用下面代码中的说明编写一个 python 函数。

My code doesn't run.我的代码不运行。 I feel like it has run into an infinite loop, please help!感觉好像进了无限循环,求帮助!

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.为函数 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))

return a value from the function:从函数返回一个值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM