Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 变量不替换函数中的一个参数_Python_Function - Fatal编程技术网

Python 变量不替换函数中的一个参数

Python 变量不替换函数中的一个参数,python,function,Python,Function,我有一个函数,我试图通过它传递一个全局变量。函数的其余部分可以工作,但是当yards1时,需要初始化变量,然后才能使用它。 像这样: import numpy as np userscore = 0 oppscore = 0 yards1=0 distance=0 down=0 def runSuccess(text, x, y, whoScore): global yards1 global distance global down global userscore

我有一个函数,我试图通过它传递一个全局变量。函数的其余部分可以工作,但是当yards1时,需要初始化变量,然后才能使用它。 像这样:

import numpy as np
userscore = 0
oppscore = 0
yards1=0
distance=0
down=0
def runSuccess(text, x, y, whoScore):

  global yards1

  global distance

  global down

  global userscore

  global oppscore

  yardschange1 = np.random.randint(x, y)
  print(text, "Gain of ", yardschange1, "yards!")
  yards1 -= yardschange1
  down += 1
  distance -= yardschange1
  if yards1 <= 0:
      print("TOUCHDOWN!")
      whoScore += 7
      print("")
      print(whoScore)
      print('userteam', ":", userscore, 'oppteam', ":", oppscore)

    runSuccess("blah", 1, 5, userscore)
将numpy导入为np
userscore=0
oppscore=0
码1=0
距离=0
向下=0
def runSuccess(文本、x、y、whoScore):
全球尺度1
全球距离
全球下降
全局用户分数
全球oppscore
yardschange1=np.random.randint(x,y)
打印(文本,“增益”,码更改1,“码!”)
码1-=码变化1
向下+=1
距离-=码变化1

如果要更改userscore的全局值,则在if语句的whoScore+=1行下添加userscore=whoScore。在函数中,您过去的runSuccess()的“userscore”被视为whoScore,这意味着它与userscore不同

似乎您可能想查找局部变量和全局变量之间的差异。我知道局部变量是在函数内部定义的,全局变量是在函数外部定义的。我想我只是不明白为什么我的“废话”会取代文本,1会取代x,5会取代y,但userscore不会取代whoscore这是有道理的。有没有一种方法可以让我使用这个函数来更改userscore或oppscore的值,或者我只需要为每个值创建一个函数。因为,您的解决方案听起来像是函数只会更改userscore的值。感谢您的帮助。@KiddMoney def runSuccess(text,x,y),保留global语句,并在函数内用userscore替换whoScore。@KiddMoney实际上,在global userscore、oppscore之后,您在函数内给user score或oppscore的任何值都将在函数外更改。
import numpy as np
userscore = 0
oppscore = 0
yards1=0
distance=0
down=0
def runSuccess(text, x, y, whoScore):

  global yards1

  global distance

  global down

  global userscore

  global oppscore

  yardschange1 = np.random.randint(x, y)
  print(text, "Gain of ", yardschange1, "yards!")
  yards1 -= yardschange1
  down += 1
  distance -= yardschange1
  if yards1 <= 0:
      print("TOUCHDOWN!")
      whoScore += 7
      print("")
      print(whoScore)
      print('userteam', ":", userscore, 'oppteam', ":", oppscore)

    runSuccess("blah", 1, 5, userscore)