【问题标题】:else: syntax is incorrectelse: 语法不正确
【发布时间】:2012-05-24 05:50:47
【问题描述】:

我对 python 有点陌生,我正在尝试编写这个脚本来取消超过 1 mb 的打印作业。(检查大小的行设置为 1 mb,以确保它正常工作)。出于某种原因,我最后一个 else 语句一直说它的语法无效。我检查了是否所有括号都关闭了,我找不到一对不匹配的。有人可以告诉我为什么它说它无效吗?您还可以看看我的第 24 行 (fullname = ...grep...) 以确保其语法正确吗?

#! /usr/bin/python

import os

infile = open ('test.pl', 'r')

outfile = open('print.reportpython', 'w+')

newfile = infile.readlines()

newfile.pop(0)

count = 0

firstline = newfile[0]

splitline = firstline.split()

currentuser = splitline[1]

currentuser = str(currentuser)

for line in newfile:

  newline = line.split()

  names = newline[1]

  size = int(newline[2])

  names = str(names)

  print names

  if names is currentuser:

    if size >= 1:

      os.popen ("cancel lab01-10292")

  fullname = os.popen("cat /etc/passwd |grep " + newline[1] + "cut -d':' -f5")

  count += 1

  print count

  else:

    print outfile.write ("(" + currentuser + ")")

    print outfile.write (" ")

    count = 0

    currentuser = names

【问题讨论】:

  • 检查缩进!
  • 我已经检查过了。我什至删除了它周围线条上的所有空格,并将它们读取为所有空格,以确保没有任何隐藏的标签
  • 每行之间不要有空格。
  • 你能想象 else 语句中存在错误吗?
  • 如果您现在遇到完全不同的问题,请提出单独的问题

标签: python syntax syntax-error if-statement


【解决方案1】:

你这样做:

if foo:
  bar
baz
else:
  bomb

这是错误的。 if 与其对应的else 之间的所有行必须比ifelse 缩进更深,如下所示:

if foo:
  bar
  baz
else:
  bomb

【讨论】:

    【解决方案2】:

    else 与上一行的缩进相同,但上一行的语句没有else 子句。修正缩进。

    【讨论】:

    • 哇哦..谢谢。我不知道我是怎么错过的。现在我的另一个问题是我的 fullname = os.popen("cat /etc/passwd |grep " + newline[1] + "cut -d":" -f5") 它说它在 ":" i 处的语法无效还将上面的“:”更改为“:”
    猜你喜欢
    • 2015-08-18
    • 2014-06-22
    • 2023-03-10
    • 1970-01-01
    • 2011-01-24
    • 2020-09-14
    • 2020-07-05
    • 2019-07-29
    • 1970-01-01
    相关资源
    最近更新 更多