Python If 语句在测试 1 到 10 之间的数字时不起作用

标签 python django

尝试让 if 语句发挥作用。

from __future__ import unicode_literals

from django.shortcuts import render

def index(request):
   return render(request, 'landscapes/index.html')

def landscape(request, id):
    print id
    if id>=1 and id<=10:
        print 'true'
        landscape = 'https://wildwithgrace.files.wordpress.com/2010/12/snowy-landscape.jpg'
    context = {
        'landscape': landscape
    }
    return render(request, 'landscapes/landscape.html', context)

即使数字大于 1 且小于 10,也只会在/# 处返回 UnboundLocalError。

url.py:

from django.conf.urls import url, include
from . import views

urlpatterns = [
    url(r'^$', views.index),
    url(r'^(?P<id>\d+)$', views.landscape),
]

最佳答案

def landscape(request, id):
    print id
    if int(id) >= 1 and int(id) <= 10:
        print 'true'
        landscape = 'https://wildwithgrace.files.wordpress.com/2010/12/snowy-landscape.jpg'
        context = {
            'landscape': landscape
        }
    else:
        context = {}
    return render(request, 'landscapes/landscape.html', context)

试试这个

关于Python If 语句在测试 1 到 10 之间的数字时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45251478/

相关文章:

javascript - 像在 Python 中那样比较 Javascript 中的两个列表的最佳方法是什么?

python - Saleor 是否支持小数订单行数量?

css - django 模板切片 css 行为

python - 正则表达式捕捉 2 个引号之间的部分

python - 按连续的公共(public)元素拆分列表

python - 如何在同一文件中编写脚本/库?

Django 管理更改列表过滤/链接到其他模型

python - 加速 CSV 更新/导入 Django 模型

python - django如何批量发送数据

django - 将数据从一个表链接到另一个表,并通过中间表连接