1

Using python 3: I have three functions: montePi, isInCircle and main. I need to have the isInCircle called by montePi. The function will work, it just says that isInCircle is not defined. 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()
Carol Chen
  • 897
  • 7
  • 14

1 Answers1

2

Because function isInCircle is defined in montePi, it can be called within montePi but not other functions as it is local. If you define isInCircle outside of montePi then you'll be able to call it from 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;

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()
Carol Chen
  • 897
  • 7
  • 14