python - 在 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。
我希望我的问题得到理解,请告诉我。
解决方案
问题出在这一行:
elif year != 2013 or year != 2014 or year != 2015 or year != 2016 or year != 2017 or year != 2018:
True
无论年份如何,这种表达方式将永远是。True
(如果年份不是 2013 年,True
第一部分or
是True
取而代之的是,我认为您想要的逻辑是:
elif not year in ('2013', '2014', '2015', '2016', '2017', '2018'):
另请注意,我正在与year
字符串值进行比较,因为它显然是一个字符串。
推荐阅读
- cmd - vbscript start .exe 没有命令提示符优先
- java - 为什么迭代器会为整数链表抛出异常
- javascript - 我应该如何格式化数据
- html - 如何使无序列表居中
- python - 发生异常:OSError 无法加载共享对象文件:llvmlite.dll
- apache-kafka - apache kafka vs redis 作为生产中的消息代理
- maven - talend 7.3.1 如何将 jdbc 或 sqlserver 支持添加到路由?
- mysql - 数据库连接适用于 Kubernetes 集群,但使用 Skaffold 开发失败
- r - ggplot, geom_line() 用于数据集中字符串(分类)变量的每个值的平均出现次数
- python - Django rest框架:嵌套序列化程序为空时排除结果