我在python中错误地构造了我的IF语句吗?

时间:2014-10-18 10:34:26

标签: python if-statement syntax

我正在做一些计算机科学的功课,我正在尝试学习一些基本的python。我正在尝试做一个IF语句,但我一直得到一个语法错误(顺便说一下,python版本3.3.3)。有人可以告诉我我做错了什么吗?请注意,虽然我的错误很可能在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()

2 个答案:

答案 0 :(得分: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])

答案 1 :(得分: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