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

自学开发者问询:掷骰子代码风格优化与输入兼容处理方案

Hey there! Let's break down your dice roll code and make it cleaner, more robust, and easier to maintain—since you're aiming for tidy, professional code as a self-taught dev, these tweaks will go a long way.

First, let's call out the core issues with your original code:

  • Broken condition syntax: if Game == "yes"or"Yes" isn't valid Python. Even if you fixed it to if Game == "yes" or Game == "Yes", it still won't handle mixed-case inputs like "YES" or "yEs".
  • Poor readability: Shoving all logic into one line violates PEP8 standards and makes the code hard to debug or modify later.
  • Misplaced import: Putting import random inside the if branch works, but Python convention is to place all imports at the top of your file for clarity.
Optimized Solution: Handling Case Insensitivity + Flexible Inputs

Here's a polished version that addresses your key concerns, plus improves overall code quality:

import random

def play_dice_game():
    # Get user input, strip extra spaces, and convert to lowercase
    user_response = input("Hello there! Would you like to bet your luck on a dice roll?\n").strip().lower()
    
    # Define a set of all valid positive responses (easy to expand later!)
    valid_yes_responses = {"yes", "y", "yeah", "sure", "ok", "let's go"}
    
    if user_response in valid_yes_responses:
        print("Well great! Here we go!")
        print(f"You rolled a {random.randint(1, 6)}!")
    else:
        print("I guess next time then...")

# Run the game when the script is executed directly
if __name__ == "__main__":
    play_dice_game()

Key Improvements Explained:

  • Case insensitivity: Using .lower() on the input ensures any capitalization (like "Yes", "YES", "yEs") gets converted to lowercase, so it matches our valid responses. .strip() also handles accidental spaces (e.g., " Yes ").
  • Flexible input compatibility: Storing valid responses in a set ({"yes", "y", ...}) lets you easily add more accepted phrases later (like "absolutely" or "count me in") without messy or chains. Set lookups are also faster than checking multiple == conditions.
  • Clean structure: Wrapping the game in a function makes it reusable (you could call it multiple times if you wanted), and splitting code into lines follows Python's readability guidelines. The if __name__ == "__main__": check ensures the game only runs when the script is executed directly, not when imported as a module.

This implementation is far more maintainable, user-friendly, and aligned with professional Python coding practices.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:25:17