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

Python共享单车项目输入报错求助:合法选项仍提示无效

US Bikeshare Project: Stuck on "Invalid choice..." Despite Valid Input

Hey there, let's fix this issue right away! The problem is rooted in your get_filters() function—you've accidentally implemented two separate city-selection loops, and the second one is causing the confusion (plus it has an undefined variable bug).

What's Going Wrong

  1. Your first while loop works perfectly: it lets users pick a city via 1/2/3, assigns the correct city variable, and breaks out of the loop.
  2. But immediately after that, another while loop starts asking users to type the city name (Chicago/New York/Washington). This is completely redundant, and worse—this loop references undefined variables like chicago (you defined uppercase constants CHICAGO, NYC, WASHINGTON instead).
  3. When you input 1 for the first city selection, the program moves to this second loop. Since 1 isn't a valid city name, it triggers an error, making you think your first choice was invalid.

Fixed Code for get_filters()

Here's the cleaned-up version of the function, removing the redundant city loop and fixing small inconsistencies:

def get_filters():
    """
    Asks user to specify a city, month, and day to analyze.
    Returns:
        (str) city - name of the city to analyze
        (int) month - number of the month to filter by, or None for no filter
        (int) day - index of the day of week to filter by, or None for no filter
    """
    invalid_choice = "Invalid choice..."
    ALL = 'all'
    print('Hello! Let\'s explore some US bikeshare data!')
    
    # Get user input for city (1=Chicago, 2=New York City, 3=Washington)
    while True:
        print("Please enter the number of which city you would like to explore: ")
        print("1 Chicago, 2 New York City, 3 Washington")
        location = input(">")
        if location == '1':
            city = CHICAGO
            print("You chose Chicago")
            break
        elif location == '2':
            city = NYC
            print("You chose New York City")
            break
        elif location == '3':
            city = WASHINGTON
            print("You chose Washington")
            break
        else:
            print(invalid_choice)
    
    # Get user input for month (1=January ... 6=June, or "all")
    while True:
        print(f"Please enter the number of the (start) month you would like to explore or \"{ALL}\": ")
        print("1 January ... 6 June")
        m = input(">")
        if m == ALL:
            month = None
            break
        try:
            month = int(m)
        except ValueError:
            print(invalid_choice)
            continue
        else:
            if 1 <= month <= 6:
                print(f"You chose {MONTHS_OF_YEAR[month-1]}")
                break
            elif month <= 12:
                print("Only January to June are in this dataset")
                print(invalid_choice)
                continue
            else:
                print(invalid_choice)
                continue
    
    # Get user input for day of week (1=Monday ...7=Sunday, or "all")
    while True:
        print(f"Please enter the number of the (start) day of the week that you would like to explore or \"{ALL}\": ")
        print("1 Monday ... 7 Sunday")
        d = input("> ")
        if d == ALL:
            day = None
            break
        try:
            day = int(d)
        except ValueError:
            print(invalid_choice)
            continue
        else:
            if 1 <= day <=7:
                day -= 1
                print(f"You chose {DAYS_OF_WEEK[day]}")
                break
            else:
                print(invalid_choice)
                continue
    
    print("-"*40)
    return city, month, day

Key Fixes Made

  • Removed the redundant second city-selection loop entirely
  • Fixed the input prompt from &gt; to > so users see a normal > character when entering input
  • Used f-strings for cleaner string formatting (optional but improves readability)
  • Added a clear divider (print("-"*40)) since your original code referenced print_divider() which wasn't defined (replace this with your actual divider function if you have one)

How to Test

Run the modified code, input 1 when asked for the city—you'll see "You chose Chicago" and the program will proceed to the month selection step without any "Invalid choice..." errors.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:23:21