[英]Python, code may be stuck in infinite loop
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.为函数 process_madlib 编写代码,该函数接受字符串“madlib”并返回字符串“processed”,其中“NOUN”的每个实例都替换为随机名词,而“VERB”的每个实例都替换为随机动词。
# 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.
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]
# 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!
def process_madlib(mad_lib):
processed = ""
index = 0
while index < len(mad_lib):
if mad_lib[index:index+4] == "NOUN":
mad_lib.replace("NOUN", random_noun())
elif mad_lib[index:index+4] == "VERB":
mad_lib.replace("VERB", random_verb())
else:
index += 1
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))
return a value from the function:从函数返回一个值:
def process_madlib(mad_lib):
processed = ""
index = 0
while index < len(mad_lib):
if mad_lib[index:index+4] == "NOUN":
mad_lib = mad_lib.replace("NOUN", random_noun())
elif mad_lib[index:index+4] == "VERB":
mad_lib = mad_lib.replace("VERB", random_verb())
else:
index += 1
return mad_lib
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.