1
str_input = input("Any thing")

if bool(str_input):
    print('Any thing')
else:
    print('''Any thing ''')

Because I am a beginner in Python I don't know how to take an input from the user as a bool. I tried to convert the str to bool but it didn't work.

Robert
  • 7,394
  • 40
  • 45
  • 64
  • Well, `input()` *always* returns a `str`. What values are you expecting your user to enter where some convert to `True` and some convert to `False`? – quamrana Jan 22 '23 at 17:08
  • 3
    Explain more. What do you mean by "it didn't work"? Give us the error(if any) as well, with the full traceback. – Shiv Jan 22 '23 at 17:09
  • Yes, in python input() function always takes string input. – Anurag Verma Jan 22 '23 at 17:10
  • Then read the docs ... especially for the function that you tried here: `bool()`. Depending on the input and its [Truth value](https://en.wikipedia.org/wiki/Truth_value) the resulting boolean value [varies](https://stackoverflow.com/questions/39983695/what-is-truthy-and-falsy-how-is-it-different-from-true-and-false). @KarlKnechtel I agree and voted to close as such duplicate. Will retract my vote, if a question and expectation was added that contradict. – hc_dev Jan 22 '23 at 17:14

1 Answers1

2

To take a boolean input from the user, you can use the input() function to get a string input, and then use the str.lower() method to convert the input to lowercase, and then check if the user entered "true" or "false".

Here is an example of how you can take a boolean input from the user:

str_input = input("Enter a boolean value (True or False): ").lower()
if str_input == "true":
    user_input = True
elif str_input == "false":
    user_input = False
else:
    print("Invalid input. Please enter either 'True' or 'False'.")
Anurag Verma
  • 121
  • 7