Bob dylan
Bob dylan

Reputation: 9

Python quiz code, not printing correct and incorrect when answered

can someone help me with this code as it is not producing 'correct' or 'incorrect' when the questions are answered. What im thinking someone will do is when each answer is produced and answered if they got it correct it will say correct but if they have gotten it wrong it will say incorrect. At the moment it just says incorrect when you finish all ten questions.

num1=0
num2=0
numofq=0

while numofq <10:
    import random
    num1 = random.randint(1, 10)
    num2 = random.randint(1, 10)
    correctAns = num1 * num2
    question = str(num1) + "x" + str(num2)
    ans = input(question)
    numofq=numofq+1
if ans == correctAns:
   print ("Correct")
else:
   print ("Incorrect")

Upvotes: 1

Views: 1597

Answers (2)

Haresh Shyara
Haresh Shyara

Reputation: 1886

import random
num1 = 0
num2 = 0
numofq = 0
correct = 0
wrong = 0
while numofq < 10:
    num1 = random.randint(1, 10)
    num2 = random.randint(1, 10)
    correctAns = num1 * num2
    question = str(num1) + "x" + str(num2)
    ans = input(question)
    if correctAns == ans:
        print 'Correct'
        correct += 1
    else:
        wrong += 1
        print 'Incorrect'
    numofq = numofq + 1
print 'Correct :', correct, 'Incorrect :', wrong

Upvotes: 0

Anshul Goyal
Anshul Goyal

Reputation: 76847

Your if-else blocks are not indented right, they should be part of the while loop:

num1=0
num2=0
numofq=0

while numofq <10:
    import random
    num1 = random.randint(1, 10)
    num2 = random.randint(1, 10)
    correctAns = num1 * num2
    question = str(num1) + "x" + str(num2)
    ans = input(question)
    numofq=numofq+1
    if ans == correctAns:
       print ("Correct")
    else:
       print ("Incorrect")

But while we are at it, you can improvise your code by

  1. using better variable names
  2. .format for string formatting
  3. putting the import at the top
  4. proper indentation with line breaks

so that the program now looks like

import random

num1 = num2 = 0
questions_asked = 0

while questions_asked <10:
    num1 = random.randint(1, 10)
    num2 = random.randint(1, 10)
    answer = num1 * num2
    question = "{} x {}: ".format(num1, num2)
    user_answer = int(input(question))
    print("Correct" if user_answer == answer else "Incorrect")
    questions_asked += 1

This outputs:

6 x 4: 24
Correct
2 x 7: 14
Correct
3 x 4: 12
Correct
...

Upvotes: 4

Related Questions