【发布时间】:2017-07-10 20:54:43
【问题描述】:
我正在尝试使用 Python 编写自己的素数和完美平方检查器, 如果这是一个素数,函数应该打印'Foo',如果这是一个完美的正方形,则打印'Bar',如果两者都不是,则打印'FooBar' 这是我的代码:
def FooBar():
prime = True
perfSqr = False
for target in range(100,100001):
for num in range(1,target+1):
if target % num == 0 and num != target:
prime = False
if target // num == num and target % num == 0:
perfSqr = True
if prime is True:
print 'Foo'
elif perfSqr is True:
print 'Bar'
else:
print 'FooBar'
if __name__ == '__main__':
FooBar()
不知怎的,我根本无法让它运行,谁能给我一些提示?
【问题讨论】:
-
范围从 1 开始,目标 % num 始终为 0。
-
你到底是什么意思?你没有调用方法吗?你能得到像
hello world这样简单的东西,而不需要你的计算和if/elses 吗? -
不要在一个大的单一函数中破坏所有逻辑。拥有
is_prime(x)、is_perfect_square(x)函数并将它们应用于序列。
标签: python algorithm primes perfect-square