我正在向程序添加一个简单的打印变量行,它给了我一个缩进错误。代码适用于注释掉的“print yes”行,如图所示,但是当我取消注释时,出现错误:
错误:
factors.append(yes)
^
IndentationError: unexpected indent
代码:
n = 1
x = int(raw_input("What is the number you would like largest prime factor of?"))
factors= []
checklist = []
primefactors = []
while n < (x+1)/2:
if x % n == 0:
yes = n
#print yes
factors.append(yes)
if n % 1000 == 0:
print "running n count = %s" % (n)
n += 1
for j in factors:
checklist = [j]
for i in range(2, j):
if j % i == 0:
checklist.append(j/i)
if len(checklist) == 1:
primefactors.append(checklist)
print "All factors of %s are %s" % (x,factors)
print "The prime factors are %s" % (primefactors)
print "The highest prime factor is %s" % (max(primefactors))
制表符和空格在 Python 中被认为是不同的。确保使用 4 个空格或制表符缩进,不要在单个程序中互换使用它们。
编辑:我发现了。就在这里:
if x % n == 0:
yes = n
#print yes
factors.append(yes)
将其更改为:
if x % n == 0:
yes = n
print yes
factors.append(yes)
您的
if
块未缩进。更改 if
块:if x % n == 0:
yes = n
#print yes
factors.append(yes)
将其更改为:
if x % n == 0:
yes = n
print yes
factors.append(yes)