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

如何用函数简化Python代码并实现布尔输入的循环校验?

优化后的Python真假问答游戏代码及解决方案

优化说明

针对需求:

  • 将重复代码封装为函数,简化整体逻辑
  • 实现输入校验循环,强制用户输入'TRUE'或'FALSE'才继续

优化后代码

import random

# 响应语集合
CORRECT_RESPONSES = ['Congrats', 'Good Job', 'You got it', "You're on fire"]
INCORRECT_RESPONSES = ['Better luck next time', 'Think a little harder',
                       'Wow are you stupid', 'How did you get this one wrong']
FINAL_RESPONSES = [
    "You wouldn't even be able to get participation points",
    'You are really really bad at this',
    "You didn't do absolutely terrible but not good either",
    "Good enough job ig"
]

# 结构化存储问题与正确答案
QUESTIONS = [
    ('"The Legend of Zelda Breath of the Wild" Released in 2017 =>', 'TRUE'),
    ('"Super Smash Bros Ultimate" has over 100 playable characters =>', 'FALSE'),
    ('There are over 500 obtainable pokemon across all the games as of 2023 =>', 'TRUE')
]

def get_valid_input(prompt):
    """获取有效的TRUE/FALSE输入,直到用户输入正确格式"""
    while True:
        user_input = input(prompt).strip().upper()
        if user_input in ('TRUE', 'FALSE'):
            return user_input
        print('Please enter "TRUE" or "FALSE"')

def true_or_false_game():
    correct_count = 0
    wrong_count = 0

    # 等待用户输入START开始游戏
    while True:
        start_input = input('Enter "START" to begin =>').strip().upper()
        if start_input == 'START':
            break
        print('Please type "START" to begin')

    # 随机抽取3个问题(与原逻辑一致,允许重复抽取)
    for _ in range(3):
        question, correct_answer = random.choice(QUESTIONS)
        user_answer = get_valid_input(question)
        
        if user_answer == correct_answer:
            print(random.choice(CORRECT_RESPONSES))
            correct_count += 1
        else:
            print(random.choice(INCORRECT_RESPONSES))
            wrong_count += 1

    # 输出最终评价与得分
    print(FINAL_RESPONSES[wrong_count])
    print(f'Correct {correct_count}; Wrong {wrong_count}')

# 启动游戏
true_or_false_game()

关键优化点

  • 结构化问题存储:把问题和正确答案存入列表元组,彻底消除原代码中大量重复的if分支,后续新增问题只需在列表中添加条目即可
  • 输入校验函数:get_valid_input函数封装了循环校验逻辑,确保用户必须输入合法值才会继续,解决了原代码中输入错误直接跳过问题的缺陷
  • 简化主逻辑:用for循环替代原while计数逻辑,去掉递归调用开始游戏的逻辑(避免潜在的递归深度问题),代码更简洁易读
  • 命名规范:调整变量名符合PEP8规范,提升代码可读性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 16:33:17