简体   繁体   English

如何使用户输入更改布尔值?

[英]How do I make a user input change a Boolean value?

I am trying to make a simple little program using Python 3.7.4. 我正在尝试使用Python 3.7.4编写一个简单的小程序。 I was wondering if it is possible (If so, how?) to change the Boolean value of a variable from a user input. 我想知道是否有可能(如果可以,如何?)从用户输入更改变量的布尔值。

As you can see in the attached code, I have tried putting the append in quotations. 如您在所附代码中所见,我尝试将附加内容放在引号中。 I also tried no quotations. 我也没有报价。

    is_male = []
    is_female = []
    is_tall = []
    is_short = []

    ans_male = bool(input("Are you a male? (True or False): "))
    if ans_male == "True":
        is_male.append("True")
    if ans_male == "False":
        is_male.append("False")
    ans_female = bool(input("Are you a female? (True or False): "))
    if ans_female == "True":
        is_female.append("True")
    if ans_female == "False":
        is_female.append("False")
    ans_tall = bool(input("Are you tall? (True or False): "))
    if ans_tall == "True":
        is_tall.append("True")
    if ans_tall == "False":
        is_tall.append("False")
    ans_short = bool(input("Are you short? (True or False): "))
    if ans_short == "True":
        is_short.append("True")
    if ans_short == "False":
        is_short.append("False")

I expect the is_male, is_tall, etc. variable's value to change to True or False according to the input. 我期望is_male,is_tall等变量的值根据输入更改为True或False。

You are getting a few things wrong. 您弄错了几件事。

1) When transforming a string into a boolean, python always returns True unless the string is empty ( "" ). 1)将字符串转换为布尔值时,除非字符串为空( "" ),否则python始终返回True。 So it doesn't matter if the string is "True" or "False" , it will always become True when you do bool(str) . 因此,不管字符串是"True"还是"False" ,当您执行bool(str)时,它将始终变为True

2) In your if statements, you're comparing a boolean (the ans_male variable) with a string ( "True" ). 2)在if语句中,您正在将布尔值( ans_male变量)与字符串( "True" )进行比较。 If you want to work with booleans, you should write only True or False , without the quotation marks. 如果要使用布尔值,则应只写TrueFalse ,不要带引号。

In your case, as you're reading a value from the input() , it is much easier to just leave it as a string and compare it with "True" and "False" instead. 在您的情况下,当您从input()读取值时,将其保留为字符串并将其与"True""False"进行比较会容易得多。 So you could do as follow: 因此,您可以执行以下操作:

ans_male = input("Are you a male? (True or False): ")
if ans_male == "True": # Check if string is equal to "True"
    is_male.append(True) # Appends the boolean value True to the list.

Here ans_male will have true value even if your input is false. 即使您输入的内容为假,ans_male也将为真值。 You can't convert string to bool value like this. 您不能像这样将字符串转换为bool值。 Better create a function to convert string into bool values as following. 更好地创建一个将字符串转换为bool值的函数,如下所示。

def stringToBool(ans_male):
    if ans_male == 'True':
       return True
    else if ans_male == 'False'
       return False
    else:
       raise ValueError

Booleans don't have quotation marks, those are only for strings. 布尔型没有引号,仅用于字符串。 The following is 1/4 of your code with this change applied: 以下是应用此更改的代码的1/4:

    is_male = []

    ans_male = bool(input("Are you a male? (True or False): "))
    if ans_male == "True":
        is_male.append(True)
    if ans_male == "False":
        is_male.append(False)

Note: ans_male == "True" has the boolean in string format because values assigned using input() are always strings. 注意: ans_male ==“ True”具有字符串格式的布尔值,因为使用input()分配的值始终是字符串。

Because of this , you may want to use the following instead (because follow): 因此 ,您可能想要使用以下内容(因为遵循):

is_male = []
    is_female = []
    is_tall = []
    is_short = []

    ans_male = bool(input("Are you a male? (Yes or No): "))
    if ans_male == "Yes":
        is_male.append(True)
    if ans_male == "No":
        is_male.append(False)
    ans_female = bool(input("Are you a male? (Yes or No): "))
    if ans_female == "Yes":
        is_female.append(True)
    if ans_female == "No":
        is_female.append(False)
    ans_tall = bool(input("Are you a male? (Yes or No): "))
    if ans_tall == "Yes":
        is_tall.append(True)
    if ans_tall == "No":
        is_tall.append(False)
    ans_short = bool(input("Are you a male? (Yes or No): "))
    if ans_short == "Yes":
        is_short.append(True)
    if ans_short == "No":
        is_short.append(False)

is_male.append(True) should work. is_male.append(True)应该可以工作。 I tested it and it works for me on v3.7.4. 我测试了它,并在v3.7.4上为我工作。

Consider this code. 考虑下面的代码。 You have a list of questions you want to ask, paired with the associated property (is_male, etc.). 您具有要询问的问题列表,并与关联的属性(is_male等)配对。 You have a dictionary that maps user input to a boolean. 您有一本将用户输入映射到布尔值的字典。 For each question, you print the current question and wait for the user to enter something. 对于每个问题,您都将打印当前问题并等待用户输入内容。 If they enter something invalid (something other than "True" or "False"), the while-loop will keep asking the same question until the user answers satisfactorily. 如果他们输入了无效的内容(“ True”或“ False”以外的东西),则while循环将继续询问相同的问题,直到用户满意地回答为止。 When the user has answered all questions we print the results. 用户回答完所有问题后,我们将打印结果。

questions = [
    ("Are you male?", "is_male"),
    ("Are you tall?", "is_tall")
]

input_to_bool = {
    "True": True,
    "False": False
}

user = {}

for question, key in questions:
    while True:
        user_input = input(f"{question}: ")
        if user_input in input_to_bool:
            user.update({key: input_to_bool[user_input]})
            break

for key, value in user.items():
    print(f"{key}: {value}")

Output: 输出:

Are you male?: True
Are you tall?: False
is_male: True
is_tall: False

Your code transform the user input to bool. 您的代码将用户输入转换为bool。

ans_male = bool(input("Are you a male? (True or False): "))

So any input will be True and no input will be False. 因此,任何输入将为True,而没有输入将为False。

How about doing something like: 如何做类似的事情:

is_male = []
ans_male = input('Are you a male? (Y or N): ')

if ans_male.upper() == 'Y':
    is_male.append(True)

elif ans_male.upper() == 'N':
    is_male.append(False)

else:
    print('Please choose Y or N')
    pass

Put your less affords and time with this code : 使用此代码节省一些时间:

    is_male = []
    is_female = []
    is_tall = []
    is_short = []

    que = "Are you {} (Yes/No) : "

    ans_male = True if input(que.format("a male?")).lower()=='yes' else False
    is_male.append(str(ans_male))
    #if you want to append list with 'True'/'False' (type->str)

    ans_female = True if input(que.format("a female?")).lower()=='yes' else False
    is_female.append(ans_female)
    #if you want to append list with True/False (type -> bool)

    ans_tall = True if input(que.format("tall?")).lower()=='yes' else False
    is_tall.append(ans_tall)

    ans_short = True if input(que.format("short?")).lower()=='yes' else False
    is_short.append(ans_short)

It is the same code that you post in the question with efficient solution. 它是您在问题中使用有效解决方案发布的相同代码。

And yes an answer should be Yes/No because True/False sometime looks weird for this type of questions. 是的回答应该Yes/No ,因为True/False有时看起来怪怪这种类型的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将值数组输入到 dataframe 的列中,其中值为 null 并创建一个新的 boolean 列来标记它? - How do I input an array of values into a column of a dataframe where the value is null and make a new boolean column that marks this? 如何从输入中获取布尔值? - How do I get a boolean value from an input? 如何用用户输入制作矩形? - How do I make a rectangle with user input? 如何更改给定 Boolean(在 Python 中)的列中的值? - How do I change the value in a column given a Boolean (in Python)? 如何从用户那里获取输入布尔值? - How to get a input a boolean value from the user? 如何使用户输入不是字符串或输入而是运算符? - How do I make user input not a string or input but an operator? 在Python中,如果用户输入错误的值,如何使输入验证继续循环 - In Python, How do I make my input validation keep on looping if the user enters an incorrect value 我无法从用户输入中获得 False boolean 值 - I am not able to get False boolean value from user input 如何根据用户输入设置 boolean 条件以清除或关闭海龟程序? - How do I set a boolean condition to clear or close the turtle program based on user input? 如果用户输入不是目录,如何将目录设为默认值 - if user input is not a directory, how can I make the directory a default value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM