Python - 将函数传递给其他函数

时间:2017-09-18 06:59:39

标签: python function

我在将crapsRoll()传递给gameCraps()时遇到问题。当我定义gameCraps()时,我收到错误:

  

从外部范围重新定义名称'crapsRoll'。

在print语句中,我收到一条错误

  

crapsRoll没有任何价值。

import random 

#===========================crapsRoll()===============================
def crapsRoll():
  roll = random.randint(2,12)
  return(roll)

#===========================gameCraps()===============================
def gameCraps(crapsRoll):
  crapsRoll = crapsRoll
  if (crapsRoll == 7 or crapsRoll == 11):
    gameState = 1
  elif (crapsRoll == 2 or crapsRoll == 3 or crapsRoll == 12):
    gameState = 2
  else:
    gameState = 3
  return(gameState)

print(gameCraps())

4 个答案:

答案 0 :(得分:2)

您不需要将其作为参数传递。只需从另一个函数调用它:

has_many through:

答案 1 :(得分:1)

如果你坚持保留这种结构,这将有效:

import random 

#===========================crapsRoll()===============================
def crapsRoll():
  roll = random.randint(2,12)
  return(roll)

#===========================gameCraps()===============================
def gameCraps(crapsRoll):
  crapsRoll = crapsRoll
  if (crapsRoll == 7 or crapsRoll == 11):
    gameState = 1
  elif (crapsRoll == 2 or crapsRoll == 3 or crapsRoll == 12):
    gameState = 2
  else:
    gameState = 3
  return(gameState)

print(gameCraps(crapsRoll()))

您必须将crapsRoll()的返回值传递给gameCraps(<insert int>)或从crapsRoll()内调用gameCraps(),因为所有函数都在同一命名空间中注册。我不知道你的代码的结构,但我宁愿重构它,而不是创建这样的trainwreck。这不是一种糟糕的方式:)。

答案 2 :(得分:0)

#===========================gameCraps()===============================
def gameCraps(crapsRoll):
  print crapsRoll
  if (crapsRoll == 7 or crapsRoll == 11):
    gameState = 1
  elif (crapsRoll == 2 or crapsRoll == 3 or crapsRoll == 12):
    gameState = 2
  else:
    gameState = 3
  return(gameState)

print(gameCraps(crapsRoll()))

这可以通过多种方式完成,但调用函数只需一次就可行

答案 3 :(得分:0)

您正在尝试检查该函数是否具有数字值,但它不需要调用该函数来获取结果。

总结我认为的两个几乎完整的答案:

import random 

#===========================crapsRoll()===============================
def crapsRoll():
  roll = random.randint(2,12)
  return(roll)

#===========================gameCraps()===============================
def gameCraps(rollFunction):
  crapsRollResult = rollFunction()
  if (crapsRollResult  == 7 or crapsRollResult  == 11):
    gameState = 1
  elif (crapsRollResult  == 2 or crapsRollResult  == 3 or crapsRollResult  == 12):
    gameState = 2
  else:
    gameState = 3
  return(gameState)

print(gameCraps(crapsRoll))

这不会使滚动功能与滚动结果混淆,并且不会为每个条件检查重新滚动。