所以我试图创建一个while循环,这样用户就可以选择是否继续这个程序。有什么建议吗?你知道吗
import random
while True:
print ("--------------------------------------------------------------------\n")
name = input("Please enter your name: ")
pack = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21]
random.shuffle(pack)
print ("Welcome {0}! Hope you have fun playing! \n".format(name))
print("Original deck:", pack, "\n")
print ("--------------------------------------------------------------------\n")
for i in range(3):
pack1 = pack[::3]
pack2 = pack[1::3]
pack3 = pack[2::3]
print("1: ", pack1, "\n")
print("2: ", pack2, "\n")
print("3: ", pack3, "\n")
user = input("Pick a number and enter the row it is in: ")
while not (user == "1" or user == "2" or user == "3"):
print(user, " is not a valid answer. Please try again \n")
user = input("Pick a number and enter the row it is in: ")
if user == "1":
pack = pack3 + pack1 + pack2
elif user == "2":
pack = pack1 + pack2 + pack3
elif user == "3":
pack = pack2 + pack3 + pack1
print("The number you are thinking of is:", pack[10], "\n")
answer = input("Would you like to play again (y/n)? ")
if answer != "y" or answer != "n":
break
print ("Please press 'y' or 'n' and then Enter... ")
if answer == "y":
continue
else:
print ("Thank you for playing!")
break
这是一个21张牌的魔术节目。如果你想试试看。你知道吗
编辑:当最后的问题被问到的时候,当你键入“y”时,它并没有真正重新启动程序。你知道吗
一般的主循环结构通常是这样的:
使用控制布尔值来处理用户参与的状态。你知道吗
另外,正如vasilisg所指出的,while循环缩进是不正确的。你知道吗
import random controlFlag = True #add boolean control while controlFlag == True: print (" \n") name = input("Please enter your name: ") pack = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21] random.shuffle(pack) print ("Welcome {0}! Hope you have fun playing! \n".format(name)) print("Original deck:", pack, "\n") print (" \n") for i in range(3): pack1 = pack[::3] pack2 = pack[1::3] pack3 = pack[2::3] print("1: ", pack1, "\n") print("2: ", pack2, "\n") print("3: ", pack3, "\n") user = input("Pick a number and enter the row it is in: ") while not (user == "1" or user == "2" or user == "3"): print(user, " is not a valid answer. Please try again \n") user = input("Pick a number and enter the row it is in: ") if user == "1": pack = pack3 + pack1 + pack2 elif user == "2": pack = pack1 + pack2 + pack3 elif user == "3": pack = pack2 + pack3 + pack1 print("The number you are thinking of is:", pack[10], "\n") answer = input("Would you like to play again (y/n)? ") if answer == "y": controlFlag = True # unnecessary, left in for completeness. elif answer == 'n': print ("Thank you for playing!") controlFlag = False else: print('wrong choice') break
;相关问题 更多 >
编程相关推荐