[英]How do I loop after each answer is printed in Python
Do I add a "for" loop here and how?我是否在此处添加“for”循环以及如何添加? I want the program to repeat itself.我希望程序重复自己。
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)])
Magic 8-ball (question & answer)魔术8球(问答)
Minimal changes to posted code对已发布代码的最小更改
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
Even Better but equivalent while loop更好但等效的while循环
while input("What is your question? "):
print(messages[random.randint(0, len(messages) - 1)])
Use random.choice使用随机选择
Simplifies random message selection from list简化从列表中随机选择消息
while input("What is your question? "):
print(random.choice(messages))
for i in messages:
print(i)
This will loop through message and print the variable message这将遍历消息并打印变量消息
To print a random message for messages on each play you can write like this, see code comments:要为每次播放的消息打印随机消息,您可以这样编写,请参阅代码注释:
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.