在python中,“!=”可以与“and”、“or”一起使用吗?

2024-04-29 16:05:28 发布

您现在位置:Python中文网/ 问答频道 /正文

result = {}
question = '你叫什么名字? '  #What is your name
question_2 = '如果你能去世界上的任何一个地方度假,你想去哪? '  #If you could go to any place in the world for vacation, where would you like to go?
question_3 = '你愿意让你旁边的人也来参加这个调查吗? (yes/ no) '  #Would you like to let people next to you participate in this survey?
while True:
    name = input(question)
    place = input(question_2)
    result[name] = place                                  #除了yes或者no不允许输入其他字符
    while True:                                           #No other characters are allowed except "yes" or "no"
        opinion = input(question_3)
        if opinion.lower() != 'yes' or 'no':
            print('请重新输入')   #please enter again
        else:
            break
    if opinion == 'no':
        break

无论你在跑步后输入什么,你都不能跳出循环

if opinion.lower() not in ('yes','no'):

这很正常,但我还是很好奇为什么会出问题

初学者,谢谢


Tags: tononameinyougoinputif
2条回答
考虑这条线:

if opinion.lower() != 'yes' or 'no':

这就是表达式的求值方式(根据优先顺序):

if (opinion.lower() != 'yes') or ('no'):

'no'总是被评估为True此外,它应该是option而不是'yes''no'(而不是'or')。把它改为:

if opinion.lower() != 'yes' and opinion.lower() != 'no':

不久之后

if opinion.lower() not in ('yes', 'no'):

这会解决你的问题

result = {}
question = "What is your name"
question_2 = "If you could go to any place in the world for vacation, where would you like to go?"
question_3 = "Would you like to let people next to you participate in this survey?"
while True:
    name = input(question)
    place = input(question_2)
    result[name] = place                                  #除了yes或者no不允许输入其他字符
    while True:                                           #No other characters are allowed except "yes" or "no"
        opinion = input(question_3)
        if opinion.lower() not in ('yes','no'):
            print('please enter again')
        else:
            break
    if opinion == 'no':
        break

你可以用一个元组来解决你的问题,这是第一件事

现在您想知道的是为什么以下代码不起作用:

x != "yes" or "no"

按照优先顺序回忆一下!=具有比或更高的优先级,因此x!=首先计算“是”,然后用“否”对其进行or运算,为了解决这个问题,在or语句周围添加括号:

x != ("yes" or "no")

我会帮你的

相关问题 更多 >