Udacity python练习

2024-06-02 20:10:06 发布

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

Im编写了一个madlibs练习,但没有返回预期的结果。它应该用代码中函数中定义的随机动词和名词替换名词和动词。在

我创建了两个测试句子,运行代码后,我只得到两个句子的第一个字符。我无法为我的一生考虑为什么!!在

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]

def process_madlib(madlib):
    #the finished sentence
    processed = ""
    #starting point
    index = 0
    #length to cut from
    box_length = 4
    #
    while index<len(madlib):
        #what you cut off from string
        frame = madlib[index:index+box_length]
        #put to string
        to_add = word_transformer(frame)
        processed += to_add
        if len(to_add) == 1:
            index +=1
        else:
            index +=5
        return processed
    # your code here
    # you may find the built-in len function useful for this quiz
    # documentation: https://docs.python.org/2/library/functions.html#len

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)

结果是

T 我


Tags: tofromteststringindexlenreturnif
1条回答
网友
1楼 · 发布于 2024-06-02 20:10:06

您的报税表位置不正确。 return processed位于while循环中,因此在while循环的第一次迭代之后,您将始终返回值-它只是句子中的第一个字母。在

你得把它放在外面。在

def process_madlib(madlib):
    #the finished sentence
    processed = ""
    #starting point
    index = 0
    #length to cut from
    box_length = 4
    #
    while index<len(madlib):
        #what you cut off from string
        frame = madlib[index:index+box_length]
        #put to string
        to_add = word_transformer(frame)
        processed += to_add
        if len(to_add) == 1:
            index +=1
        else:
            index +=5
    return processed  # <   THIS IS WHAT WAS CHANGED

这将产生以下输出:

^{pr2}$

相关问题 更多 >