创建简单的python程序时出现语法错误

时间:2013-11-19 02:45:45

标签: python if-statement syntax indentation

希望你们一切顺利。

尝试创建一个充当字典的Python程序,但现在在创建elif语句时遇到了一些问题。我是我的空闲我一直有迹象表明我的语法对于elif是错误的,但我不是我做错了什么呢?我想这是一个缩进错误,但究竟是什么呢?

if choice == "0":
   print "good bye"

elif choice == "1":
  name = raw_input("Which philosopher do you want to get")
if name in philosopher:
 country = philosopher [name]
 print name, "comes from" , country
else:
 print "No such term"
***elif choice == "2" :*** ***<<I am being told that I have syntax error in this elif element, what am I doing wrong)**
  name = raw_input(" What name would you like to enter")
if name not in philosopher:
    country = raw_input( "Which country do you want to put your philosopher in")
    philosopher [name] = country
    print name, "has now been added and he is from", country
else:
      print "We already have that name"

3 个答案:

答案 0 :(得分:2)

假设您修复了缩进,if语句将按此顺序排列:

if x:
  #do something
elif x:
  #do something

if x:
  #do something
else:
  #do something

elif x:#CAUSES ERROR
  #do something

if x:
  #do something
else:
  #do something

您的elifelse声明之后出现。你不能这样做。 elif 必须介于ifelse之间。否则编译器永远不会捕获elif(因为它刚刚运行并执行了else语句)。换句话说,您必须按如下顺序排列if语句:

if x:
  #do something
elif x:
  #do something
else:
  #do something

答案 1 :(得分:1)

我认为你对缩进问题是正确的。以下是我认为您要做的事情:

if choice == "0":
    print "good bye"
elif choice == "1":
    name = raw_input("Which philosopher do you want to get")
    if name in philosopher:
        country = philosopher [name]
        print name, "comes from" , country
    else:
        print "No such term"
elif choice == "2" :
    name = raw_input(" What name would you like to enter")
    if name not in philosopher:
        country = raw_input( "Which country do you want to put your philosopher in")
        philosopher [name] = country
        print name, "has now been added and he is from", country
    else:
        print "We already have that name"

关键问题是缩进不一致,这使得Python难以确定您想要的内容。在你开发自己的风格并且有充分理由做其他事情之前,每个级别一致的四个缩进空间是一个好习惯。让编辑帮助您持续缩进。哦,并确保在缩进时不要混合标签和空格:这有点似乎有效,然后再回来咬你。

答案 2 :(得分:0)

您希望将if name in philosopher ... No such term"部分放在以elif choice == "1":开头的块中。如果是这样,您需要再缩进一次,以便Python正确地对您的ifelifelse语句进行分组。

if choice == "0":
    # code
elif choice == "1":
    if name in philospher: # indented twice; can only run if choice == "1"
        # code
    else:
        # code
elif choice == "2":
    # code
# rest of code