Amy
Amy

Reputation: 75

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

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

Upvotes: 0

Views: 101

Answers (4)

nur
nur

Reputation: 161

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

Upvotes: 0

Rahul Tanwani
Rahul Tanwani

Reputation: 441

Write the last print statement outside the for loop. 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

Upvotes: 1

mclafee
mclafee

Reputation: 1426

Move this line out of loop scope.

print "Marks:", counter

Upvotes: 1

ahmet2106
ahmet2106

Reputation: 5007

The last line:

print "Marks:", counter

is inside the for loop, so just correct it, and it should work:

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

Upvotes: 2

Related Questions