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

时间:2017-07-22 06:30:46

标签: 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。

urls.py:

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

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

1 个答案:

答案 0 :(得分:1)

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)

试试这个