【问题标题】:Name not defined, even with global variable?名称未定义,即使使用全局变量?
【发布时间】:2020-11-28 04:26:51
【问题描述】:

所以我正在尝试编写一个函数来计算 pi 的估计值,然后从 pi 的实际值中减去该估计值。但是,当我运行它时,我收到一条错误消息,提示未定义名称“piCalc”。关于我做错了什么有什么想法吗?

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()

【问题讨论】:

  • 您没有在main() 函数中捕获computePI() 返回的值。请参阅这部分代码computePI(throws)。 -- def main()的第 3 行

标签: python python-3.x nameerror


【解决方案1】:

尝试这样的事情,你会得到一个错误,因为你的价值不是全局的。这样,computPI 无论如何都会返回 piccalc,因此您可以获取返回值。

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()

【讨论】:

  • 你没有捕捉到computePI(throws)的返回值
  • @JoeFerndz 我的意思是你可以这样做而不是只执行一次功能。
【解决方案2】:

你没有在你的函数中声明全局

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()

【讨论】:

    【解决方案3】:

    在main函数和代码中初始化piCalc 表示 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-15
      • 2022-06-14
      • 1970-01-01
      • 1970-01-01
      • 2021-11-29
      • 1970-01-01
      • 2018-05-04
      • 2015-12-22
      相关资源
      最近更新 更多