Elif声明不起作用

时间:2013-07-06 12:46:24

标签: python if-statement python-2.7

enter image description here

我真的无法理解我做错了什么。 真的很感谢你的帮助。

3 个答案:

答案 0 :(得分:2)

你的缩进是错误的。左缩进一次,语法错误将消失。

if < Condition Here >:
    # Do Something
    elif < Condition Here >: 

会出现语法错误,而

if < Condition Here>:
     # Do Something
elif < Condition Here >:
     # Do Something

是正确的缩进。缩进在Python中非常重要。

来自Python Docs

  

在逻辑开头引出空格(空格和制表符)   line用于计算行的缩进级别   turn用于确定语句的分组。

答案 1 :(得分:2)

elif语句没有使用if语句正确缩进:

if some_condition:
    #code
elif some_other_condition:
    #code

来自docs

  

在逻辑开头引出空格(空格和制表符)   line用于计算行的缩进级别   turn用于确定语句的分组。

来自docs的示例:

>>> x = int(raw_input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...      x = 0
...      print 'Negative changed to zero'
... elif x == 0:
...      print 'Zero'
... elif x == 1:
...      print 'Single'
... else:
...      print 'More'
...
More

在IDLE上尝试这样的事情:

>>> x = 2
>>> if x == 0:
    print x
elif x == 1:
    print x
elif x == 2:
    print x
else:
    print 'foo'


2

答案 2 :(得分:0)

你应该创建一个单独的python脚本,例如tmp.py并在那里放置最复杂的命令序列:

if something:
    pass
else:
    pass

保存,然后如果您在run tmpIPython,如果您在shell(命令提示符,bash等)中,则使用python tmp.py运行。

相关问题