![](/img/trans.png)
[英]How do I remove the previous question printed when iterating through a loop in python?
[英]How do I loop after each answer is printed in Python
我是否在此处添加“for”循环以及如何添加? 我希望程序重复自己。
print('Ask a question')
import random
messages = ['It is certain',
'It is decidedly so',
'Yes definitely',
'Reply hazy try again',
'Ask again later',
'Concentrate and ask again',
'My reply is no',
'Outlook not so good',
'Very doubtful']
print(messages[random.randint(0, len(messages) - 1)])
魔术8球(问答)
对已发布代码的最小更改
import random
from random import randint
messages = ['It is certain',
'It is decidedly so',
'Yes definitely',
'Reply hazy try again',
'Ask again later',
'Concentrate and ask again',
'My reply is no',
'Outlook not so good',
'Very doubtful']
while True:
question = input("What is your question? ")
if question:
print(messages[random.randint(0, len(messages) - 1)])
else:
break
更好但等效的while循环
while input("What is your question? "):
print(messages[random.randint(0, len(messages) - 1)])
使用随机选择
简化从列表中随机选择消息
while input("What is your question? "):
print(random.choice(messages))
for i in messages:
print(i)
这将遍历消息并打印变量消息
要为每次播放的消息打印随机消息,您可以这样编写,请参阅代码注释:
import random
messages = ['It is certain',
'It is decidedly so',
'Yes definitely',
'Reply hazy try again',
'Ask again later',
'Concentrate and ask again',
'My reply is no',
'Outlook not so good',
'Very doubtful']
user_input = ""
print ("Press enter to play or q + enter to quit")
# while user input doesn't equal q
while user_input != "q":
# print a random message
print(messages[random.randint(0, len(messages) - 1)])
# ask for user input
user_input = input()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.