why does my math quiz always print incorrect when

2019-03-07 03:09发布

问题:

okay so im writing a code that randomly generates questions and lets the user answer but my problem is that even if the user gets the answer right it will always print incorrect

print ("what is your username")
name = input () .title()
print (name, "welcome")
import random
score=0
question=0
for i in range(10):
    ops = ["+", "-", "*"]
    num1 = random.randint (0,10)
    num2 = random.randint (0,10)
    oparator = random.choice(ops)
    Q=(str(num1)+(oparator)+(str(num2)))
    print (Q)
    guess = input()
    guess = int(guess)
    if oparator =='+':
        answer = (str(num1+num2))

    elif oparator =='-':
        answer = (str(num1-num2))

    else:
        oparator =='*'
        answer = (str(num1*num2))

    if guess == (Q):  
        print ("correct")
        score + 1

    else:
        print ("incorrect")   

I honestly don't understand what is wrong. any help would be greatly thanked p.s I know my codes a mess

回答1:

You need to compare guess with answer.

    print ("what is your username")
    name = input().title()
    print (name, "welcome")
    import random
    score=0
    question=0
    for i in range(10):
        ops = ["+", "-", "*"]
        num1 = random.randint (0,10)
        num2 = random.randint (0,10)
        oparator = random.choice(ops)
        Q=(str(num1)+(oparator)+(str(num2)))
        print (Q)
        guess = input()
        guess = int(guess)
        if oparator =='+':
            answer = int(str(num1+num2)) # Convert to int

        elif oparator =='-':
            answer = int(str(num1-num2))

        else:
            oparator =='*'
            answer = int(str(num1*num2))

        if guess == answer:  # Compare user's answer with actual answer
            print ("correct")
            score = score + 1 # Update the score

        else:
            print ("incorrect") 


标签: python random