John Smith
John Smith

Reputation: 3

How to convert input as boolean type and use it in if and else statement?

x = bool(input ( "Write True or False\n"))

if  x is True :
  print("its true")
elif x is False :
    print ("its false")

when I write True or False I always get "its true". i want the program to say "its false" when i type False.

Upvotes: 0

Views: 2123

Answers (2)

rlms
rlms

Reputation: 11060

I'd just compare the strings:

x = input("Write True or False\n")

if x == "True":
  print("its true")
elif x == "False":
    print ("its false")
else:
    print("don't know what that is") 

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 117856

You'll have a problem with converting to bool because technically any non-empty string will evaluate to True

>>> bool('True')
True
>>> bool('False')
True
>>> bool('')
False

You can use ast.literal_eval though

>>> from ast import literal_eval
>>> literal_eval('True')
True
>>> literal_eval('False')
False

Otherwise you'll have to compare the actual strings themselves

x = input("Write True or False\n")

if x in ('True', 'true'):
  print("its true")
elif x in ('False', 'false'):
    print ("its false")
else:
    print("don't know what that is")  

Upvotes: 1

Related Questions