为什么使用“OR"检查多个值的变量只检查第一个值? [英] Why does checking a variable against multiple values with `OR` only check the first value?

查看:47
本文介绍了为什么使用“OR"检查多个值的变量只检查第一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查一个变量是否有多个值之一.我很困惑为什么 or 在这种情况下不起作用.我正在学习给出示例 if (a or b): 的教程,但是当我尝试这样做时,它只根据第一个值检查变量.我的支票有什么问题?

name = raw_input('请输入您的姓名:')如果 len(name) <5:打印您的姓名少于 5 个字符"elif len(name) == 5:打印你的名字正好有 5 个字符"如果名称==(杰西"或杰西"):打印嘿杰西!"别的:打印您的姓名超过 5 个字符"

解决方案

("Jesse" 或 "jesse")

上述表达式测试 "Jesse" 的计算结果是否为 True.如果是,则表达式将返回它;否则,它将返回 "jesse".表达式相当于写:

"Jesse" if "Jesse" else "jesse"

因为 "Jesse" 是一个非空字符串,它会总是评估为 True 并因此返回:

<预><代码>>>>bool("Jesse") # 非空字符串在 Python 中求值为 True真的>>>bool("") # 空字符串的计算结果为 False错误的>>>>>>(杰西"或杰西")'杰西'>>>("或杰西")'杰西'>>>

这意味着表达式:

name == ("Jesse" 或 "jesse")

基本上相当于写这个:

name == "Jesse"

<小时>

为了解决您的问题,您可以使用 in 运算符:

# 测试是否可以在元组中找到name的值("Jesse", "jesse")如果名字在 ("Jesse", "jesse"):

或者,您可以使用 name 的值小写>str.lower 然后直接和 "jesse" 对比:

# 这也将处理诸如JeSSe"、jESSE"、JESSE"等输入.如果 name.lower() == "jesse":

I want to check if a variable has one of multiple values. I'm confused about why or doesn't work in this situation. I was following a tutorial that gave the example if (a or b):, but when I try to do this it only checks the variable against the first value. What is wrong with my check?

name = raw_input('Please type in your name:')

if len(name) < 5:
    print "Your name has fewer than 5 characters"
elif len(name) == 5:
    print "Your name has exactly 5 characters"
    if name == ("Jesse" or "jesse"):
        print "Hey Jesse!"
else:
    print "Your name has greater than 5 characters"

解决方案

("Jesse" or "jesse")

The above expression tests whether or not "Jesse" evaluates to True. If it does, then the expression will return it; otherwise, it will return "jesse". The expression is equivalent to writing:

"Jesse" if "Jesse" else "jesse"

Because "Jesse" is a non-empty string though, it will always evaluate to True and thus be returned:

>>> bool("Jesse")  # Non-empty strings evaluate to True in Python
True
>>> bool("")  # Empty strings evaluate to False
False
>>>
>>> ("Jesse" or "jesse")
'Jesse'
>>> ("" or "jesse")
'jesse'
>>>

This means that the expression:

name == ("Jesse" or "jesse")

is basically equivalent to writing this:

name == "Jesse"


In order to fix your problem, you can use the in operator:

# Test whether the value of name can be found in the tuple ("Jesse", "jesse")
if name in ("Jesse", "jesse"):

Or, you can lowercase the value of name with str.lower and then compare it to "jesse" directly:

# This will also handle inputs such as "JeSSe", "jESSE", "JESSE", etc.
if name.lower() == "jesse":

这篇关于为什么使用“OR"检查多个值的变量只检查第一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆