如何从 python 中的用户获取布尔值输入?
How to get a Boolean input from the user in python?
我想得到用户的意见。如果我想要一个字符串作为输入,那么我可以 input("enter your answer")
但是,如果我希望输入为布尔值:仅 True 或 False,我该如何在 python?
中执行此操作
您可以:
- 创建一个单独的方法,要求输入
"True"
或 "False"
之类的字符串,并根据它 return 的内容将该方法用作布尔值:
def trueCheck():
response = input("True or False?")
if response == "True":
return True
if response == "False":
return False
- 或者将来自
_main
的响应传递给方法和 return 一个布尔值:
def trueCheck(response):
if response == "True":
return True
if response == "False":
return False
我想得到用户的意见。如果我想要一个字符串作为输入,那么我可以 input("enter your answer")
但是,如果我希望输入为布尔值:仅 True 或 False,我该如何在 python?
您可以:
- 创建一个单独的方法,要求输入
"True"
或"False"
之类的字符串,并根据它 return 的内容将该方法用作布尔值:
def trueCheck(): response = input("True or False?") if response == "True": return True if response == "False": return False
- 或者将来自
_main
的响应传递给方法和 return 一个布尔值:
def trueCheck(response): if response == "True": return True if response == "False": return False