繁体   English   中英

Python 2-如何使用“或”?

[英]Python 2 - How do I use 'or'?

我真的是python新手,并且我刚刚编写了一个小程序。 如果键入“ Hello”或“ hello”,它将显示为“正在工作”,如果键入其他任何内容,则将显示为“不工作”。 这是我到目前为止的代码:

print "Type in 'Hello'"
typed = raw_input("> ")
if (typed) == "Hello" or "hello":
   print "Working"
else:
    print "not working"

该代码不起作用,无论我提交什么内容,即使我键入“ jsdfhsdkfsdhjk”,它也始终会显示“正在工作”。 如果我取出“ or”和“ hello”,它确实可以工作,但是我想同时检查两者。 如何使脚本起作用?

非常感谢!!

您正在检查typed是否等于"Hello"或者作为独立表达式的"hello"计算结果是否为true(确实如此)。 您不必链接多个值来检查原始变量。 如果要检查一个表达式是否等于不同的事物,则必须重复它:

if typed == 'Hello' or typed == 'hello':

或者,类似:

if typed in ['Hello', 'hello']: # check if typed exists in array

或者,是这样的:

if typed.lower() == 'hello': # now this is case insensitive.

if (typed) == "Hello" or "hello":应该是if typed == "Hello" or typed == "hello":

目前的问题是or应该分开两个问题。 它不能用于将同一问题的两个答案分开(我认为这是您期望的结果)。

因此,python尝试将“ hello”解释为一个问题,并将其强制转换为true / false值。 碰巧“ hello”强制转换为true (您可以查找原因)。 因此,您的代码实际上说的是“ if something or TRUE”,始终为true ,因此始终输出“ working”。

您可能要尝试将typed转换为小写,因此只需检查一件事。 如果他们键入“ HELLO”怎么办?

typed = raw_input("> ")
if typed.lower() == "hello":
    print "Working"
else:
    print "not working"

or (和and )两侧的表达式彼此独立地求值。 因此,右侧的表达式不会共享左侧的'=='。

如果您想针对多种可能性进行测试,则可以

typed == 'Hello' or typed == 'hello'

(如Hbcdev所建议),或使用in运算符:

typed in ('Hello', 'hello')

您可以通过两种方式做到这一点(Atleast)

print "Type in 'Hello'"
typed = raw_input("> ")
if typed == "Hello" or typed == "hello":
   print "Working"
else:
    print "not working"

或者使用in

print "Type in 'Hello'"
typed = raw_input("> ")
if typed in ("Hello","hello",):
   print "Working"
else:
    print "not working"

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM