自学开发者问询:掷骰子代码风格优化与输入兼容处理方案
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 toif 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 randominside theifbranch 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 messyorchains. 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
相关产品推荐
相关产品推荐

