3

我正在从在线教程中学习 Python。我的问题是,当我运行脚本时,无论我输入什么,我得到的响应都是 if go == "kitchen"...

def go_to():
    go = raw_input("Go to? ")

    if go == Kitchen or breakfast:
         print "You rumble down stairs and into the kitchen. Your mom has left some microwaved waffles on the table for you. Your big boy step sits by the counter."
    elif go == "back to bed" or "back to sleep" or bed or sleep:
        print "You hit snooze and roll over."
    elif go == "bathroom" or "toilet" or "potty" or "pee" or "poop" or "take a sh*t" or "take a dump" or "drop a load":
        print "You make a stop at the head first."
        go_to()
    else:
        print "That is not a command I understand."
        go_to()
go_to()
4

6 回答 6

5

正如评论中提到的,您or在这里的使用不正确。这个:

go == "kitchen" or "breakfast"

相当于这个:

(go == "kitchen") or "breakfast"

or运算符将其两个操作数都转换为布尔值,这为您提供:

(something) or true

这总是减少到true,所以你总是输入 if 语句

于 2012-08-02T15:38:12.137 回答
1

正如 Ignacio 所说,您需要一个新教程。

如果任一子表达式或计算结果为,则表达式go == Kitchen or breakfast将为真。如果评估为与 相同的对象,或者它们的类型定义了一个为它们定义相等性的方法,或者如果对象不是,就会发生这种情况。go == KitchenbreakfastTruegoKitchen__eq__breakfastNone

检查变量是否包含列表中的值的方法是:

if go in (Kitchen, breakfast):
   # do something

另请注意,您的代码没有显示变量Kitchenbreakfast定义的位置,并且您的缩进不正确。

于 2012-08-02T15:38:57.077 回答
0

我相信问题出在你的第一个 if 语句上

在大多数编程语言中,你不能像你一样只说“或”。您需要做的是在所有条件下重复“go ==”部分。

if go == Kitchen or go == breakfast:

它现在正在做的是评估 (go == Kitchen) 并发现它是错误的。然后它正在评估“早餐”并返回真。因为它是一个“或”语句,所以整个 if 为真。

于 2012-08-02T15:37:28.107 回答
0

语法

if go == "Kitchen" or "breakfast":

由于评估顺序是错误的。看来您打算检查 go 是“厨房”还是“早餐”。但是,您检查 go 是否为“kitchen”或字符串“breakfast”是否为真。后者总是如此,因为非空字符串的计算结果不是 False。

描述您的意图的直观方式是:

if (go == "kitchen") or (go == "breakfast"):

可能更 Pythonic 你也可以写:

if go in ["kitchen", "breakfast"]:
于 2012-08-02T15:39:41.963 回答
0

要检查条件是否是事物列表之一,则应使用in,例如:

if go in ('Bathroom', 'take a dump', 'have a beep'):
    # do something...
elif go in ('Kitchen', 'Living room'):
    # etc...
else:
    # no idea where to go?

的使用or并没有达到您的预期,并且已在其他帖子中进行了解释。

于 2012-08-02T15:39:51.930 回答
0

你的代码说的是如果去厨房或早餐所以对于python来说这意味着如果去厨房或早餐

所以,它要么是Something,要么是True。它解析为 True ,因此第一个 if 语句总是被执行。您可以通过以下方式修复它 if go in ['kitchen', 'breakfast']

于 2021-11-06T03:21:15.283 回答