2014-09-28 96 views
-5

这里是我的代码,如下所示:Elif语句语法错误:语法无效?

menu= "Welcome to the menu\n"          \ 
+  "Please select an option below:\n"       \ 
+ ( "0 - Enter a number\n" + "1 - Display current number\n" + \ 
"2 - Divisibility checking\n" + "3 - Perfect checking\n"  + \ 
"4 - Triangular checking\n" + "5 - Quit\n") 
x == ("") 
while option!=5:             # <<< Q2 
    print(menu) 
    option= int(input("Enter option: ")) 
    if option==0: 
     x= int(input("What is your number?: ")) 
     while x <=0: 
      x= int(input("Must be positive, please! What is your number?: ") 
    elif option==1:            # <<< Q1 
     print("The current number is", x) 
     elif (x == ""): 
      print("No number yet - Please input a number and try again.") 
      x= int(input("What is your number?: ")) 

Q1: 我想知道为什么我一直得到一个错误消息我的代码line 14,第二elif声明。

Q2: 我也想知道怎么样,我的第一个while发言,我如果我不提示用户输入选项还可以定义“option”为option!=5然后print菜单。

对这两种情况的任何帮助都会很感激。

谢谢。

+2

你读过这段代码吗?你知道'elif'属于什么吗? – 2014-09-28 16:57:17

+0

在你的while循环没有做任何事情之前,你不能象'elif(x ==“”)''也有'x ==(“”)''那样嵌套elif语句。 – 2014-09-28 17:01:43

+1

您已忘记关闭前一行的int()括号。 – 2014-09-28 17:09:37

回答

0

关于你的第二条ELIF语句,我认为你的嵌套错误。

你有一个外决策树,你去哪里在可用选项,树是:

你不需要在内部ELIF,因为它不是一个else语句所选择的选项。您刚刚开始一个新的决策树(您尝试查找x是否已分配,如果不请求数字,则显示该数字)。因此,正确的代码应该是:

elif option == 1: 
    if x == "": 
     print("No number yet - Please input a number and try again.") 
     x= int(input("What is your number?: ")) 
    else: 
     print("The current number is", x) 
elif option == 2 
    --> Handling of option 2 

这应该有效。我把自由首先把if语句,否则你会得到输出

"The current number is " 
"No number yet - Please input a number and try again."... 

我觉得这是一个很值得什么意思伊格纳西奥,当他问,如果你知道的elif属于什么。

+0

我想你错过了最重要的问题,那就是缺少一个')'。 – SethMMorton 2014-09-29 03:34:48

+0

这确实是一个问题,Martijn正确指出了,但是当她在第二个elif语句中提到了一个问题时(因此编辑错误,Q1应该在代码中进一步向下标记两行),但我仍然认为错误缩进的elif是她的问题。 – MichaelA 2014-09-29 19:14:07