[英]How do I fix my code for Python Mad lips loops?
我的代码有一些问题,我在下面包含了提示和我的代码。
Mad Libs 是让一个人提供各种单词的活动,然后用这些单词以意想不到的(并且希望是有趣的)方式完成一个短篇小说。
编写一个程序,将一个字符串和一个 integer 作为输入,并使用输入值输出一个句子,如下例所示。 程序重复执行,直到输入字符串退出并忽略随后的 integer 输入。
例如:如果输入是:
苹果 5 鞋 2 退出 0 output 是:
每天吃 5 个苹果,医生远离我。 一天吃两双鞋,医生远离我。
我的代码:
word = ''
tokens = ''
while True:
print('Eating {} {} a day keeps the doctor away.'.format(tokens[0],tokens[1]))
word = input()
tokens = input().split()
if tokens == 'quit':
break
根据您的问题陈述,您必须一遍又一遍地输入,直到输入字符串quit
为止。
试试下面的一段代码:
while True:
word = input()
token = int(input())
if word == 'quit':
break
else:
print(f'Eating {token} {word} a day keeps the doctor away.')
我不确定我是否理解,但也许这就是你要找的。
while True:
word = str(input('Enter word: '))
tokens = int(input('Enter number: '))
print('Eating {} {} a day keeps the doctor away.'.format(tokens,word))
if word == 'quit':
break
我认为这就是你要找的:
tokens = input().split()
index = 0
while True:
print('Eating {} {} a day keeps the doctor away.'.format(tokens[index + 1],tokens[index]))
if tokens[index + 2] == 'quit':
break
index += 2
虽然这会做你想做的事。 如果您输入“apples 5 shoes 2 quit 0”,它将返回
Eating 5 apples a day keeps the doctor away.
Eating 2 shoes a day keeps the doctor away.
我觉得一个更好的更安全的方法是在你到达看起来像这样的标记结束后停下来:
tokens = input().split()
index = 0
maxIndex = len(tokens)
while index + 1 < maxIndex:
print('Eating {} {} a day keeps the doctor away.'.format(tokens[index + 1],tokens[index]))
index += 2
这样您就不需要添加退出,并且如果您忘记它,您的代码将不会永远运行。
while True:
tokens = input().split()
if tokens == ['quit']:
break
print('Eating {} {} a day keeps the doctor away.'.format(tokens[0],tokens[1]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.