[英]Function not defined after declaration in python3
Using python 3: I have three functions: montePi, isInCircle and main. 使用python 3:我具有三个功能:montePi,isInCircle和main。 I need to have the isInCircle called by montePi.
我需要有montePi调用的isInCircle。 The function will work, it just says that isInCircle is not defined.
该函数将起作用,它只是说isInCircle未定义。 How can I define it?
我该如何定义?
import random
import math
def montePi(numDarts):
inCircle = 0
def isInCircle(x, y, r):
r = 1
d = math.sqrt(x**2 + y**2)
if d <= r:
return True
else:
return False
for i in range(numDarts):
x = random.random()
y = random.random()
d = math.sqrt(x**2 + y**2)
if d <= 1:
inCircle = inCircle +1
pi = inCircle / numDarts * 4
return pi
def main():
print(montePi(100))
print(montePi(1000))
print(montePi(10000))
print(montePi(100000))
main()
Because function isInCircle
is defined in montePi
, it can be called within montePi
but not other functions as it is local. 由于功能
isInCircle
被定义montePi
,它可以被称为内montePi
而不是其他的功能,因为它是本地的。 If you define isInCircle
outside of montePi
then you'll be able to call it from main
. 如果定义
isInCircle
之外montePi
,那么你就可以从调用它main
。
Not sure what you're trying to program here, but there seems to be a chance that this question , regarding functions within functions can help you decide what you want here. 不确定您要在此处编程的内容,但是关于函数中的函数的问题似乎有可能帮助您在此处确定所需的内容。 Here is a question that covers how scopes work.
这是一个涵盖范围如何工作的问题。
Should you need to call isInCircle
from main
or outside main
, then this is how it should be formatted; 如果您需要调用
isInCircle
从main
或外部main
,那么这是应该如何进行格式化;
import random
import math
def isInCircle(x, y, r):
r = 1
d = math.sqrt(x**2 + y**2)
if d <= r:
return True
else:
return False
def montePi(numDarts):
inCircle = 0
for i in range(numDarts):
x = random.random()
y = random.random()
d = math.sqrt(x**2 + y**2)
if d <= 1:
inCircle = inCircle +1
pi = inCircle / numDarts * 4
return pi
def main():
print(montePi(100))
print(montePi(1000))
print(montePi(10000))
print(montePi(100000))
main()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.