首页 > 解决方案 > 在 if else 条件下,该程序不会运行 else 中的代码:

问题描述

我将粘贴下面的代码然后解释

from flask import Flask,render_template,url_for,request,redirect
import pandas as pd
import glob
import os
import pickle

# load the model from disk
# here we load random forest model as it gave good results when compared
loaded_model=pickle.load(open('pickle-files/RandomForestRegressor.pkl', 'rb'))
app = Flask(__name__)

@app.route('/',methods = ['POST', 'GET'])
def home():
   if request.method == 'POST':
        year = request.form['value']
        if len(year) == 0:
            return render_template('home.html')
        elif year != 2013 or year != 2014 or year != 2015 or year != 2016 or year != 2017 or year != 2018:
            return render_template('home.html', num = 'You did not enter the above year correctly')
        else:
            df=pd.read_csv('Data/Real-Data/real_{}.csv'.format(year))
            my_prediction=loaded_model.predict(df.iloc[:,:-1].values)
            my_prediction=my_prediction.tolist()
            return render_template('home.html', prediction = my_prediction)
   else:
       return render_template('home.html')




if __name__ == '__main__':
    app.run(debug=True)

当我在主机上运行应用程序时,一切正常,除了程序没有触及 else 块中的代码。

假设年份 = 2013,它应该进入 else 块进行预测工作,并在网页上返回其结果。

我将在此处粘贴 Web 应用程序的屏幕截图 注意:请忽略图片中的 barbrothers.com

我希望预测显示如下截图

相反,我在下面的截图中得到这样的在此处输入图像描述

我尝试了许多不同的方法来正确地工作,但它并没有预测我想要的值,即 2013 2014 2015 2016 2017 2018 2013-2018。

我希望我的问题得到理解,请告诉我。

标签: pythonif-statementflask

解决方案


问题出在这一行:

elif year != 2013 or year != 2014 or year != 2015 or year != 2016 or year != 2017 or year != 2018:

True无论年份如何,这种表达方式将永远是。True(如果年份不是 2013 年,True第一部分orTrue

取而代之的是,我认为您想要的逻辑是:

elif not year in ('2013', '2014', '2015', '2016', '2017', '2018'):

另请注意,我正在与year字符串值进行比较,因为它显然是一个字符串。


推荐阅读