0

I have an issue with my hangman maths game where the back end question algorithm says an answer is wrong when it is actually correct. This only seems to happen with negative numbers being multiplied by a positive number. E.g. -4*5 = -20. I have taken my basic algorithm from when i started creating the program to see if it still existed then. And the issue was there. How may I resolve this issue? Here is sample code of the algorithm with all of my GUI code removed:

from tkinter import *
from tkinter import ttk
import random

#says negatives are incorrect when multiplying a negitive by  a positive
OP = ['*', '+', '-', '/']
count = 0


range1 = input("Range 1:" )
range1int = int(range1)


range2 = input("Range 2 (must be positive):" )
range2int = int(range2)

while count is 0:
    operator = random.choice(OP)

    if operator is '/':
        num1 = random.randint(1,range2int)
        num2 = random.randint(1,range2int)
    else:
        num1 = random.randint(range1int,range2int)
        num2 = random.randint(range1int,range2int)

    is_looping = True
    if operator is '/':
        invalid = num1%num2
        while invalid == 0:
            num1 = random.randint(1,range2int)
            num2 = random.randint(1,range2int)
            invalid = num1%num2
            if invalid is 0:
                is_looping = False
                break
    if not is_looping:
        break
    else:
        invalid = 0

    if invalid is 0:


        print("What is ", num1, operator, num2)
        question = eval( str(num1) + operator + str(num2))
        QuestInt = int(question)

        AnsInput = input("Enter Answer (Press Enter When Done):")
        IntAns = int(AnsInput)




        if IntAns is QuestInt:
            print("Correct!")
        else:
            print("Incorrect")

1 Answers1

3

You are using is instead of == several times for comparison. In particular the line if IntAns is QuestInt: is breaking your neck. Replace it with if IntAns == QuestInt: and your code will work as expected:

What is  -3 * 10
Enter Answer (Press Enter When Done):-30
Correct!

In general, the is keyword checks if two objects are the same, while the == operator checks if they are equal. This is a very important difference. I noticed that your code also stops unexpectedly at other places because you use is there. If the question arises, why your code worked before with positive integers, have a look at this answer.

EDIT:

As Mark Dickinson pointed out in the comments:

All your uses of is in your original code should be replaced with ==. There are use-cases for is, notably comparing with singletons like None, True and False, but they're relatively rare.

Thomas Kühn
  • 9,412
  • 3
  • 47
  • 63