You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python测验计分逻辑问题:修正二次答对扣0.5分的计算错误

修正测验计分逻辑的简洁方案

你的代码核心问题是答错时错误地累加了分数,不管答题结果如何都执行加分操作,导致分数计算偏差。下面是符合需求的简洁修正版,用三元表达式替代冗余的if/else,仅在答对时根据尝试次数加分:

score = 0

# Q1 选择题
for tries in range(2):
    print("\nQUESTION 1:")
    print("Which of the following terms describes the body's ability to maintain its normal state? Input a Letter A-E ")
    print(" a) Anabolism\n b) Catabolism\n c) Tolerance\n d) Homeostasis\n e) Metabolism")
    answer1 = input("Make your choice: ")
    if answer1.lower() == "d":
        print("Correct!")
        # 首次答对加1分,二次答对加0.5分
        score += 1 if tries == 0 else 0.5
        break
    print("False!")
else:
    print("Out of chances! Sorry you are incorrect, Homeostasis (answer D) describes the body’s ability to maintain its normal state.")
    
# Q2 数值题
for i in range(2):
    print("\nQUESTION 2")
    answer = input("How many organ systems are in the human body? Please enter an integer: ") 
    
    if answer == "11":
        print("Correct, there are 11 organ systems in the body. The 11 systems are Integumentary System, Skeletal System, Muscular System, Nervous System, Endocrine System, Cardiovascular System, Lymphatic System, Respiratory System, Digestive System, Urinary System, and Reproductive System")
        score += 1 if i == 0 else 0.5
        break
    print("Incorrect")
    if i == 1:
        print("The correct answer is 11")

print(f"You scored {score} points")

关键修正点:

  • 仅在答对分支内执行加分操作,答错时不做任何分数累加
  • 用1 if 尝试次数==0 else 0.5的三元表达式,简洁判断当前尝试对应的分值
  • 用answer1.lower()统一处理大小写输入,避免因大小写导致的判断错误
  • 移除了无意义的score += 0语句,简化冗余代码

内容的提问来源于stack exchange,提问作者Abi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 12:33:20