【问题标题】:Python throwing invalid syntax even though syntax is correct即使语法正确,Python也会抛出无效语法
【发布时间】:2019-05-07 01:20:45
【问题描述】:

我最近一直在使用数组,在我的练习程序中,由于某种原因,它不会停止抛出语法错误,而且我的 IDE 告诉我的所有内容都是出乎意料的。据我所知,一切都很好。我只是需要另一双眼睛。

我尝试从头开始重写并完全开始一个新文件。我什至卸载了python并重新安装了它。

import array as arr
employee_names = arr.array("u",[])
employee_hours = arr.array("u,",[])
employee_wage = arr.array("u",[])
input_employees = int(input("Type 1 if you want to start or 0 if you want to quit: ")

while input_employees == 1:
    input_names = input("Type in the names of the employees: ")
    employee_names.append(input_names)
    input_employees = int(input("If you want to enter more press 1 or if you are done press 0: ")
    if input_employees == 0:
        break
        print(employee_names)
    else:
    continue

但是当你运行它时,由于某种原因,你会在 while 语句中遇到语法错误。

【问题讨论】:

  • 您忘记关闭前一行的括号。
  • 您也没有在第二个input 上关闭括号。
  • @kindall 是对的,但是您忘记在两个 input 语句上关闭括号。
  • 谢谢大家。我发布后不久就意识到了这一点。感谢您的帮助。

标签: python syntax


【解决方案1】:

我认为这应该可以正常工作:

employee_names = []
employee_hours = []
employee_wage = []
input_employees = int(input("Type 1 if you want to start or 0 if you want to quit: "))
while input_employees:
    input_names = input("Type in the names of the employees: ")
    employee_names.append(input_names)
    input_employees = int(input("If you want to enter more press 1 or if you are done press 0: "))
    if not input_employees:
        break
    else:
        continue

请记住:

1) 始终完成括号。

2) 在开始编码之前学习语法。

注意:我没有修复你的算法,只是修复了可能的错误。

【讨论】:

  • 是的,感谢您的回复。我知道语法。我想是什么,在这一点上,我对让数组工作感到非常沮丧,以至于我看不出问题出在哪里。甚至我的 IDE 对语法错误的位置也没有帮助。
  • @jedimilk 您可以随时在 stackoverflow 上发布您的问题。总会有人帮助你。
【解决方案2】:

根据您给出的代码 sn-p,问题似乎与

else:
continue

部分。 Python 完全适用于缩进,因此在编写 Python 代码时始终检查嵌套缩进。这是没有错误的代码:-

import array as arr
employee_names = arr.array("u",[])
employee_hours = arr.array("u,",[])
employee_wage = arr.array("u",[])
input_employees = int(input("Type 1 if you want to start or 0 if you want to quit: ")

while input_employees == 1:
    input_names = input("Type in the names of the employees: ")
    employee_names.append(input_names)
    input_employees = int(input("If you want to enter more press 1 or if you are done press 0: ")
    if input_employees == 0:
        print(employee_names) // print before break
        break
    else:
       continue

另外,else部分可以省略,因为即使没有添加else部分,循环也会继续。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-15
    • 2021-11-13
    • 2022-08-11
    • 1970-01-01
    相关资源
    最近更新 更多