在python中输出没有达到预期的效果

时间:2013-12-10 07:39:34

标签: python for-loop

与实际输出相比,未获得预期输出。 虽然这里的计数器已放在循环外。 这里标记在Righ t Wrong之后每次打印。 我希望它只能在最后打印一次。我已经把它写在if循环之外了

resp = {}
ansdb = {}
counter = 0

for i in range(1, 10):
    resp_i = form.getvalue('opt_%d' %i, '0')
    resp[i] = int(resp_i)

print "<br>"


for row in prsnobj.result:
    ansdb[int(row[0])] = int(row[1])

print "<br>"

for i in range(1, len(resp)+1):

    if resp[i] == ansdb[i]:
        print "<br>Right"
        counter += 1

   else:
       print "<br>Wrong"

   print "Marks:", counter

实际输出:

Right Marks: 1
Right Marks: 2
Wrong Marks: 2
Right Marks: 3
Right Marks: 4 

预期:

Right 
Right 
Wrong 
Right
Right 
Marks: 4

4 个答案:

答案 0 :(得分:2)

最后一行:

print "Marks:", counter

在for循环中,所以只需更正它,它应该可以工作:

resp = {}
ansdb = {}
counter = 0

for i in range(1, 10):
    resp_i = form.getvalue('opt_%d' %i, '0')
    resp[i] = int(resp_i)

print "<br>"

for row in prsnobj.result:
    ansdb[int(row[0])] = int(row[1])

print "<br>"

for i in range(1, len(resp)+1):

    if resp[i] == ansdb[i]:
        print "<br>Right"
        counter += 1
    else:
        print "<br>Wrong"

print "Marks:", counter

答案 1 :(得分:1)

将此行移出循环范围。

print "Marks:", counter

答案 2 :(得分:1)

在for循环之外写下最后一个print语句。像这样:

resp = {}
ansdb = {}
counter = 0

for i in range(1, 10):
    resp_i = form.getvalue('opt_%d' %i, '0')
    resp[i] = int(resp_i)

print "<br>"


for row in prsnobj.result:
    ansdb[int(row[0])] = int(row[1])

print "<br>"

for i in range(1, len(resp)+1):

    if resp[i] == ansdb[i]:
        print "<br>Right"
        counter += 1

  else:
       print "<br>Wrong"

print "Marks:", counter

答案 3 :(得分:0)

我对此进行了测试并且工作正常:

resp = {}
ansdb = {}
counter = 0

for i in range(1, 10):
    resp_i = form.getvalue('opt_%d' %i, '0')
    resp[i] = int(resp_i)

print "<br>"


for row in prsnobj.result:
    ansdb[int(row[0])] = int(row[1])

print "<br>"

for i in range(1, len(resp)+1):
    if resp[i] == ansdb[i]:
        print "<br>Right"
        counter += 1
    else:
        print "<br>Wrong"

print "Marks:", counter