玩家与电脑选择相同时无法打印Draw的Python代码问题
问题描述
期望在玩家与电脑选择相同选项时打印“Draw”,但代码在电脑选择完成后直接结束,无法正常输出该内容。原代码如下:
rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ---.__(___) ''' #Write your code below this line 👇 players_choice = input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors. ") if players_choice == "0": print(rock) elif players_choice == "1": print(paper) elif players_choice == "2": print(scissors) import random print("Computer chooses:") computer_options = [rock, paper, scissors] computer_choice = random.choice(computer_options) print(computer_choice) if computer_choice == players_choice: print("Draw")
问题原因
判断条件的对比对象不匹配:
players_choice是用户输入的字符串("0"/"1"/"2")computer_choice是随机选中的ASCII图形字符串
两者类型和内容完全不同,导致if computer_choice == players_choice永远不会触发。
修正方案
统一对比基准,改用数字索引进行判断,同时保留图形输出:
rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ---.__(___) ''' #Write your code below this line 👇 players_choice = input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors. ") # 将用户输入转为整数,方便后续对比 player_idx = int(players_choice) # 根据索引打印玩家选择的图形 if player_idx == 0: print(rock) elif player_idx == 1: print(paper) elif player_idx == 2: print(scissors) import random print("Computer chooses:") computer_options = [rock, paper, scissors] # 先随机生成电脑选择的索引 computer_idx = random.randint(0, 2) computer_choice = computer_options[computer_idx] print(computer_choice) # 对比索引判断是否平局 if computer_idx == player_idx: print("Draw")
内容的提问来源于stack exchange,提问作者Oran Kelly
相关产品推荐
相关产品推荐

