Python:如何正确缩进此代码? [关闭]

问题描述 投票:-4回答:2

有人可以帮我解决这段python代码上的缩进错误吗?我试图编写一个程序来检查方程(10a + b)c =(10b + c)a的所有可能的一位整数值。

def plug():
  a = 1
  while a < 10:
   if (int(a) * 10 + int(b)) * int(c) ==(int(b) * 10 + int(c)) * int(a) and 0 > b > 10 and 0 > c > 10:
     print (a + b + c)
    a += 1
plug()
python indentation
2个回答
1
投票

下面的代码将解决您的缩进错误。原因是Python(与许多其他语言不同)是与缩进相关(4个空格),而不是使用{};之类的附加语法。请查看PEP 8了解更多信息。

此外,我将all()函数引入到您的代码中,作为许多and语句的替代方法。

但是,您仍然有错误,因为未定义bc。在代码运行之前,需要解决此问题。

def plug():
    a = 1
    # Variables b and c must be defined.
    # b = 1
    # c = 1
    while a < 10:
        if all([((int(a) * 10 + int(b)) * int(c)) == ((int(b) * 10 + int(c)) * int(a)), (0 > b > 10), (0 > c > 10)]):
            print(a + b + c)
        a += 1

-1
投票

如果您使用2个空格缩进:

  1. 第4行(if语句)在if之前应有另一个空格。

  2. 第6行(a + = 1)相同。

或者您也可以复制并粘贴这个!

def plug():
  a = 1
  while a < 10:
    if (int(a) * 10 + int(b)) * int(c) ==(int(b) * 10 + int(c)) * int(a) and 0 > b > 10 and 0 > c > 10:
      print (a + b + c)
      a += 1
plug()
© www.soinside.com 2019 - 2024. All rights reserved.