2017-04-02 104 views
-3

這是我爲Learn Python the Hard Way練習36編寫的代碼。但是我無法運行door_1函數中的代碼。如果我選擇3作爲選項,然後向左或向右移動存儲在目錄中的任何內容,則無論輸入什麼內容,輸出都是「獅子吃了你」。卡在第36次練習中學習Python困難之路

from sys import exit #importing module from lib 

def Tadaa(): 
    print "This is a place where you will get a surprise" 
    next = int(raw_input("Enter any number from 1-10 :")) 
    if next <= 10: 
     if next % 2 == 0 : 
      print "You will be buying me a shake :)." 
     else : 
      print "You will be getting a shake by me." 
    else : 
     print "Do it correctly." 

def door_1(): 
    print "There are 3 doors . Choose any door from the the remaining three doors" 
    print "Lets hope for the best " 
    next = raw_input("Enter your option :") 
    if next == "1": 
     print "abc " 
    elif next == "2": 
     print "abc" 
    elif next == "3": 
     print "You have entered 3rd door ." 
     print "Here are 2 doors one on left and one on right." 

     dir = raw_input("Choose which door do you wnat to enter :") 

     if dir == "left" or "Left": 
      print "Lion ate you . You are dead ." 
     elif dir == "right" or "Right" : 
      print "You will be getting a surprise" 
      Tadaa() 
     else : 
      print "abc" 
    else : 
     print "abc" 

def door_2(): 
    print "There are two doors A and B which will decide your fate" 

    next = raw_input("Enter the door ") 

    if next == "A" or "a": 
     door_1()    
    elif next == "B" or "b": 
     print "You are back from where you have started" 
     start() 
    else : 
     print "I got no idea what that means." 
     exit(0) 

def start(): 
    print "You are in dark room" 
    print "There is a door to your right and left ." 
    print "Which one do you take" 

    next = raw_input("> ") 

    if next == "Right" or "right": 
     door_2() 
    elif next == "Left" or "left": 
     door_1() 
    else : 
     print "abc" 
start() 

回答

2

的問題是你的聲明:

if dir=="left" or "Left": 

你想要的是

if dir=="left" or dir=="Left": 

實際上,什麼只是在做or "Left"是幹什麼的,是檢查是否你已經字符串剛剛創建存在與否。換句話說,它類似於:

x='Left' 
if x: 

X確實存在,所以if XTrue

這裏的關鍵是要始終評估量子語句,並且當您使用andor語句一起使用時,請確保使用括號是明確的。 if statement_one or statement_two

+0

但是如果你會看到start()函數,你會看到我已經對下一個語句做了同樣的事情,但它確實運行了 –

+0

嗯。我不能確定,但​​我可以告訴你的一個事實就是你評估'if'陳述不正確的方式:)如上所示正確執行,看看是否能解決你的問題。 – Henry

+0

如果你瞭解下一條語句,請告訴我:) –