如何在Python中打印出每个答案后进行循环?

最后发布: 2020-07-09


问题

我是否要在这里添加一个 "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)])
python loops for-loop
回答

神奇的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 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()