Python |进行while循环时不返回任何内容

时间:2018-08-11 14:26:44

标签: python while-loop

# Let's put it all together. Write code for the function process_madlib, which takes in 

#字符串“ madlib”并返回字符串“ processed”,其中每个实例 **#“ NOUN”被替换为随机名词,并且“ 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]

def process_madlib(text):
    proc =""
    lenght = len("NOUN")
    i=0
    while text[i:i+lenght] !='':
        i +=1
        if text[i:1+lenght] == "NOUN":
            proc= text[i:-1] + word_transformer("NOUN") + text[i+lenght:]
            return proc

    **

**# 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 = "ds NOUN ds"
test_string_2 = "I'm going to VERB VERB to the store and pick up a NOUN or two."
print process_madlib(test_string_1)
print process_madlib(test_string_2)

始终不返回任何值,如果我手动对其进行测试并更改“ i”都很好

编辑:添加代码...

您可以阅读注释中的说明

2 个答案:

答案 0 :(得分:3)

您的代码在循环中使用的变量存在一些问题,特别是您应该使用lenght + i而不是lenght + 1。另外,您在错误的位置增加了i

这是一个有效的版本:

def process_madlib(text):
    proc = ""
    lenght = len("NOUN")
    i = 0
    while text[i:lenght + i] != '':
        if text[i:lenght + i] == "NOUN":
            proc = text[i:-1] + word_transformer("NOUN") + text[i + lenght:]
            return proc
        i += 1
    return text


test_string_1 = "NOUN ds"
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 :(得分:-1)

您似乎拼错了“ lenght”。它应该是“长度”。

除此之外,我认为您要使用的是len(i)。 这是中间的代码。

while text[i:len(text)+1] !='':
    i +=1
    if text[i:len(text)+1] == "NOUN":
        proc= text[i:-1] + word_transformer("NOUN") + text[i+len(text):]
        return proc

根据Aran-Fey的评论进行编辑。

相关问题