理解python中的def函数

理解python中的def函数,python,Python,我试图用python计算e(2.718283),我意识到你不能简单地除法,所以我定义了一个函数来除法并取整到五位数,我还定义了一个函数来查找阶乘,就是这样- . def div(x,y): t=x+0.00 p=y+0.00 a=t/p 圆形(a、5) 打印 def事实(n): c=1 d=1 而c=n: 打破 p=p*n 打印p m=0 当m=20: 打破 打印e` 我执行它,得到这个UnboundLocalError:赋值前引用的局部变量“p”。但事实(3)似乎是完美的。。 发生了

我试图用python计算e(2.718283),我意识到你不能简单地除法,所以我定义了一个函数来除法并取整到五位数,我还定义了一个函数来查找阶乘,就是这样- .

def div(x,y):
t=x+0.00
p=y+0.00
a=t/p
圆形(a、5)
打印
def事实(n):
c=1
d=1
而c=n:
打破
p=p*n
打印p
m=0
当m<20时:
e=div(1,事实(m))+q
q=div(1,事实(m+1))+q
如果m>=20:
打破
打印e`
我执行它,得到这个UnboundLocalError:赋值前引用的局部变量“p”。但事实(3)似乎是完美的。。 发生了什么事


PS:我还不习惯这里的格式,但我已经在实际代码中正确缩进了

按要求编辑:

line 20, in <module>
e = div(1,fact(m)) + q
File "/home/anirudh/Desktop/TEST PY/Hark-1.py", line 16, in fact
p = p*n
UnboundLocalError: local variable 'p' referenced before assignment
第20行,在
e=div(1,事实(m))+q
文件“/home/anirudh/Desktop/TEST PY/Hark-1.PY”,实际上是第16行
p=p*n
UnboundLocalError:赋值前引用了局部变量“p”

有几个错误:

  • q
    e=div(1,事实(m))+q中使用之前,在任何地方都没有定义
  • 您不会将
    轮(a,5)
    的结果分配给任何对象
  • 如果未输入
    while c
    循环,则执行
    p=p*n
    时将不会定义
    p
  • fact
    div
    函数都不会
    返回任何内容。(它们隐式返回
    None
  • 如果m>=20:,则无需检查

首先,Python中已经有了一些用于计算阶乘的更简洁的内置方法

import math 
print math.factorial(3)     #6
print math.factorial(4)     #24
如果你想在除以两个整数后得到浮点值,你可以简单地将其中任何一个输入到浮点,不需要将它们都转换

float_ans = p/float(q)
#or
float_ans = float(p)/q
使用此信息,您可以通过以下方式计算e的值:

 #Knowing the fact that e = 1 + 1/1! + 1/2! + 1/3! + 1/4! + 1/5! ....
    import math
    e = 0
    """
    As factorial of 20 is a very large value and you won't require that much of
    precision, I have cut down the no of iterations from 20 to 7 only, it also gives
    you a fair amount of precision, you can always change the range to increase and
    decrease the precision accordingly.
    """
    for num in range(0,7):    
        e+=(float(1)/math.factorial(num))
    print e
2.7180556


请修复缩进并包含完整的异常回溯。此外,如果在脚本顶部添加来自uuu future uuuu import division的
,则可以正确分割。如果
c>=n
,则在
循环时不输入
。我想你可以做剩下的。好的,我用p=1初始化了循环,设置q=0。。现在怎么办?事实(3)确实返回6{我想我误解了返回的含义}打印和返回之间有区别<代码>打印(值)
向用户显示值<代码>返回值
(函数内部)生成
,作为调用函数的结果。有关函数的更多信息,请参阅。谢谢您的时间,我想我终于明白了。@AnirudhGanesh如果Rawing的答案有帮助,请使用左侧的勾号将其标记为已接受。这会让其他人知道你的问题已经得到了回答,因此他们可以帮助其他人。接受和提升投票也能提高声誉,这是感谢某人为解决你的问题所做的努力的一种方式。
 #Knowing the fact that e = 1 + 1/1! + 1/2! + 1/3! + 1/4! + 1/5! ....
    import math
    e = 0
    """
    As factorial of 20 is a very large value and you won't require that much of
    precision, I have cut down the no of iterations from 20 to 7 only, it also gives
    you a fair amount of precision, you can always change the range to increase and
    decrease the precision accordingly.
    """
    for num in range(0,7):    
        e+=(float(1)/math.factorial(num))
    print e