我尝试使用while循环,这样这个游戏就可以继续玩了,除非用户输入的字符串不是myList中的选项之一。我该把这个while循环放在哪里?(抱歉,我对编码比较陌生)。
import random
def AceDiamondSpade():
#Set up a list which contains Ace, Diamond and Spade so that the computer can randomly choose one of them.
myList = ["Ace", "Diamond", "Spade"]
#
choice = input("Ace, Diamond, or Spade? ")
computerChoice = random.choice(myList)
playAgain = True
if str(choice) != str(myList[0]) and str(choice) != str(myList[1]) and str(choice) != str(myList[2]):
playAgain = False
print ("invalid! Please enter again or make sure that you have capitalized the first letter of your answer!")
if str(choice) == str(computerChoice):
print ("You and the computer selected the same thing, you tie!")
if str(choice) == "Ace" and str(computerChoice) == "Diamond":
print ("You selected Ace, and the comptuer selected Diamond, you win!")
if str(choice) == "Diamond" and str(computerChoice) == "Spade":
print ("You selected Diamond, and the Computer selected Spade, you win!")
if str(choice) == "Spade" and str(computerChoice) == "Ace":
print ("You selected Spade, and the comptuer selected Ace, you win!")
if str(choice) == "Ace" and str(computerChoice) == "Spade":
print ("You selected Ace, and the computer selected Spade, you lose!")
if str(choice) == "Spade" and str(computerChoice) == "Diamond":
print ("You selected Spade, and the computer selected Diamond, you lose!")
if str(choice) == "Diamond" and str(computerChoice) == "Ace":
print ("You selected Diamond, and the computer selected Ace, you lose!")
这是基于diegaoguilar的回答,但它增加了一个新功能的前景。在
我敢肯定你只是直接把代码复制/粘贴到网站上,但是要小心缩进,如果可能的话,在行间留出一些间隔,这样会使阅读变得更容易。在
您可以使用类do while,在python中,它是由几个不同的ways组成的:
所以你的代码应该是这样的:
在
while True
你假设下面的代码块(游戏)将无限执行。但是在if
条件下,检查结果输入是否不是引用的list
的成员,while循环将结束。在我同意这个评论,你不需要在代码的任何一点使用
str
。再增加几个函数也会使它看起来更好。在相关问题 更多 >
编程相关推荐