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

共享单车数据分析Python代码选城市后卡顿问题修复请求

问题分析与修复方案

程序冻结的核心原因

你的get_filters()函数里,城市、月份、日期的循环逻辑完全错误,导致输入正确值时触发无限循环,程序卡死:

  • 以城市选择为例,当前代码用while True包裹判断,但仅在输入错误时重新输入一次就break,完全没处理「输入正确时退出循环」的逻辑。如果用户第一次输入正确城市名,if city not in CITY_DATA.keys()不成立,循环会一直运行,程序直接冻结。

附带的代码错误

除了循环逻辑,还有几处拼写和语法错误会导致功能异常:

  • 月份列表里的'faburay'是拼写错误,应为'february'
  • 星期列表存在空格和拼写错误:' sunday'(开头多空格)、'tusday'→'tuesday'、'wedensday'→'wednesday'、'thrusday'→'thursday'
  • 打印语句写错:prtint应为print

修复后的完整代码

import time
import pandas as pd
import numpy as np

CITY_DATA = { 'chicago': 'chicago.csv',
              'new york city': 'new_york_city.csv',
              'washington': 'washington.csv' }

def get_filters():
    """
    Asks user to specify a city, month, and day to analyze.

    Returns:
        (str) city - name of the city to analyze
        (str) month - name of the month to filter by, or "all" to apply no month filter
        (str) day - name of the day of week to filter by, or "all" to apply no day filter
    """
    print('Hello! Let\'s explore some US bikeshare data!')
    # 获取城市输入,循环处理无效输入
    city = input("please choose a city from (chicago , new york city , washington): ").lower()
    while city not in CITY_DATA.keys():
        print("invalid city name please try again: ")
        city = input("please choose a city from (chicago , new york city , washington): ").lower()
    
    # 获取月份输入,循环处理无效输入
    month = input(" please choose and type a full month name or type all: ").lower()
    months = ['january' , 'february' , 'march' , 'april' , 'may' , 'june' , 'all' ]
    while month not in months:
        print("invalid month name please try again")
        month = input(" please choose and type a full month name or type all: ").lower()
    
    # 获取星期输入,循环处理无效输入
    day = input("please add a week day name or type all: ").lower()
    days = ['saturday', 'sunday', 'monday' , 'tuesday', 'wednesday','thursday','friday','all']
    while day not in days:
        print('invalid week day name please try again')
        day = input("please add a week day name or type all: ").lower()

    print('-'*40)
    return city, month, day

关键修改说明

  1. 循环逻辑修正:将while True改为while 输入值不在有效列表中,这样只要输入正确就自动退出循环,输入错误则持续提示重新输入。
  2. 拼写错误修正:修复了月份、星期的拼写错误,去除星期列表里的多余空格。
  3. 语法错误修正:把prtint改为正确的print。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 18:05:16