0

When I execute this piece of code in python3

x= bool(input())
y= bool(input())
print(x+y)

and when I give input as True True or False False or True False,
I am getting output as 2.
Why is it so? I expected 1 and 0 as the output.

enter image description here

NcXNaV
  • 1,657
  • 4
  • 14
  • 23
  • 1
    A note to those who voted to close this on the basis that it already had an answer: no, it didn't. The OP clearly demonstrated that they already knew `False` and `True` acted like `0` and `1`. Which is what the linked answer is about. But that's not the problem here. _Here_ the confusion was about what `input()` returns, which the linked answer says nothing about. The linked answer is fine on its own - but it's simply irrelevant to _this_ question. – Tim Peters Sep 17 '21 at 16:31

2 Answers2

2

input() in Python 3 returns a string. No data conversions are performed. So the inputs you get are, literally, the strings "True" and/or "False". Then bool() applied to a non-empty string returns True.

>>> bool("True")
True
>>> bool("False")
True
>>> bool("just about anything")
True
>>> bool("") # except an empty string
False

That's why you always get 2 no matter what you enter. Both inputs become True, which equals 1 in a numeric context.

>>> True == 1
True

While people will yell at you if you do this, eval() is the most convenient (although dangerous!) way to evaluate a string as if it were Python code:

>>> eval("True")
True
>>> eval("False")
False

It's dangerous because eval() will evaluate any Python expression, so if you don't trust your input it can trick your program into doing just about anything.

Tim Peters
  • 67,464
  • 13
  • 126
  • 132
1

Input converts your input to string format!
bool(str) gives you True state! And then you're trying to do True + True so you get 2!

x = bool(input()) #--> x= True
y = bool(input()) #--> y= True
print(x+y) #--> True + True = 2
Shayan
  • 5,165
  • 4
  • 16
  • 45
  • It returns 2 even when trying with False and False. That I am confused. – Murali Sankar Sep 17 '21 at 04:16
  • @MuraliSankar It should! It's what python do! And it's so helpful! Example : https://stackoverflow.com/questions/69214701/how-to-count-number-of-increases-decreases-across-a-row-in-a-dataframe – Shayan Sep 17 '21 at 04:18