我有以下代碼。它工作正常,但當players
列表長度變爲0時,我的網頁變空白,並且這個IndexError: list index out of range
錯誤出現在我的終端(服務器)中。當players
列表變空時,我想要一種方法將服務器重定向到self.redirect('/')
。IndexError:列表索引超出範圍| webapp2
def choose_random_player(list):
return random.choice(list)
class GuessPlayer(Handler):
players = ['sanchez', 'welbeck', 'giroud', 'ozil', 'ramsey']
random_player = choose_random_player(players)
score = 0
def get(self):
self.render("guessplayer.html",
random_player=GuessPlayer.random_player,
score=GuessPlayer.score)
def post(self):
user_answer = self.request.get("player-name")
if user_answer == GuessPlayer.random_player:
GuessPlayer.score += 1
GuessPlayer.players.remove(GuessPlayer.random_player)
GuessPlayer.random_player = choose_random_player(GuessPlayer.players)
self.render("guessplayer.html",
random_player=GuessPlayer.random_player,
score=GuessPlayer.score)
else:
self.render("guessplayer.html",
random_player=GuessPlayer.random_player,
score=GuessPlayer.score)
HTML表單:
{% extends 'base.html' %}
{% block content %}
<div class="row">
<div class="col-md-12 text-center">
<h4>Enter The Player Name</h4>
<div class="thumbnail">
<div class="score">Score: {{score}}</div>
<img src="../images/{{random_player}}.jpg" alt="...">
<form method="post">
<input type="text" name="player-name">
<br><br>
<input type="submit" class="btn btn-primary">
</form>
</div>
</div>
</div>
{% endblock %}
請加上'choose_random_player'的定義 –