【问题标题】:Syntax error when creating simple python program创建简单的python程序时出现语法错误
【发布时间】:2013-11-19 02:45:45
【问题描述】:

希望你一切都好。

尝试创建一个充当字典的 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"

【问题讨论】:

  • 你不能在 else 之后有一个 elif。顺序为:if、elif、else

标签: python if-statement syntax indentation


【解决方案1】:

假设您修复了缩进,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

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

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

【讨论】:

    【解决方案2】:

    我认为您对缩进问题是正确的。这是我认为您正在尝试做的事情:

    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 很难确定你想要什么。在你形成自己的风格并有充分的理由不这样做之前,每层一致的四个缩进空间是一个好习惯。让您的编辑器帮助您一致地缩进。哦,请确保在缩进时不要混合制表符和空格:这有一种方法似乎有点作用,然后又回来咬你。

    【讨论】:

      【解决方案3】:

      您似乎想将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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-11-25
        • 2019-10-16
        • 1970-01-01
        • 2013-05-12
        • 2018-11-21
        • 2018-06-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多