简体   繁体   English

elif 语句出现语法错误

[英]elif statement getting a syntax error

I'm trying to set up a menu.我正在尝试设置菜单。 In the menu, the user is able to pick which option to take and then add or delete items from a list.在菜单中,用户可以选择要选择的选项,然后从列表中添加或删除项目。 I'm having trouble with the syntax in my elif statement.我的 elif 语句中的语法有问题。 it's saying there is a syntax error and highlighting the second elif.它说存在语法错误并突出显示第二个 elif。 I'm not sure what the problem is.我不确定问题是什么。

choice = int(input('Enter your choice: '))
if choice !=0:
    display_menu()
elif choice == 1:
    add_value = float(input('Add value: ')
elif choice == 2:
    delete_value_by_value = float(input('Which value would you like to delete? 

You forgot a closing parenthesis in the fifth line:你忘记了第五行的右括号:

add_value = float(input('Add value: '))
#                                     ^

Also, the seventh line is not properly terminated.此外,第七行没有正确终止。 You want:你要:

delete_value_by_value = float(input('Which value would you like to delete?'))
#                                                                         ^^^
delete_value_by_value = float(input('Which value would you like to delete?'))
                                                                 missing--^^^

Keep in mind that Python can only tell you where it stopped being able to make sense of your program, it can't tell you where you actually made the mistake.请记住,Python 只能告诉您它在哪里无法理解您的程序,它不能告诉您实际上在哪里犯了错误。

In this case you have left parentheses open on the preceding line.在这种情况下,您在前一行中留下了括号。 Python allows expressions to span multiple lines when parentheses are open, so it is taking the elif as part of the parenthesized expression.当括号打开时,Python 允许表达式跨越多行,因此它将elif作为括号表达式的一部分。 elif is invalid in an expression, so Python raises an error there. elif在表达式中无效,因此 Python 会在此处引发错误。 But the "real" mistake (ie, the one that goes with your intended meaning) is the missing parenthesis.但是“真正的”错误(即与您预期含义相符的错误)是缺少括号。

Just be glad you're not programming in good old UCSD Pascal in the 1980s.很高兴你没有在 1980 年代用老式的 UCSD Pascal 编程。 Every program had to end with a period.每个程序都必须以句点结束。 If it didn't, you got an error message pointing to some random place inside your program, leaving you mystified.如果没有,您会收到一条错误消息,指向程序中的某个随机位置,让您感到困惑。

I'd suggest searching for a good IDE that highlights syntaxes to minimize simple errors and typos.我建议寻找一个好的 IDE,它突出显示语法以尽量减少简单的错误和拼写错误。 Personally I like Eclipse with PyDev.我个人喜欢带有 PyDev 的 Eclipse。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM