简体   繁体   中英

Name not defined, even with global variable?

So I'm trying to write a function to calculate an estimated value of pi, which is then subtracted from the actual value of pi. However, when I run it, I get an error saying that name 'piCalc' is not defined. Any ideas as to what I did wrong?

import math
import random
def computePI (numThrows):
  circleCount = 0
  for i in range(numThrows):
      xPos = random.uniform (-1.0, 1.0)
      yPos = random.uniform (-1.0, 1.0)
      distance = math.hypot(xPos, yPos)
      if distance < 1:
        circleCount = circleCount + 1  
  piCalc =  4 * (circleCount/numThrows)
  return(piCalc)
def main():
  global piCalc
  throws = int(input(""))
  computePI(throws)
  difference = piCalc - math.pi
  print(piCalc)
  print(difference)
main()

Try something like this, you are getting an error because your value is not global. This way computPI is returning the picalc anyway so you can just snag the return value.

import math
import random
def computePI (numThrows):
  circleCount = 0
  for i in range(numThrows):
      xPos = random.uniform (-1.0, 1.0)
      yPos = random.uniform (-1.0, 1.0)
      distance = math.hypot(xPos, yPos)
      if distance < 1:
        circleCount = circleCount + 1  
  piCalc =  4 * (circleCount/numThrows)
  return(piCalc)
def main():
   throws = int(input(""))
   calc = computePI(throws)
   difference = calc - math.pi
   print(calc)
   print(difference)
main()

You have not declared global in your function

import math
import random
def computePI (numThrows):
  global piCalc
  circleCount = 0
  for i in range(numThrows):
      xPos = random.uniform (-1.0, 1.0)
      yPos = random.uniform (-1.0, 1.0)
      distance = math.hypot(xPos, yPos)
      if distance < 1:
        circleCount = circleCount + 1  
  piCalc =  4 * (circleCount/numThrows)
  return(piCalc)
def main():
  global piCalc
  throws = int(input(""))
  computePI(throws)
  difference = piCalc - math.pi
  print(piCalc)
  print(difference)
main()

initialize the piCalc in the main function and code means piCalc = 0

import math
import random
def computePI (numThrows):
  circleCount = 0
  for i in range(numThrows):
      xPos = random.uniform (-1.0, 1.0)
      yPos = random.uniform (-1.0, 1.0)
      distance = math.hypot(xPos, yPos)
      if distance < 1:
        circleCount = circleCount + 1  
  piCalc =  4 * (circleCount/numThrows)
  return(piCalc)
def main():
  global piCalc 
  piCalc = 0
  throws = int(input(""))
  computePI(throws)
  difference = piCalc - math.pi
  print(difference)
main()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM