how to get a boolean value from the user, if its not a boolean value the loop runs until it gets a boolean value(True/false)
Asked
Active
Viewed 297 times
-1
-
It really depends on how you interpret the input. A user may enter `y`, `yes`, or anything else and then you use conditionals `if user_input == 'yes': val = True` – NotAName Jul 06 '22 at 05:48
-
Does this answer your question? [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – SiHa Jul 06 '22 at 06:09
4 Answers
1
If you want the user to only input True
or False
Then Use this...
while True:
user_in = input("Write True OR False:> ")
if user_in in ['True','False']: # OR ['True','False','true','false']
print("User input bool values.")
break
else:
print("Incorrect Type, Try Again.")

codester_09
- 5,622
- 2
- 5
- 27
0
You'd read a value from the user as a string, and then compare it to values you consider true or false.
If you try bool(input())
the only thing that will be False
is empty input.
Tip: if you're looking for a particular value, like true
from your user, you may want to convert to lowercase to make case-insensitive checks easier.
if input().lower() == 'true':
...
else:
...
If you wish to accept only 'true'
or 'false'
I suggest creating a function to do that.
def read_bool(prompt='', err_msg=None, true='true', false='false', case_insensitive=True):
while True:
val = input(prompt)
if case_insensitive:
val = val.lower()
true = true.lower()
false = false.lower()
if val == true:
return True
elif val == false:
return False
elif err_msg:
print(err_msg)

Chris
- 26,361
- 5
- 21
- 42
0
You can just check if the value submitted by the user equals to True or False
val == 'True'
val == 'False'
This is string comparison but the result of the comparison is a boolean value.

M B
- 2,700
- 2
- 15
- 20
-1
You can check if the input is True
, true
or False
, false
by use the lower method
Here is the code:
close = False
while not close:
# Your code here
if input().lower() in ["true", "false"]:
close = True

John
- 21
- 3
-
1How would you know what the input was when the *while* loop terminates? – DarkKnight Jul 06 '22 at 05:58