为什么打印0而不是5?
我找不到我的逻辑错误?

score = 0

def pass_score(test_string, aScore):
  if re.match(a, test_string):
    increase_score(5, score)
    print (aScore)

def increase_score (aValue, aScore):
  aScore += aValue

最佳答案

没有全局变量的第一种方法返回值:

def increase_score (aValue, aScore):
  aScore += aValue
  return aScore

def pass_score(test_string, aScore):
  if re.match(a, test_string):
    aScore = increase_score(5, aScore)
    print (aScore)


第二种方法,使用global var:

score = 0

def increase_score (aValue):  #don't need to receive score, I've it.
  global score
  score += aValue

def pass_score(test_string):
  global score
  if re.match(a, test_string):
    increase_score(5)
    print (score)


我想您需要两者兼而有之。无论如何,此时您的代码看起来有点脏,混合了本地变量和全局变量。

10-08 11:41