import random punches = ['石頭','剪刀','布'] computer_choice = random.choice(punches) user_choice = input('請出拳:(石頭、剪刀、布)') # 請用戶輸入選擇 while user_choice not in punches: # 當用戶輸入錯誤,提示錯誤,重新輸入 print('輸入有誤,請重新出拳') user_choice = input() # 亮拳 print('————戰斗過程————') print('電腦出了:%s' %(computer_choice)) print('你出了:%s' %(user_choice)) # 勝負 print('—————結果—————') if user_choice == computer_choice: # 使用if進行條件判斷 print('平局!') elif (user_choice == '石頭' and computer_choice == '剪刀') or (user_choice == '剪刀' and computer_choice == '布') or (user_choice == '布' and computer_choice == '石頭'): print('你贏了!') else: print('你輸了!')
在上面的代碼中,判定你勝利的條件很長.我們可以嘗試優化它
石頭的索引為0,剪刀索引為1,布的索引為2(或-1)
分析發現,當你的選擇在列表中的索引等於電腦的索引-1時,你總是勝利的
因此,該條件我們就可以優化為
elif user_choice == punches[punches.index(computer_choice)-1]:
