2014-10-18 23 views
-2

我正在做一些計算機科學作業,並試圖學習一些基本的python。我試圖做一個IF語句,但我不斷收到語法錯誤(順便說一下,Python 3.3.3版本)。有人可以告訴我我做錯了什麼嗎?請注意,雖然我的錯誤很可能在IF聲明中,但它也可能在其他地方。謝謝。我在Python中錯誤地構造了我的IF語句嗎?

print ("Hello. What is your name?") 
print("") 
name = input() 
print("") 
print("Hello ", name, ". What lesson do you have next?") 
print("") 
lesson = input() 
print("") 
print("I hate ", lesson, ". You're rubbish.") 
wait = input() 
print("...") 
wait = input() 
print("...") 
wait = input() 
print("...") 
wait = input() 
print("") 
print("Do you like me? If you love me, type 1. If you hate me, type 2. If you're inbetween, type 3.") 
print("") 
emotion = input() 
print("") 
if emotion == 1: 
    print ("Awwwwwww.") 
    print ("") 
    else: 
     if emotion == 2: 
     print ("Yeah well I don't like you either.") 
     print ("") 
     else: 
      if emotion == 3: 
      print ("Yeah OK fair enough") 
      print ("") 
      else: 
       print("I said type 1, 2 or 3. I'm going now.") 
       print("") 
print("I'm going now. Goodbye friend.") 
print("") 
wait = input() 
quit() 
+1

使用'如果/ elif's' – 2014-10-18 10:36:02

+1

後實際的錯誤消息你 – thefourtheye 2014-10-18 10:36:28

+0

我得到的是「語法錯誤」。它不會告訴我什麼。 – 2014-10-18 10:36:55

回答

0

Python是縮進敏感的。 的else的縮進必須是一樣的if的壓痕:

if emotion == 1: # 1 
    <code> 
    if <condition>: # 2 
     <code> 
    elif <condition>: # 2 
     <code> 
    else: # 2 
     <code> 
else: # 1 
    <code> 

#1 else屬於#1 if。 #2 elifelse屬於#2 if

1

else總是要縮進到相同的級別對應的if

if emotion == 1: 
    print ("Awwwwwww.") 
    print ("") 
else: 
    if emotion == 2: 
     # etc. 

接下來,你可以在這裏使用elif

if emotion == 1: 
    print ("Awwwwwww.") 
    print ("") 
elif emotion == 2: 
    # etc. 

接下來,我不是在這裏使用if...elif...完全;你會使用列表或映射來代替:

emotions = ['', 'Awwwwwww.', "Yeah well I don't like you either.", ...] 
print(emotions[emotion]) 
+0

感謝您的幫助。我已經添加了你的ELIF建議(因爲我仍然是一個初學者,不理解另一個),但現在我得到一個「無效的語法」錯誤的冒險旁邊的情感== 2: – 2014-10-18 10:46:42

+0

@ user2627595:那麼你有另一個錯誤的地方。例如,你真的在​​'elif'下有一個套件(一個縮進的語句塊)嗎? – 2014-10-18 12:06:04