Python always returning False in the boolean comparison

this is my code. whatever I input for A and B it always returns false..

def TorF():
    for i in range(10):
        A = input('A: ')
        B = input('B: ')
        print((A and not B) or (B and not A))

TorF()

results:

>>> 
A: True
B: False
False
A: True
B: True
False
A: False
B: True
False

Upvotes: 0

Views: 1231

Answers (1)

Kevin
Kevin

Reputation: 76254

In 3.X, input returns a string, so you aren't actually performing your boolean logic on bools. It's always evaluating as False because not s is False for any non-empty string s; s and False is False for any value of s; and of course False or False is False. Try explicitly converting the type of A and B beforehand.

def TorF():
    for i in range(10):
        A = input('A: ').lower() == "true"
        B = input('B: ').lower() == "true"
        print((A and not B) or (B and not A))

TorF()

Result:

A: True
B: False
True
A: True
B: True
False
A: False
B: True
True

Upvotes: 1

Related Questions