[英]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. #字符串“ madlib”并返回字符串“ processed”,其中**#“ NOUN”的每个实例都用随机名词替换,而“ 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 始终不返回任何值,如果我手动对其进行测试并更改为“ i”,则一切看起来都很好
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
. 您的代码在循环中使用的变量存在一些问题,特别是您应该使用lenght + i
而不是lenght + 1
。 Also, you're incrementing i
in the wrong spot. 另外,您在错误的位置上增加了i
。
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). 除此之外,我认为您要使用的是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. 根据Aran-Fey的评论进行编辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.