Python“和”与“或”之间的条件条件差异

时间:2019-07-23 23:58:32

标签: python-3.x if-statement

我希望用户通过说“是”或“否”来决定是否删除所选文件。无论出于何种原因,“是”有效,但“否”则循环返回并决定返回初始if语句

我已经尝试了一些方法,经过一些Google搜索,我似乎找不到适合此问题的响应。我尝试过:

使用str()和不使用str()更改inputText

我已经尝试过在字符串文本上使用引号和撇号。

我尝试更改初始的If语句:

第一:

if inputText != ('yes' or 'no'):

我什至尝试过

第二:

if inputText != 'yes' or inputText != 'no':

第三:

if (inputText != 'yes') or (inputText != 'no'):

我最接近的是第一。出于某种原因,“是”似乎有效,但“否”似乎会循环回到第一个If语句。

有人能指出我正确的方向吗?我想念什么?

inputText = str(input("Are you sure you want to delete file? (yes/no) "))
ctrl = True
while ctrl == True:
    if inputText != ('yes' or 'no'):
        inputText = input('Please type "yes" or "no" ')
    elif inputText == 'yes':
        ##delete
        print("pretend got deleted")
        ctrl = False
    elif inputText == 'no':
        ##shit does not get deleted
        print("pretend doesn't got deleted")
        ctrl = False

我预期的结果将很简单

>> Are you sure you want to delete file? (yes/no) *random text that isn't 'yes' or 'no'*
>> Please type "yes" or "no"

这是我最初的If语句示例中的结果:

>> Are you sure you want to delete file? (yes/no) yes
>> pretend got deleted

这是我的期望:

>> Are you sure you want to delete file (yes/no) no
>> pretend doesn't got deleted

这是我真正得到的

>> Are you sure you want to delete file (yes/no) no
>> Please type "yes" or "no" 

即使我这样做:

>> Are you sure you want to delete file (yes/no) no
>> Please type "yes" or "no" yes
>> pretend got deleted

是我得到的结果

2 个答案:

答案 0 :(得分:2)

问题出在您的第一个if语句中。一旦发现您的输入不是if inputText != ('yes' or 'no'),您的第一个if yes就会解析为true。因此,仅当输入不是true而不是解析为yes的{​​{1}}时,才更改是否解析为no

您的代码如下所示

if inputText != ('yes') and inputText != ('no')

答案 1 :(得分:0)

这里的问题与您的逻辑有关,尤其是这一行:

inputText != ('yes' or 'no')

(“是”或“否”)解析为“是”,因为那是第一个评估为True(在布尔上下文中)的元素

您可能打算这样做:

inputText = str(input("Are you sure you want to delete file? (yes/no) "))
ctrl = True
while ctrl == True:
    if inputText not in ('yes', 'no',):
        inputText = input('Please type "yes" or "no" ')
    elif inputText == 'yes':
        ##delete
        print("pretend got deleted")
        ctrl = False
    elif inputText == 'no':
        ##shit does not get deleted
        print("pretend doesn't got deleted")
        ctrl = False

一些注意事项:

  1. 现在您正在测试inputText是否不在包含'yes'和'no'的值集中(inputText不在('yes','no',)中)

  2. 请注意,该集合中的结尾逗号('yes','no',)(仅在右括号之前)-在Python中,()用于操作顺序以及定义集合-因此,如果您将值保留在parens('yes')=>中,则与'yes'相同。尾部的逗号('yes',)将使Python意识到您要定义一个集合-并以此为准。现在,严格来说,如果不止一个值,则最后不需要逗号,即,('yes','no')可以-但是,这是养成习惯的“最佳实践”始终使用逗号结尾,因此您不会在某个点上意外地尝试定义单个元素集,而最终只得到一个值。

相关问题