{% if guess == rand_num %}
<h1>{{message1}}</h1>
{% elif guess > rand_num %}
<h1>{{message3_a}}</h1>
<h1>{{message3_b}}</h1>
{% elif guess < rand_num %}
<h1>{{message2_a}}</h1>
<h1>{{message2_b}}</h1>
{% endif %}
def easy(request, ):
rand_num = random.choice(lst)
print(rand_num)
attempts = 11
for _ in range(0, 10):
# print(f"You have {attempts} remaining to guess the number.")
# guess = int(input("Make a guess: "))
guess = request.GET.get('guessed_number')
if guess == rand_num:
return render(request, 'easy.html', {'attempts': attempts, "message1": f"You got it! The anshwer was {rand_num}"})
break
elif guess < rand_num:
attempts -= 1
return render(request, 'easy.html', {'attempts': attempts, "message2_a": "Too Low", "message2_b": "Guess again"})
elif guess > rand_num:
attempts -= 1
return render(request, 'easy.html', {'attempts': attempts, "message3_a": "Too High", "message2_b": "Guess again"})
attempts -= 1
return render(request, 'easy.html', {'attempts': attempts, 'guess': guess, 'rand_num': rand_num})
return render(request, 'easy.html')
我正在尝试运行此Django代码,但它不起作用。
您可以在执行比较之前明确检查变量是否存在。
{% if guess is not None and rand_num is not None %}
{% if guess == rand_num %}
<h1>{{ message1 }}</h1>
{% elif guess > rand_num %}
<h1>{{ message3_a }}</h1>
<h1>{{ message3_b }}</h1>
{% elif guess < rand_num %}
<h1>{{ message2_a }}</h1>
<h1>{{ message2_b }}</h1>
{% endif %}
{% else %}
<h1>No guess or random number provided.</h1>
{% endif %}
在线,您可以使用默认过滤器在不存在或不存在的情况下提供默认值
您可能想做更多的事情来验证您的
guessed_number
参数的存在并最终成为int。那么此逻辑的其余部分应该更具气密性。
您可以:确保查询参数首先存在,并且不是非
确保猜测是一个实际的整数
guess = request.GET.get('guessed_number', None)
if not guess:
return HttpResponseBadRequest('You must provide a guess number')
try:
guess_number = int(guess)
except ValueError:
return HttpResponseBadRequest('Guess number must be an integer')
# do the rest of the logic with assurance that "guess" is an int you can use