Roshan
Roshan

Reputation: 3

How do I input boolean Truth values to a variable?

#executing the XOR gate

print('Enter a truth value for each of the variables and get A XOR B.')
print('Enter A')
a = input()
print('Enter B')
b = input()
print('The XOR gate value is:')
print(((a and (not b)) or ((not a) and b)))

So it's pretty obvious that I'm trying to input Boolean key words True and False into variables a and b to get the output of an XOR gate.

The issue here is that the input function is evaluating the True or False input to be a string instead of a Boolean registered word and the program is always returning False as the answer.

I would like to know if there is a way to input and store Boolean values in variables.

Upvotes: 0

Views: 1747

Answers (3)

DeepSpace
DeepSpace

Reputation: 81594

Any non-empty string evaluates to the boolean True. Even bool('False') is True.

You can use a = True if input().lower() in ('t', 'true') else False
(or the shorter form, a = input().lower() in ('t', 'true'))
and same for b.

Of course this does not have to be in a single line, and you can decide what logic is used to decide which strings are allowed/interpreted as True or False.

Do not go the eval way.

ast.literal_eval may be used, but will accept any literal (int, list, string).

Upvotes: 2

Ajinkya Taranekar
Ajinkya Taranekar

Reputation: 330

just compare the values of input with True if, its true return a = True else a =False. By default input() takes a string as input, so, we can convert it like this.

#executing the XOR gate

print('Enter a truth value for each of the variables and get A XOR B.')

print('Enter A')

a = True if input() == 'True' else False

print('Enter B')

b = True if input() == 'True' else False

print('The XOR gate value is:')

print(((a and (not b)) or ((not a) and b)))

So, just write True or False for inputs.

Upvotes: 0

pts
pts

Reputation: 87221

a = input()[0].lower() in '1ty'

This accepts 1, true and yes (among others) in a case insensitive way as True.

Upvotes: 0

Related Questions