2012-08-02 92 views
3

我是从一个在线教程学习Python的。我的问题是,当我运行该脚本,不管是什么我输入的响应我得到的是,如果去==“厨房” ......Python函数运行到第一个if语句不管输入

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() 
+5

您需要一个新的教程,因为'or'的用法不正确。 – 2012-08-02 15:34:26

+2

就目前而言,这个程序会因为语法错误而中止。缩进在Python中很重要。请解决这个问题。此外,你有'床'和'睡眠'这些没有引用的东西。当你的函数被调用时,这也会出错。 – 2012-08-02 15:36:36

+1

你不喜欢''''和'''字符,是吗? – glglgl 2012-08-02 15:41:03

回答

1

正如伊格纳西奥说,Y你需要一个新的教程。

如果子表达式go == Kitchenbreakfast评估为True,则表达式go == Kitchen or breakfast将为真。这将发生,如果go的计算结果为相同的对象Kitchen,或它们的类型定义了一个__eq__方法,其限定平等它们,或者这将是情况下,如果breakfast是一个对象,它是不None

的方式来检查,如果变量包含在列表中的值是:

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

另请注意,您的代码不显示其中的变量Kitchenbreakfast定义,你的缩进不正确。

+0

我猜'厨房'和'早餐'没有定义... – 2012-08-02 15:42:20

+0

是的,他们werent的意思是变量,但stri NGS。我只是在尝试不同的事情,把报价拿走,忘了把它们放回去。谢谢您的帮助。 – 2012-08-02 17:43:55

+0

@ user1571810无论它们是变量还是字符串都无关紧要。适用相同的评估规则(当然除了有额外的评估步骤外)。 – Marcin 2012-08-02 17:45:27

0

我beleive的问题是你的第一个if语句

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

if go == Kitchen or go == breakfast: 

它现在正在做的是评估(去==厨房)并发现它是假的。那么它正在评估“早餐”并且返回true。因为它是一个“或”的陈述,那么整个如果是真的。

5

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

go == "kitchen" or "breakfast" 

等效于此:

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

or运营蒙上它的两个操作数到布尔值,它给你:

(something) or true 

总是降低到true,所以你总是进入if语句

0

语法

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

是因为计算的顺序的错误。看来你打算检查一下去是“厨房”还是“早餐”。但是,您检查是否是“厨房”或字符串“早餐”是否为真。后者总是这样,因为一个非空字符串计算的东西,一点也不假。

描述你的意图将是直观的方式:

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

也许更Python,你也可以这样写:

if go in ["kitchen", "breakfast"]: 
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不符合你的期望,并已在其他文章中解释过。