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

Python条件语句问题:输入错误城市无法提前终止程序

Fix: Terminate Immediately on Invalid City Input

Hey there! The issue here is super straightforward—right now you're asking for the month input before checking if the city is valid. Let's fix that first, then we'll clean up all that repetitive code too (it'll make your program way easier to maintain!).

Step 1: Fix the Input Flow

The core problem is your input order: you're collecting the month before validating the city. We need to flip that:

  • Get the city input first
  • Check if it's in your allowed list (Chicago, New York, Washington) immediately
  • If it's not valid, print oopsie and exit right away
  • Only proceed to ask for the month if the city is valid

Step 2: Simplify Repetitive Code

Your original code has identical logic repeated for every city-month pair—this is hard to update later. We can use a dictionary to map full city names to their dataframe abbreviations, cutting down all that duplication.

Modified Code

def common_day1():
    # Map full city names to their abbreviations in your dataframe
    allowed_cities = {
        "Chicago": "CHI",
        "New York": "NYC",
        "Washington": "WAS"
    }
    
    # Get and validate city FIRST
    city = input("Enter city: ")
    if city not in allowed_cities:
        print("oopsie")
        return  # Exit function immediately if city is invalid
    
    # Now get and validate month (only if city is valid)
    try:
        month = int(input("Enter Month: "))
        # Ensure month is within 1-6 (matches your original logic)
        if not (1 <= month <= 6):
            print("Invalid month! Please enter a number between 1 and 6.")
            return
    except ValueError:
        print("Invalid month! Please enter a numeric value.")
        return
    
    # Fetch relevant data from your dataframe
    city_month = df_merged[['City','Month','Day']]
    city_abbrev = allowed_cities[city]
    filtered_data = city_month.loc[(city_month['City'] == city_abbrev) & (city_month['Month'] == month)]
    
    # Calculate and display the most common day
    common_day = filtered_data['Day'].value_counts().argmax()
    print(f"The most common day for {city} during {month} is {common_day}.")

# Run the function
common_day1()

Key Changes Explained

  • Early Termination: We validate the city input right after collecting it—no month input is requested if the city is invalid, which fixes your original issue.
  • Reduced Duplication: The allowed_cities dictionary replaces all the repeated city-specific if/elif blocks, making the code shorter and easier to update.
  • Robust Month Validation: Added checks to ensure the month is a valid number between 1-6, which prevents unexpected errors.
  • Cleaner Output: Used an f-string for the final print statement (more readable than .format() in Python 3.6+).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:26:01