Skip to main content
 首页 » 编程设计

python之为什么 “else” 行给出无效语法错误

2025年05月04日18tintown

我在使用 Jupyter Notebook 创建代码来预测某些数据时遇到以下错误:

File "<ipython-input-104-f41838a4a887>", line 240 
    else: 
       ^ 
SyntaxError: invalid syntax 

我已经检查了缩进和格式错误,但还没有解决问题。

if dfoutput[1] <= 0.05: 
    # Auto Correlation plot to select p term for the ARIMA model. 
    auto_corr(df) 
    set_p_value() 
 
    # Partial Auto Correlation plot to select q term for the ARIMA model. 
    plot_pacf(df) 
    set_q_value() 
 
    # d value == 0 as no differencing took place. 
    print('\nd value set as 0 as no differencing took place.') 
    d_value = 0 
 
    # Select length of time to forecast over. 
    future_dates(forecast_length) 
 
    # Create the ARIMA model (Use the values of the dataframe to avoid ValueError): 
    model = ARIMA(df.values, order=(p_value, d_value, q_value)) 
    results = model.fit() 
 
    # Option to show summary of the model: 
    model_summary(results) 
 
    # Option to show the residuals: 
    show_residuals(results) 
 
    # FORECASTING THE DATA 
    final_df['forecast'] = results.predict(start=0, end=len(final_df) - 1) 
 
    # Plotting the forecasted values 
    plt.figure(figsize=(12,7)) 
    plt.plot(final_df[column_to_assess], label='real', color='blue') 
    plt.plot(final_df['forecast'].iloc[len(df)-1:], label='forecast', color='red') 
    plt.xlabel('Date') 
    plt.ylabel('Median House Value') 
    plt.title('Median House Prices for ' + column_to_assess + ' (1995 - 2018) & Forecasted Prices (2018 - ' + str(final_df.index[-1].year) + ")") 
    plt.grid() 
    plt.legend() 
 
 
'''THIS IS WHERE THE ERROR ARISES:''' 
else: 
 
    # Perform Error, Trend, Seasonality (ETS) decomposition to check for seasonality: 
    ets_result = seasonal_decompose(df.astype(int), model='multiplicative') 
 
    # Plot the ETS decomposition 
    fig = result.plot() 
    fig.set_size_inches(12,7) 

请您参考如下方法:

具有讽刺意味的是,错误的唯一原因是您的标记文本:'''THIS IS WHERE THE ERROR ARISES:'''。这不是注释而是三引号字符串文字,它将 else 与 if 断开连接。删除它,语法错误就会消失。