def game():
print("Welcome to Nim!")
nim_list_1 = ['*', '*', '*']
nim_list_2 = ['*', '*', '*', '*', '*']
nim_list_3 = ['*', '*', '*', '*','*', '*', '*']
player = 1
pile_num = [1,2,3]
print("Pile 1:", *nim_list_1)
print("Pile 2:", *nim_list_2)
print("Pile 3:", *nim_list_3)
while (nim_list_1 and nim_list_2) or nim_list_3 is not None:
# Catches IndexError if we try to pop from empty list
try:
count = 0
while count != pick and pile is not None:
count += 1
pile.pop()
except IndexError:
print("Can't remove sticks from empty pile")
我面临的问题是:即使列表为空,while循环仍在执行。我希望函数在所有列表变空后立即显示获胜者?任何建议将不胜感激:)
答案 0 :(得分:1)
鉴于您声明的目标是“在所有列表变为空”后立即显示获胜者,测试nim_list_3 is not None
完全错误!
空列表是“虚假”,但这并不意味着它是None
!所以,只是测试
while (nim_list_1 and nim_list_2) or nim_list_3:
将完成(更接近)您声明的目标 - 当列表3为空且列表1为空或列表2为时,退出。这与“所有列表都变空”不一样,但它比对None
的检查更接近! - )
要实际声明“仅在所有列表为空时退出”,它应为:
while nim_list_1 or nim_list_2 or nim_list_3:
当然,由于您没有向我们展示列表的更新方式,因此很难猜测您是否真正意味着您所说的内容(“所有列表变空”)或您编码的内容(三个列表的处理方式不同)