Python分院帽(Codedex 15):如何统计选中选项的学院得分并输出
解决分院帽项目的得分统计问题
你的代码核心问题是没有正确初始化和更新各学院的得分变量,最后计算总分的逻辑也完全不对。下面是修正后的完整代码,我会把关键问题和修改点说明白:
原代码的核心问题
- 没有为四个学院创建独立的得分变量,比如
gryffindor = 0,导致无法累计分数 - 存在语法错误的语句:
input1 total = input1 == 1 + 0,这行完全不符合Python语法,也起不到统计分数的作用 - 最后把
input1 + input2 + input3作为所有学院的总分,这是把用户输入的选项数字相加,和学院得分毫无关系
修正后的完整代码
# 初始化四个学院的得分,初始为0 gryffindor = 0 slytherin = 0 hufflepuff = 0 ravenclaw = 0 # Question 1 print("Do you like Dawn or Dusk?") print("1) Dawn") print("2) Dusk") input1 = int(input("My answer is: ")) if input1 == 1: print("Gryffindor and Ravenclaw +1") gryffindor += 1 ravenclaw += 1 elif input1 == 2: print("Hufflepuff and Slytherin +1") hufflepuff += 1 slytherin += 1 else: print("Wrong input") # Question 2 print("\nWhen I’m dead, I want people to remember me as?") print("1) The Good") print("2) The Great") print("3) The Wise") print("4) The Bold") input2 = int(input("My answer is: ")) if input2 == 1: print("Hufflepuff +1") hufflepuff += 1 elif input2 == 2: print("Slytherin +1") slytherin += 1 elif input2 == 3: print("Ravenclaw +1") ravenclaw += 1 elif input2 == 4: print("Gryffindor +1") gryffindor += 1 else: print("Wrong input") # Question 3 print("\nWhich kind of instrument most pleases your ear?") print("1) The Violin") # 原代码里的Voilin拼写错误,顺便修正了 print("2) The Trumpet") print("3) The Piano") print("4) The Drum") input3 = int(input("My answer is: ")) if input3 == 1: print("Slytherin +1") slytherin += 1 elif input3 == 2: print("Hufflepuff +1") hufflepuff += 1 elif input3 == 3: print("Ravenclaw +1") ravenclaw += 1 elif input3 == 4: print("Gryffindor +1") gryffindor += 1 else: print("Wrong input") # 输出各学院总分,还可以找出最高分的学院作为最终分院结果 print("\n--- 各学院总分 ---") print(f"Gryffindor: {gryffindor}") print(f"Slytherin: {slytherin}") print(f"Hufflepuff: {hufflepuff}") print(f"Ravenclaw: {ravenclaw}") # 找出最高分对应的学院 max_score = max(gryffindor, slytherin, hufflepuff, ravenclaw) houses = [("Gryffindor", gryffindor), ("Slytherin", slytherin), ("Hufflepuff", hufflepuff), ("Ravenclaw", ravenclaw)] selected_houses = [house for house, score in houses if score == max_score] print("\n--- 分院结果 ---") if len(selected_houses) == 1: print(f"你被分到了 {selected_houses[0]}!") else: print(f"你被分到了 {'、'.join(selected_houses)}!")
关键修改说明
- 初始化得分变量:开头给四个学院各设一个初始值为0的变量,用来累计每次选择的加分
- 正确更新分数:每个选项分支里,用
+=1给对应学院的分数加1,比如选择Dawn时,同时给格兰芬多和拉文克劳各加1分 - 修正语法和拼写错误:去掉了无效的
input1 total语句,修正了小提琴的拼写错误(Violin而非Voilin) - 完善分院结果:不仅输出各学院总分,还自动找出最高分的学院,输出最终分院结果
内容的提问来源于stack exchange,提问作者Gnarlyeah
相关产品推荐
相关产品推荐

