简体   繁体   中英

Python | Returns none when doing a while loop

# Let's put it all together. 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!****

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)

Always Return none , if i tested it manually and change "i" all look good

edit : adding code ......

your can read the instruction in the comments

Your code has a few issues with the variable you're using in the loop, specifically you should be using lenght + i instead of lenght + 1 . Also, you're incrementing i in the wrong spot.

Here's a version that works:

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))

It looks like you misspelled "lenght". It should be "length".

Aside from that, what I think you are trying to use is len(i). Here is the code in the middle.

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

edited based on Aran-Fey's comment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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