【问题标题】:debugging invalid syntax error iPython调试无效的语法错误 iPython
【发布时间】:2013-03-31 22:54:03
【问题描述】:

我在执行程序后遇到以下语法错误感谢this post的thkang

You entered:  ./#
Expanded to:  ./#
=================
File "./largestoddxyz.py", line 43
else: #x and z are even
   ^
SyntaxError: invalid syntax

代码如下:
我是使用 Python 的新手,并试图解决这个问题,但不幸的是,我没能做到。希望这里有人可以帮助我。

#!/usr/bin/env python
# This program exmamines variables x, y, and z 
# and prints the largest odd number among them

import sys

x,y,z = map(int,sys.argv[1:4])

if x%2 != 0:
  if y%2 != 0:
    if z%2 != 0:
      if x > y and x > z: #x is the biggest odd
        print 'x is the biggest odd ' and x
      elif y > z and y > x: #y is the biggest odd
        print 'y is the biggest odd ' and y
      elif z > x and z > y: #z is the biggest odd
        print 'z is the biggest odd ' and z

    else: #z is even
      if x > y: #x is the biggest odd
        print 'x is the biggest odd ' and x
      else: #y is the biggest odd
        print 'y is the biggest odd ' and y

  else: #y is even
      if z%2 != 0: #z is odd
        if x > z: #x is the biggest odd
          print 'x is the biggest odd ' and x
        else: #z is the biggest odd
          print 'z is the biggest odd ' and z
      else: #y,z are even and x is the biggest odd
        print 'x is the biggest odd ' and x

else: #x is even
  if y%2 != 0 and z%2 != 0: #y,z is odd
      if y > z: #y is the biggest odd
        print 'y is the biggest odd ' and y
      else: #z is the biggest odd
        print 'z is the biggest odd ' and z
  else: #x and y are even
    if z%2 != 0: #z is the biggest odd
      print 'z is the biggest odd ' and z
  else: #x and z are even
    if y%2 != 0: #y is odd
      if z%2 = 0: #z is even
        print 'y is the biggest odd ' and y

print 'finished'

【问题讨论】:

    标签: debugging ipython


    【解决方案1】:

    缩进错误;注意

      else: #x and y are even
        if z%2 != 0: #z is the biggest odd
          print 'z is the biggest odd ' and z
      else: #x and z are even
    

    您想缩进第二个else 以及它下面的所有内容。您可能需要运行 pep8 来验证一切是否正常,即您使用了正确的间距并且不要混合制表符和空格字符。

    另外,在行中

    if z%2 = 0: #z is even
    

    您想要比较 ==,而不是分配 =

    【讨论】:

    • 所以我做了正确的缩进,但现在我在第 45 行收到错误 ['File "largestoddxyz.py", line 45 if z%2 = 0: #z is even ^ SyntaxError: invalid语法']
    • @dustin 请不要用答案编辑您的问题 - 这会使其他人更难理解它,并阻止该问题成为其他人的路标犯了同样的错误。更新了答案。
    • pep8 非常感谢!我希望我早点知道。
    • 如果所有数字都是偶数,我只是添加了一个部分,但它返回另一个语法错误。我跑了 pep8 但它一无所获。
    • @dustin 尝试reduce your program to a minimal one that exhibits the problem,然后将其作为新问题发布。
    猜你喜欢
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-09
    • 2014-11-23
    • 1970-01-01
    相关资源
    最近更新 更多