getting ZeroDivisionError: integer division or modulo by zero
getting ZeroDivisionError: integer division or modulo by zero
我在 python 中写了一个简单的 Pascal 三角形代码,但我收到一个错误
def factorial(n):
c=1
re=1
for c in range(n):
re = re * c;
return(re)
print "Enter how many rows of pascal triangle u want to show \n"
n=input();
i=1
c=1
for i in range(n):
for c in range(n-i-1):
print ""
for c in range(i):
a = factorial(i);
b = factorial(c);
d = factorial(i-c);
z = (a/(b*d));
print "%d" % z
print "\n"
错误:
Traceback (most recent call last):
File "/home/tanmaya/workspace/abc/a.py", line 19, in <module>
z = (a/(b*d));
ZeroDivisionError: integer division or modulo by zero
ZeroDivisionError 表示您尝试对数字 n
进行除法或取模 0.
在你的例子中,z = (a/(b*d))
导致 z = (a/0)
此外,正如@theB 所指出的,您的 factorial
函数不正确。
尝试解决这些问题。
此外,您的代码中并不需要 ;
。当我们想让代码成为一行时,通常是我们放 ;
的情况。
你的 factorial()
函数 returns 0 因为你如何定义你的范围。
内置范围从 0 开始,除非另有定义:
for c in range(n):
re = re * c # no semicolons in Python
正在做:
re = re * 0
在第一次迭代中,因此对于所有后续迭代:
re = 0 * c
永远是 0
像这样从 1 开始你的范围
for c in range(1, n):
re *= c # The *= operator is short hand for a = a * b
你可以更清楚地看到这一点:
>>> print(list(range(5)))
[0, 1, 2, 3, 4]
>>> print(list(range(1,5)))
[1, 2, 3, 4]
>>>
或者使用 Python:
自带的函数来代替滚动你自己的函数
>>> from math import factorial
>>> factorial(3)
6
仔细阅读您的代码后,您似乎试图通过在 for
循环之外设置 c = 1
来规避此问题。这不会起作用,因为您在循环外声明的变量正在循环内重新分配。
我在 python 中写了一个简单的 Pascal 三角形代码,但我收到一个错误
def factorial(n):
c=1
re=1
for c in range(n):
re = re * c;
return(re)
print "Enter how many rows of pascal triangle u want to show \n"
n=input();
i=1
c=1
for i in range(n):
for c in range(n-i-1):
print ""
for c in range(i):
a = factorial(i);
b = factorial(c);
d = factorial(i-c);
z = (a/(b*d));
print "%d" % z
print "\n"
错误:
Traceback (most recent call last):
File "/home/tanmaya/workspace/abc/a.py", line 19, in <module>
z = (a/(b*d));
ZeroDivisionError: integer division or modulo by zero
ZeroDivisionError 表示您尝试对数字 n
进行除法或取模 0.
在你的例子中,z = (a/(b*d))
导致 z = (a/0)
此外,正如@theB 所指出的,您的 factorial
函数不正确。
尝试解决这些问题。
此外,您的代码中并不需要 ;
。当我们想让代码成为一行时,通常是我们放 ;
的情况。
你的 factorial()
函数 returns 0 因为你如何定义你的范围。
内置范围从 0 开始,除非另有定义:
for c in range(n):
re = re * c # no semicolons in Python
正在做:
re = re * 0
在第一次迭代中,因此对于所有后续迭代:
re = 0 * c
永远是 0
像这样从 1 开始你的范围
for c in range(1, n):
re *= c # The *= operator is short hand for a = a * b
你可以更清楚地看到这一点:
>>> print(list(range(5)))
[0, 1, 2, 3, 4]
>>> print(list(range(1,5)))
[1, 2, 3, 4]
>>>
或者使用 Python:
自带的函数来代替滚动你自己的函数>>> from math import factorial
>>> factorial(3)
6
仔细阅读您的代码后,您似乎试图通过在 for
循环之外设置 c = 1
来规避此问题。这不会起作用,因为您在循环外声明的变量正在循环内重新分配。