简体   繁体   English

python中的输出未达到预期

[英]Output is not getting as expected in python

Not getting an expected output as compared to actual output. 与实际输出相比没有得到预期的输出。 Although the counter here has been placed outside the loop. 尽管此处的计数器已放置在循环外部。 Here Marks are printed every after the Righ t Wrong. 在“错误”之后,每次都会打印标记。 I want that it should get printed only once that is at the end. 我希望只在最后一次打印一次。 I have written it already outside the if loop 我已经在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

Actual Output: 实际输出:

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

Expected: 预期:

Right 
Right 
Wrong 
Right
Right 
Marks: 4

The last line: 最后一行:

print "Marks:", counter

is inside the for loop, so just correct it, and it should work: 在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

将此行移出循环范围。

print "Marks:", counter

Write the last print statement outside the for loop. 在for循环外编写最后一个打印语句。 Something like this: 像这样:

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

I tested this and it works correctly: 我测试了一下,它可以正常工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM