簡體   English   中英

Python | 在執行while循環時不返回任何內容

[英]Python | Returns none when doing a 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”,則一切看起來都很好

編輯:添加代碼...

您可以閱讀注釋中的說明

您的代碼在循環中使用的變量存在一些問題,特別是您應該使用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))

您好像拼錯了“長度”。 它應該是“長度”。

除此之外,我認為您要使用的是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的評論進行編輯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM