正如标题中所述,我想在我的Web2py应用中为0
或None
显示session.counter
而不是session.wrong_counter
。我已经尝试了大约10种不同的方法来做到这一点,但由于某种原因我没有把它弄好。
这是页面Controller
的{{1}}:
score
在def score():
image = db.pic(request.args(0,cast=int)) or redirect(URL('index'))
correct = image.id == session.pic_id
next_game = random.randint(1, 35)
wrong_counter = []
right_counter = []
if correct:
session.counter = (session.counter or 0)+1
right_counter=session.counter
if not correct:
session.wrong_counter = (session.wrong_counter or 0)+1
wrong_counter=session.wrong_counter
return locals()
我有View
和{{=session.counter}}
。在{{=session.wrong_counter}}
期间首次访问的网页score
会显示session
,而另一个会显示1
,具体取决于None
或correct
但是,我希望显示not correct
而不是0
。
我非常感谢一些建议。
答案 0 :(得分:0)
当wrong_counter
为真时,只需将correct
值初始化为0,并且未设置wrong_counter:
if correct:
session.counter = (session.counter or 0)+1
right_counter=session.counter
if not session.wrong_counter:
# This is the first time we have a correct answer
wrong_counter = 0
else:
wrong_counter = (session.wrong_counter or 0)+1
session.wrong_counter = wrong_counter
if not correct:
session.wrong_counter = (session.wrong_counter or 0)+1
wrong_counter=session.wrong_counter
这样,它不会将None
作为默认值,而是为0。
但是,您已将right_counter
和wrong_counter
设置为循环上方的空列表。如果将它们设置为会话变量的值,它将使您的逻辑更容易:
right_counter = session.counter or 0
wrong_counter = session.wrong_counter or 0
if correct:
right_counter = int(right_counter) + 1
if not correct:
wrong_counter = int(wrong_counter) + 1
session.counter = right_counter
session.wrong_counter = wrong_counter